Code chi tiết không được viết tắt (Dựa vào github tôi gửi có các…
Jump to turn (6)
- User
Code chi tiết không được viết tắt (Dựa vào github tôi gửi có các backend.QLnhatro.sql,code front-end Reactjs) Phát triển tính năng gửi vào email của đại diện phòng có is_representative =1 một dòng hoá đơn thanh toán là bao gồm giá của các dịch vụ trong phòng (dưới là ví dụ về code hoạt động với phòng 101.Tôi muốn code phải tổng quát nhất) 1.cách tính tiền (nếu unit 1 thì sẽ lấy cost của dịch vụ đó nhân với số thành viên trong phòng,nếu unit 3 thì sẽ là giá giữ nguyên ,Còn unit 2 là giá tiền điện và tiền nước sẽ dựa vào chỉ số mình nhập ở trang http://localhost:3000/admin/inpWE nhân với cost tương ứng) ở trang http://localhost:3000/admin/inpWE Giả sử đây là các dịch vụ của phòng id là 1 Thì sẽ gửi email vào đại diện phòng có id_representative = 1 của phòng đó
3.Nội dung email được gửi là Thanh toán tiền phòng 101(có id_room 1) tháng xxxx: Bao gồm Tiền nước : 4000 x a =4000a (a là chỉ số tiền nước nhập ở trang gửi email) Tiền điện: 2622 x b = 2622b (b là chỉ số tiền điện nhập ở trang gửi email) Tiền Wifi: 80000 Tiền Mì xào: 30000 x c =30000c (c là số người tỏng phòng vì có unit là 1) Total = 4000a+2622b+80000+30000c (VNĐ) Xin mời thanh toán qua link VNPay sau: {Link}
Đây chỉ là mẫu @PostMapping("/send-email") public ResponseEntity sendEmail( @RequestParam int roomId, @RequestParam double waterIndex, @RequestParam double electricityIndex, @RequestParam int memberCount ) { // Lấy danh sách dịch vụ của phòng List services = roomServicesRepository.findByRoomId(roomId);
// Tính tiền cho từng dịch vụ double total = 0; StringBuilder body = new StringBuilder(); for (RoomServices service : services) { double price = calculatePrice(service, waterIndex, electricityIndex, memberCount); total += price; body.append(service.getName()).append(": ").append(price).append("\n"); }
// Gửi email cho đại diện phòng String to = "địa chỉ email của đại diện phòng"; String subject = "Thanh toán tiền phòng " + roomId; String emailBody = "Thanh toán tiền phòng " + roomId + " tháng " + LocalDate.now().getMonth() + ":\n" + "Bao gồm:\n" + body.toString() + "Total: " + total + " VNĐ"; emailService.sendEmail(to, subject, emailBody);
return ResponseEntity.ok("Email đã được gửi thành công!"); }
private double calculatePrice(RoomServices service, double waterIndex, double electricityIndex, int memberCount) { switch (service.getUnit()) { case 1: return service.getCost() * memberCount; case 2: if (service.getName().contains("Tiền nước")) { return service.getCost() * waterIndex; } else if (service.getName().contains("Tiền điện")) { return service.getCost() * electricityIndex; } break; case 3: return service.getCost(); } return 0; } package com.example.QuanLyPhongTro.controller;
import com.example.QuanLyPhongTro.config.VNPayConfig; import com.example.QuanLyPhongTro.models.Rooms; import com.example.QuanLyPhongTro.payload.InvoiceRequest; import com.example.QuanLyPhongTro.services.EmailService; import com.example.QuanLyPhongTro.services.RoomsService; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;
import com.example.QuanLyPhongTro.models.Invoices; import com.example.QuanLyPhongTro.services.InvoicesService;
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*;
@RestController @RequestMapping("/invoices") public class InvoicesController {
}
@PostMapping("/send-email") public ResponseEntity sendEmail( @RequestParam int roomId, @RequestParam double waterIndex, @RequestParam double electricityIndex, @RequestParam int memberCount ) { // Lấy danh sách dịch vụ của phòng List services = roomServicesRepository.findByRoomId(roomId);
// Tính tiền cho từng dịch vụ
double total = 0;
StringBuilder body = new StringBuilder();
for (RoomServices service : services) {
double price = calculatePrice(service, waterIndex, electricityIndex, memberCount);
total += price;
body.append(service.getName()).append(": ").append(price).append("\n");
}
// Gửi email cho đại diện phòng
String to = "địa chỉ email của đại diện phòng";
String subject = "Thanh toán tiền phòng " + roomId;
String emailBody = "Thanh toán tiền phòng " + roomId + " tháng " + LocalDate.now().getMonth() + ":\n" +
"Bao gồm:\n" +
body.toString() +
"Total: " + total + " VNĐ";
emailService.sendEmail(to, subject, emailBody);
return ResponseEntity.ok("Email đã được gửi thành công!");
}
private double calculatePrice(RoomServices service, double waterIndex, double electricityIndex, int memberCount) { switch (service.getUnit()) { case 1: return service.getCost() * memberCount; case 2: if (service.getName().contains("Tiền nước")) { return service.getCost() * waterIndex; } else if (service.getName().contains("Tiền điện")) { return service.getCost() * electricityIndex; } break; case 3: return service.getCost(); } return 0; } package com.example.QuanLyPhongTro.controller;
import com.example.QuanLyPhongTro.config.VNPayConfig; import com.example.QuanLyPhongTro.models.Rooms; import com.example.QuanLyPhongTro.payload.InvoiceRequest; import com.example.QuanLyPhongTro.services.EmailService; import com.example.QuanLyPhongTro.services.RoomsService; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;
import com.example.QuanLyPhongTro.models.Invoices; import com.example.QuanLyPhongTro.services.InvoicesService;
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*;
@RestController @RequestMapping("/invoices") public class InvoicesController {
}
Tôi muốn bạn gửi 1 link thanh toán VNPay ở dưới đoạn {Link của email} để thanh toán tổng số tiền cần thanh toán khi thanh toán xong hoá đơn sẽ tự thay đổi trạng thái 1 tức là đã thanh toán đây là đoạn code xử lí với thanh toán và trang nhập số điện nước và gửi email hãy nhúng api vào đó cho hợp lí biết (khi từ trang room click vào ô thanh toán nằm ở room nó sẽ hiện ra trang InputWaterElectric kèm số id_room rồi) package com.example.QuanLyPhongTro.controller;
import com.example.QuanLyPhongTro.config.VNPayConfig; import com.example.QuanLyPhongTro.models.Rooms; import com.example.QuanLyPhongTro.payload.InvoiceRequest; import com.example.QuanLyPhongTro.services.EmailService; import com.example.QuanLyPhongTro.services.RoomsService; import jakarta.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;
import com.example.QuanLyPhongTro.models.Invoices; import com.example.QuanLyPhongTro.services.InvoicesService;
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.*;
@RestController @RequestMapping("/invoices") public class InvoicesController {
package com.example.QuanLyPhongTro.controller;
import com.example.QuanLyPhongTro.config.VNPayConfig;
import com.example.QuanLyPhongTro.models.Invoices;
import com.example.QuanLyPhongTro.models.RoomServices;
import com.example.QuanLyPhongTro.models.Rooms;
import com.example.QuanLyPhongTro.models.Users;
import com.example.QuanLyPhongTro.payload.InvoiceRequest;
import com.example.QuanLyPhongTro.repositories.InvoicesRepository;
import com.example.QuanLyPhongTro.repositories.RoomServicesRepository;
import com.example.QuanLyPhongTro.repositories.UsersRepository;
import com.example.QuanLyPhongTro.services.EmailService;
import com.example.QuanLyPhongTro.services.InvoicesService;
import com.example.QuanLyPhongTro.services.RoomsService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
@RestController
@RequestMapping("/invoices")
public class InvoicesController {
// ... (các khai báo khác)
@Autowired
private InvoicesRepository invoicesRepository;
@PostMapping("/send-email")
public ResponseEntity<String> sendEmail(
@RequestParam int roomId,
@RequestParam double waterIndex,
@RequestParam double electricityIndex,
HttpServletRequest req // Thêm HttpServletRequest để lấy IP
) {
// ... (logic tính toán như trước)
// Tạo hóa đơn trước khi gửi email
Invoices invoice = new Invoices();
invoice.setTotal(total);
invoice.setCreatedAt(new Date());
invoice.setRoom(roomsService.getRoomById(roomId));
invoice.setStatus(0); // Chưa thanh toán
invoicesRepository.save(invoice);
// Tạo link thanh toán VNPay
String paymentLink = createPaymentLink(invoice, req);
// Tạo nội dung email với link thanh toán
String emailBody = // ... (nội dung email như trước)
"Vui lòng thanh toán qua link VNPay sau: " + paymentLink;
emailService.sendEmail(to, subject, emailBody);
return ResponseEntity.ok("Email đã được gửi thành công!");
}
// ... (các phương thức khác)
}
Hãy viết đầy đủ ra không được viết tắt những trang đó Đồng thời ở .env tôi đã khai báo REACT_APP_API_BASE_URL=http://localhost:8080 nên là tôi muốn bạn nhúng nó vào api luôn
package com.example.QuanLyPhongTro.controller;
// ... (các import khác)
@RestController
@RequestMapping("/invoices")
public class InvoicesController {
// ... (các khai báo khác)
@PostMapping("/send-email")
public ResponseEntity<String> sendEmail(
@RequestParam int roomId,
@RequestParam double waterIndex,
@RequestParam double electricityIndex,
HttpServletRequest req
) {
// ... (logic tính toán, tạo hóa đơn như trước)
String paymentLink = createPaymentLink(invoice, req);
// Tạo nội dung email với link thanh toán
String emailBody = "Thanh toán tiền phòng " + room.getRoomNumber() + " tháng " + LocalDate.now().getMonthValue() + ":\n" +
"Bao gồm:\n" +
body.toString() +
"Total: " + String.format("%.0f", total) + " VNĐ\n" +
"Vui lòng thanh toán qua link VNPay sau: " + paymentLink;
emailService.sendEmail(to, subject, emailBody);
return ResponseEntity.ok("Email đã được gửi thành công!");
}
// ... (các phương thức khác, bao gồm createPaymentLink và transaction)
}
Tiếp tục
Vui lòng cung cấp thêm thông tin hoặc câu hỏi. Tôi cần biết bạn muốn tiếp tục với điều gì để có thể hỗ trợ bạn tốt nhất. Ví dụ:
Tôi sẵn sàng hỗ trợ bạn tiếp tục phát triển ứng dụng.
Tiếp tục
Tôi cần thêm thông tin từ bạn để có thể tiếp tục. Bạn muốn làm gì tiếp theo? Một số gợi ý:
InputWaterElectric không? Ví dụ: thêm thông báo thành công/thất bại, hiển thị danh sách dịch vụ, v.v.Hãy cho tôi biết bạn muốn làm gì tiếp theo để tôi có thể hỗ trợ bạn.
Tiểp tục
Tôi vẫn cần thêm thông tin từ bạn để có thể tiếp tục. Bạn có thể cho tôi biết bạn đang gặp khó khăn ở bước nào, hoặc bạn muốn cải thiện/thêm tính năng gì cho ứng dụng không?
Một số việc bạn có thể muốn làm tiếp theo:
Hãy cho tôi biết cụ thể bạn muốn làm gì để tôi có thể hỗ trợ bạn tốt hơn.
@Autowired
private InvoicesService _invoicesService;
@Autowired
private RoomsService _roomsService;
@Autowired(required = false)
private EmailService emailService;
// Lấy tất cả hóa đơn
@GetMapping("/all") // Thay đổi đường dẫn để tránh xung đột
public List<Invoices> getAllInvoices() {
return _invoicesService.getAllInvoices();
}
// Lấy hóa đơn theo ID
@GetMapping("/{id}")
public ResponseEntity<Invoices> getInvoiceById(@PathVariable int id) {
Invoices invoice = _invoicesService.getInvoiceById(id);
if (invoice != null) {
return ResponseEntity.ok(invoice);
}
return ResponseEntity.notFound().build();
}
// Lấy hóa đơn với phân trang
@GetMapping("") // Giữ nguyên để trả về danh sách hóa đơn với phân trang
public Page<Invoices> getInvoices(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return _invoicesService.getInvoices(page, size);
}
// Thêm hóa đơn mới
@PostMapping("")
public Invoices addInvoice(@RequestBody Invoices invoice) {
return _invoicesService.addInvoice(invoice);
}
// Cập nhật hóa đơn theo ID
@PutMapping("/{id}")
public ResponseEntity<Invoices> updateInvoice(@PathVariable int id, @RequestBody Invoices invoiceDetails) {
Invoices updatedInvoice = _invoicesService.updateInvoice(id, invoiceDetails);
if (updatedInvoice != null) {
return ResponseEntity.ok(updatedInvoice);
}
return ResponseEntity.notFound().build();
}
// Xóa hóa đơn theo ID
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteInvoice(@PathVariable int id) {
if (_invoicesService.deleteInvoice(id)) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}
@PostMapping("/create")
public ResponseEntity<String> createInvoice(@RequestBody InvoiceRequest request, HttpServletRequest req) {
// Tạo hóa đơn mới với thông tin từ yêu cầu
Rooms room = _roomsService.getRoomById(request.getRoomId());
if (room == null) {
return ResponseEntity.badRequest().body("Phòng không tồn tại.");
}
Invoices invoice = _invoicesService.createInvoice(request.getTotal(), room); // Tạo hóa đơn
String paymentLink = createPaymentLink(invoice, req); // Tạo link thanh toán
// Tạo thông điệp gửi tới người dùng
String message = request.getMessage() + "\nVui lòng thanh toán hóa đơn của bạn tại: " + paymentLink;
emailService.sendEmail(request.getEmail(), "Hóa Đơn Thanh Toán", message); // Gửi email
return ResponseEntity.ok("Hóa đơn đã được tạo và gửi đến email của bạn.");
}
private String createPaymentLink(Invoices invoice, HttpServletRequest req) {
long amount = (long)(invoice.getTotal() * 100); // Chuyển đổi sang đơn vị tiền tệ (VND)
String vnp_TxnRef = VNPayConfig.getRandomNumber(8); // Tạo số tham chiếu giao dịch
String vnp_IpAddr = VNPayConfig.getIpAddress(req); // Địa chỉ IP của người dùng
String vnp_OrderInfo = Base64.getEncoder().encodeToString((invoice.getId() + "").getBytes()); // Thông tin đơn hàng
// Thiết lập các tham số cần thiết
Map<String, String> vnp_Params = new HashMap<>();
vnp_Params.put("vnp_Version", "2.1.0"); // Phiên bản API VNPay
vnp_Params.put("vnp_Command", "pay"); // Lệnh thanh toán
vnp_Params.put("vnp_TmnCode", VNPayConfig.vnp_TmnCode); // Mã đối tác
vnp_Params.put("vnp_Amount", String.valueOf(amount)); // Số tiền
vnp_Params.put("vnp_CurrCode", "VND"); // Đơn vị tiền tệ
vnp_Params.put("vnp_TxnRef", vnp_TxnRef); // Số tham chiếu giao dịch
vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo); // Thông tin đơn hàng
vnp_Params.put("vnp_ReturnUrl", VNPayConfig.vnp_ReturnUrl); // URL trả về sau khi thanh toán
vnp_Params.put("vnp_IpAddr", vnp_IpAddr); // Địa chỉ IP của người dùng
// Tạo thời gian tạo và thời gian hết hạn (nếu cần)
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String vnp_CreateDate = formatter.format(new Date());
vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
// Tạo chuỗi hash cho bảo mật
List<String> fieldNames = new ArrayList<>(vnp_Params.keySet());
Collections.sort(fieldNames);
StringBuilder hashData = new StringBuilder();
for (String fieldName : fieldNames) {
String fieldValue = vnp_Params.get(fieldName);
if (fieldValue != null && fieldValue.length() > 0) {
hashData.append(fieldName).append("=").append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII));
hashData.append("&");
}
}
String vnp_SecureHash = VNPayConfig.hmacSHA512(VNPayConfig.secretKey, hashData.toString());
String queryUrl = VNPayConfig.vnp_PayUrl + "?" + hashData.toString() + "vnp_SecureHash=" + vnp_SecureHash;
return queryUrl; // Trả về URL thanh toán đầy đủ
}
@GetMapping("/payment_infor")
public ResponseEntity<?> transaction(
HttpServletRequest request,
@RequestParam(value = "vnp_TxnRef") String txnRef,
@RequestParam(value = "vnp_ResponseCode") String responseCode,
@RequestParam(value = "vnp_Amount") String amount,
@RequestParam(value = "vnp_OrderInfo") String orderInfo
) {
// Giải mã thông tin đơn hàng
String decodedOrderInfo = new String(Base64.getDecoder().decode(orderInfo));
// Tách thông tin cần thiết
String[] orderDetails = decodedOrderInfo.split("\\|");
int invoiceId = Integer.parseInt(orderDetails[0]); // Lấy ID hóa đơn từ thông tin
// Kiểm tra mã phản hồi
if ("00".equals(responseCode)) {
// Thanh toán thành công, cập nhật trạng thái hóa đơn
Invoices invoice = _invoicesService.getInvoiceById(invoiceId);
if (invoice != null) {
invoice.setStatus(1); // 1: đã thanh toán
_invoicesService.updateInvoice(invoice); // Cập nhật hóa đơn
}
return ResponseEntity.status(HttpStatus.OK).body("Thanh toán thành công!");
} else {
// Thanh toán không thành công
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Thanh toán không thành công!");
}
}
@Autowired
private InvoicesService _invoicesService;
@Autowired
private RoomsService _roomsService;
@Autowired(required = false)
private EmailService emailService;
// Lấy tất cả hóa đơn
@GetMapping("/all") // Thay đổi đường dẫn để tránh xung đột
public List<Invoices> getAllInvoices() {
return _invoicesService.getAllInvoices();
}
// Lấy hóa đơn theo ID
@GetMapping("/{id}")
public ResponseEntity<Invoices> getInvoiceById(@PathVariable int id) {
Invoices invoice = _invoicesService.getInvoiceById(id);
if (invoice != null) {
return ResponseEntity.ok(invoice);
}
return ResponseEntity.notFound().build();
}
// Lấy hóa đơn với phân trang
@GetMapping("") // Giữ nguyên để trả về danh sách hóa đơn với phân trang
public Page<Invoices> getInvoices(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return _invoicesService.getInvoices(page, size);
}
// Thêm hóa đơn mới
@PostMapping("")
public Invoices addInvoice(@RequestBody Invoices invoice) {
return _invoicesService.addInvoice(invoice);
}
// Cập nhật hóa đơn theo ID
@PutMapping("/{id}")
public ResponseEntity<Invoices> updateInvoice(@PathVariable int id, @RequestBody Invoices invoiceDetails) {
Invoices updatedInvoice = _invoicesService.updateInvoice(id, invoiceDetails);
if (updatedInvoice != null) {
return ResponseEntity.ok(updatedInvoice);
}
return ResponseEntity.notFound().build();
}
// Xóa hóa đơn theo ID
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteInvoice(@PathVariable int id) {
if (_invoicesService.deleteInvoice(id)) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}
@PostMapping("/create")
public ResponseEntity<String> createInvoice(@RequestBody InvoiceRequest request, HttpServletRequest req) {
// Tạo hóa đơn mới với thông tin từ yêu cầu
Rooms room = _roomsService.getRoomById(request.getRoomId());
if (room == null) {
return ResponseEntity.badRequest().body("Phòng không tồn tại.");
}
Invoices invoice = _invoicesService.createInvoice(request.getTotal(), room); // Tạo hóa đơn
String paymentLink = createPaymentLink(invoice, req); // Tạo link thanh toán
// Tạo thông điệp gửi tới người dùng
String message = request.getMessage() + "\nVui lòng thanh toán hóa đơn của bạn tại: " + paymentLink;
emailService.sendEmail(request.getEmail(), "Hóa Đơn Thanh Toán", message); // Gửi email
return ResponseEntity.ok("Hóa đơn đã được tạo và gửi đến email của bạn.");
}
private String createPaymentLink(Invoices invoice, HttpServletRequest req) {
long amount = (long)(invoice.getTotal() * 100); // Chuyển đổi sang đơn vị tiền tệ (VND)
String vnp_TxnRef = VNPayConfig.getRandomNumber(8); // Tạo số tham chiếu giao dịch
String vnp_IpAddr = VNPayConfig.getIpAddress(req); // Địa chỉ IP của người dùng
String vnp_OrderInfo = Base64.getEncoder().encodeToString((invoice.getId() + "").getBytes()); // Thông tin đơn hàng
// Thiết lập các tham số cần thiết
Map<String, String> vnp_Params = new HashMap<>();
vnp_Params.put("vnp_Version", "2.1.0"); // Phiên bản API VNPay
vnp_Params.put("vnp_Command", "pay"); // Lệnh thanh toán
vnp_Params.put("vnp_TmnCode", VNPayConfig.vnp_TmnCode); // Mã đối tác
vnp_Params.put("vnp_Amount", String.valueOf(amount)); // Số tiền
vnp_Params.put("vnp_CurrCode", "VND"); // Đơn vị tiền tệ
vnp_Params.put("vnp_TxnRef", vnp_TxnRef); // Số tham chiếu giao dịch
vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo); // Thông tin đơn hàng
vnp_Params.put("vnp_ReturnUrl", VNPayConfig.vnp_ReturnUrl); // URL trả về sau khi thanh toán
vnp_Params.put("vnp_IpAddr", vnp_IpAddr); // Địa chỉ IP của người dùng
// Tạo thời gian tạo và thời gian hết hạn (nếu cần)
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String vnp_CreateDate = formatter.format(new Date());
vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
// Tạo chuỗi hash cho bảo mật
List<String> fieldNames = new ArrayList<>(vnp_Params.keySet());
Collections.sort(fieldNames);
StringBuilder hashData = new StringBuilder();
for (String fieldName : fieldNames) {
String fieldValue = vnp_Params.get(fieldName);
if (fieldValue != null && fieldValue.length() > 0) {
hashData.append(fieldName).append("=").append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII));
hashData.append("&");
}
}
String vnp_SecureHash = VNPayConfig.hmacSHA512(VNPayConfig.secretKey, hashData.toString());
String queryUrl = VNPayConfig.vnp_PayUrl + "?" + hashData.toString() + "vnp_SecureHash=" + vnp_SecureHash;
return queryUrl; // Trả về URL thanh toán đầy đủ
}
@GetMapping("/payment_infor")
public ResponseEntity<?> transaction(
HttpServletRequest request,
@RequestParam(value = "vnp_TxnRef") String txnRef,
@RequestParam(value = "vnp_ResponseCode") String responseCode,
@RequestParam(value = "vnp_Amount") String amount,
@RequestParam(value = "vnp_OrderInfo") String orderInfo
) {
// Giải mã thông tin đơn hàng
String decodedOrderInfo = new String(Base64.getDecoder().decode(orderInfo));
// Tách thông tin cần thiết
String[] orderDetails = decodedOrderInfo.split("\\|");
int invoiceId = Integer.parseInt(orderDetails[0]); // Lấy ID hóa đơn từ thông tin
// Kiểm tra mã phản hồi
if ("00".equals(responseCode)) {
// Thanh toán thành công, cập nhật trạng thái hóa đơn
Invoices invoice = _invoicesService.getInvoiceById(invoiceId);
if (invoice != null) {
invoice.setStatus(1); // 1: đã thanh toán
_invoicesService.updateInvoice(invoice); // Cập nhật hóa đơn
}
return ResponseEntity.status(HttpStatus.OK).body("Thanh toán thành công!");
} else {
// Thanh toán không thành công
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Thanh toán không thành công!");
}
}
package com.example.QuanLyPhongTro.controller;
import com.example.QuanLyPhongTro.config.VNPayConfig;
import com.example.QuanLyPhongTro.models.Invoices;
import com.example.QuanLyPhongTro.models.RoomServices;
import com.example.QuanLyPhongTro.models.Rooms;
import com.example.QuanLyPhongTro.models.Users;
import com.example.QuanLyPhongTro.payload.InvoiceRequest;
import com.example.QuanLyPhongTro.repositories.RoomServicesRepository;
import com.example.QuanLyPhongTro.repositories.UsersRepository;
import com.example.QuanLyPhongTro.services.EmailService;
import com.example.QuanLyPhongTro.services.InvoicesService;
import com.example.QuanLyPhongTro.services.RoomsService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
@RestController
@RequestMapping("/invoices")
public class InvoicesController {
@Autowired
private InvoicesService invoicesService;
@Autowired
private RoomsService roomsService;
@Autowired
private EmailService emailService;
@Autowired
private RoomServicesRepository roomServicesRepository;
@Autowired
private UsersRepository usersRepository;
// Các phương thức khác của controller
@PostMapping("/send-email")
public ResponseEntity<String> sendEmail(
@RequestParam int roomId,
@RequestParam double waterIndex,
@RequestParam double electricityIndex
) {
// Lấy danh sách dịch vụ của phòng
List<RoomServices> services = roomServicesRepository.findByRoomId(roomId);
// Lấy thông tin phòng
Rooms room = roomsService.getRoomById(roomId);
if (room == null) {
return ResponseEntity.badRequest().body("Phòng không tồn tại.");
}
// Lấy số lượng thành viên trong phòng từ thông tin phòng
int memberCount = room.getMaxOccupants();
// Tính tiền cho từng dịch vụ
double total = 0;
StringBuilder body = new StringBuilder();
for (RoomServices service : services) {
double price = calculatePrice(service, waterIndex, electricityIndex, memberCount);
total += price;
body.append(service.getName()).append(": ").append(String.format("%.0f", service.getCost())).append(" x ").append(getMultiplier(service, waterIndex, electricityIndex, memberCount)).append(" = ").append(String.format("%.0f", price)).append(" VNĐ\n");
}
// Lấy email của đại diện phòng
Optional<Users> representative = usersRepository.findRepresentativeByRoomId(roomId);
if (representative.isEmpty()) {
return ResponseEntity.badRequest().body("Không tìm thấy đại diện phòng.");
}
String to = representative.get().getEmail();
// Tạo nội dung email
String subject = "Thanh toán tiền phòng " + room.getRoomNumber();
String emailBody = "Thanh toán tiền phòng " + room.getRoomNumber() + " tháng " + LocalDate.now().getMonthValue() + ":\n" +
"Bao gồm:\n" +
body.toString() +
"Total: " + String.format("%.0f", total) + " VNĐ\n" +
"Vui lòng thanh toán qua link VNPay sau: {Link}"; // Thêm link thanh toán ở đây
emailService.sendEmail(to, subject, emailBody);
return ResponseEntity.ok("Email đã được gửi thành công!");
}
private double calculatePrice(RoomServices service, double waterIndex, double electricityIndex, int memberCount) {
switch (service.getUnit()) {
case 1:
return service.getCost() * memberCount;
case 2:
if (service.getName().contains("Tiền nước")) {
return service.getCost() * waterIndex;
} else if (service.getName().contains("Tiền điện")) {
return service.getCost() * electricityIndex;
}
break;
case 3:
return service.getCost();
}
return 0;
}
private String getMultiplier(RoomServices service, double waterIndex, double electricityIndex, int memberCount) {
switch (service.getUnit()) {
case 1:
return String.valueOf(memberCount);
case 2:
if (service.getName().contains("Tiền nước")) {
return String.valueOf(waterIndex);
} else if (service.getName().contains("Tiền điện")) {
return String.valueOf(electricityIndex);
}
break;
case 3:
return "1"; // Giá cố định
}
return "";
}
}
Những thay đổi chính:
room.getMaxOccupants() thay vì truyền vào như một tham số.usersRepository.findRepresentativeByRoomId(roomId) để lấy email của người đại diện dựa trên roomId. Bạn cần triển khai phương thức này trong UsersRepository. Ví dụ:// Trong UsersRepository.java
@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
// ... các phương thức khác
@Query("SELECT u FROM Users u JOIN u.rooms r WHERE r.id = :roomId AND u.isRepresentative = 1")
Optional<Users> findRepresentativeByRoomId(@Param("roomId") int roomId);
}
String.format("%.0f", price) để hiển thị giá tiền mà không có phần thập phân.{Link} vào nội dung email. Bạn cần thay thế bằng logic tạo link thanh toán VNPay thực tế. Bạn có thể sử dụng phương thức createPaymentLink hiện có của bạn và gọi nó trong phương thức sendEmail này, sau đó chèn link vào emailBody.Lưu ý:
java.time nếu bạn chưa có.Users và Rooms để xác định đại diện phòng. Hãy điều chỉnh code theo cấu trúc database của bạn.{Link} trong email body bằng link thanh toán thực tế.Với những thay đổi này, code của bạn sẽ tổng quát hơn và hoạt động chính xác cho mọi phòng, tự động lấy thông tin cần thiết và gửi email đến đúng người đại diện.
@Autowired
private InvoicesService _invoicesService;
@Autowired
private RoomsService _roomsService;
@Autowired(required = false)
private EmailService emailService;
// Lấy tất cả hóa đơn
@GetMapping("/all") // Thay đổi đường dẫn để tránh xung đột
public List<Invoices> getAllInvoices() {
return _invoicesService.getAllInvoices();
}
// Lấy hóa đơn theo ID
@GetMapping("/{id}")
public ResponseEntity<Invoices> getInvoiceById(@PathVariable int id) {
Invoices invoice = _invoicesService.getInvoiceById(id);
if (invoice != null) {
return ResponseEntity.ok(invoice);
}
return ResponseEntity.notFound().build();
}
// Lấy hóa đơn với phân trang
@GetMapping("") // Giữ nguyên để trả về danh sách hóa đơn với phân trang
public Page<Invoices> getInvoices(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return _invoicesService.getInvoices(page, size);
}
// Thêm hóa đơn mới
@PostMapping("")
public Invoices addInvoice(@RequestBody Invoices invoice) {
return _invoicesService.addInvoice(invoice);
}
// Cập nhật hóa đơn theo ID
@PutMapping("/{id}")
public ResponseEntity<Invoices> updateInvoice(@PathVariable int id, @RequestBody Invoices invoiceDetails) {
Invoices updatedInvoice = _invoicesService.updateInvoice(id, invoiceDetails);
if (updatedInvoice != null) {
return ResponseEntity.ok(updatedInvoice);
}
return ResponseEntity.notFound().build();
}
// Xóa hóa đơn theo ID
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteInvoice(@PathVariable int id) {
if (_invoicesService.deleteInvoice(id)) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}
@PostMapping("/create")
public ResponseEntity<String> createInvoice(@RequestBody InvoiceRequest request, HttpServletRequest req) {
// Tạo hóa đơn mới với thông tin từ yêu cầu
Rooms room = _roomsService.getRoomById(request.getRoomId());
if (room == null) {
return ResponseEntity.badRequest().body("Phòng không tồn tại.");
}
Invoices invoice = _invoicesService.createInvoice(request.getTotal(), room); // Tạo hóa đơn
String paymentLink = createPaymentLink(invoice, req); // Tạo link thanh toán
// Tạo thông điệp gửi tới người dùng
String message = request.getMessage() + "\nVui lòng thanh toán hóa đơn của bạn tại: " + paymentLink;
emailService.sendEmail(request.getEmail(), "Hóa Đơn Thanh Toán", message); // Gửi email
return ResponseEntity.ok("Hóa đơn đã được tạo và gửi đến email của bạn.");
}
private String createPaymentLink(Invoices invoice, HttpServletRequest req) {
long amount = (long)(invoice.getTotal() * 100); // Chuyển đổi sang đơn vị tiền tệ (VND)
String vnp_TxnRef = VNPayConfig.getRandomNumber(8); // Tạo số tham chiếu giao dịch
String vnp_IpAddr = VNPayConfig.getIpAddress(req); // Địa chỉ IP của người dùng
String vnp_OrderInfo = Base64.getEncoder().encodeToString((invoice.getId() + "").getBytes()); // Thông tin đơn hàng
// Thiết lập các tham số cần thiết
Map<String, String> vnp_Params = new HashMap<>();
vnp_Params.put("vnp_Version", "2.1.0"); // Phiên bản API VNPay
vnp_Params.put("vnp_Command", "pay"); // Lệnh thanh toán
vnp_Params.put("vnp_TmnCode", VNPayConfig.vnp_TmnCode); // Mã đối tác
vnp_Params.put("vnp_Amount", String.valueOf(amount)); // Số tiền
vnp_Params.put("vnp_CurrCode", "VND"); // Đơn vị tiền tệ
vnp_Params.put("vnp_TxnRef", vnp_TxnRef); // Số tham chiếu giao dịch
vnp_Params.put("vnp_OrderInfo", vnp_OrderInfo); // Thông tin đơn hàng
vnp_Params.put("vnp_ReturnUrl", VNPayConfig.vnp_ReturnUrl); // URL trả về sau khi thanh toán
vnp_Params.put("vnp_IpAddr", vnp_IpAddr); // Địa chỉ IP của người dùng
// Tạo thời gian tạo và thời gian hết hạn (nếu cần)
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String vnp_CreateDate = formatter.format(new Date());
vnp_Params.put("vnp_CreateDate", vnp_CreateDate);
// Tạo chuỗi hash cho bảo mật
List<String> fieldNames = new ArrayList<>(vnp_Params.keySet());
Collections.sort(fieldNames);
StringBuilder hashData = new StringBuilder();
for (String fieldName : fieldNames) {
String fieldValue = vnp_Params.get(fieldName);
if (fieldValue != null && fieldValue.length() > 0) {
hashData.append(fieldName).append("=").append(URLEncoder.encode(fieldValue, StandardCharsets.US_ASCII));
hashData.append("&");
}
}
String vnp_SecureHash = VNPayConfig.hmacSHA512(VNPayConfig.secretKey, hashData.toString());
String queryUrl = VNPayConfig.vnp_PayUrl + "?" + hashData.toString() + "vnp_SecureHash=" + vnp_SecureHash;
return queryUrl; // Trả về URL thanh toán đầy đủ
}
@GetMapping("/payment_infor")
public ResponseEntity<?> transaction(
HttpServletRequest request,
@RequestParam(value = "vnp_TxnRef") String txnRef,
@RequestParam(value = "vnp_ResponseCode") String responseCode,
@RequestParam(value = "vnp_Amount") String amount,
@RequestParam(value = "vnp_OrderInfo") String orderInfo
) {
// Giải mã thông tin đơn hàng
String decodedOrderInfo = new String(Base64.getDecoder().decode(orderInfo));
// Tách thông tin cần thiết
String[] orderDetails = decodedOrderInfo.split("\\|");
int invoiceId = Integer.parseInt(orderDetails[0]); // Lấy ID hóa đơn từ thông tin
// Kiểm tra mã phản hồi
if ("00".equals(responseCode)) {
// Thanh toán thành công, cập nhật trạng thái hóa đơn
Invoices invoice = _invoicesService.getInvoiceById(invoiceId);
if (invoice != null) {
invoice.setStatus(1); // 1: đã thanh toán
_invoicesService.updateInvoice(invoice); // Cập nhật hóa đơn
}
return ResponseEntity.status(HttpStatus.OK).body("Thanh toán thành công!");
} else {
// Thanh toán không thành công
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Thanh toán không thành công!");
}
}
} import React, { useState } from 'react'; import classNames from 'classnames/bind'; import styles from './InputWaterElectric.module.scss'; // Assuming you are using SCSS modules
const cx = classNames.bind(styles); // Create a className function bound to styles
function InputWaterElectric() { const [electricityReading, setElectricityReading] = useState(''); const [waterReading, setWaterReading] = useState(''); const [readings, setReadings] = useState([]);
const handleSubmit = (e) => {
};
return (
<div className={cx('meter-reading')}>
<div className={cx('meter-reading__form')}>
<h2>Nhập Chỉ Số Điện Và Nước</h2>
<form onSubmit={handleSubmit}>
<div className={cx('form-group')}>
<label>Chỉ Số Điện (kWh)</label>
<input
type="number"
value={electricityReading}
onChange={(e) => setElectricityReading(e.target.value)}
placeholder="Nhập chỉ số điện"
required
/>
</div>
<div className={cx('form-group')}>
<label>Chỉ Số Nước (m³)</label>
<input
type="number"
value={waterReading}
onChange={(e) => setWaterReading(e.target.value)}
placeholder="Nhập chỉ số nước"
required
/>
</div>
<button type="submit">Gửi Email</button>
</form>
</div>
</div>
);
}
export default InputWaterElectric;
import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import styles from './InputWaterElectric.module.scss';
import { useParams } from 'react-router-dom';
import axios from 'axios';
const cx = classNames.bind(styles);
function InputWaterElectric() {
const { roomId } = useParams(); // Lấy roomId từ URL
const [electricityReading, setElectricityReading] = useState('');
const [waterReading, setWaterReading] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`/invoices/send-email`, {
roomId: parseInt(roomId), // Chuyển đổi roomId thành số nguyên
waterIndex: parseFloat(waterReading),
electricityIndex: parseFloat(electricityReading)
});
if (response.status === 200) {
// Xử lý khi gửi email thành công (ví dụ: hiển thị thông báo)
alert("Email đã được gửi thành công!");
// Chuyển hướng hoặc reset form
} else {
// Xử lý khi gửi email thất bại
alert("Gửi email thất bại!");
}
} catch (error) {
console.error("Lỗi khi gửi email:", error);
alert("Gửi email thất bại!");
}
};
return (
// ... (JSX như trước)
);
}
export default InputWaterElectric;
Thay đổi chính:
Invoices mới và lưu nó vào database trước khi gửi email. Điều này đảm bảo rằng luôn có một hóa đơn tương ứng với link thanh toán.HttpServletRequest: Phương thức sendEmail bây giờ nhận HttpServletRequest làm tham số để có thể tạo link thanh toán VNPay.createPaymentLink và được chèn vào emailBody.useParams trong React: Component InputWaterElectric giờ sử dụng useParams hook của React Router để lấy roomId từ URL. Đảm bảo bạn đã thiết lập routing chính xác để truyền roomId vào URL.roomId thành số: Trong component React, roomId được chuyển đổi thành số nguyên bằng parseInt() trước khi gửi request.Cấu hình vnp_ReturnUrl:
Bạn cần chắc chắn rằng vnp_ReturnUrl trong VNPayConfig được cấu hình để trỏ đến một endpoint trên backend của bạn, nơi bạn sẽ xử lý phản hồi từ VNPay sau khi thanh toán hoàn tất. Endpoint này sẽ nhận vnp_OrderInfo (chứa invoiceId), kiểm tra trạng thái thanh toán và cập nhật trạng thái của hóa đơn trong database. Bạn đã có endpoint /payment_infor để làm việc này.
Với những thay đổi này, người dùng sẽ nhận được email với link thanh toán VNPay, và sau khi thanh toán, trạng thái hóa đơn sẽ được cập nhật tự động.
import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import styles from './InputWaterElectric.module.scss';
import { useParams } from 'react-router-dom';
import axios from 'axios';
const cx = classNames.bind(styles);
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL;
function InputWaterElectric() {
const { roomId } = useParams();
const [electricityReading, setElectricityReading] = useState('');
const [waterReading, setWaterReading] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`${API_BASE_URL}/invoices/send-email`, {
roomId: parseInt(roomId),
waterIndex: parseFloat(waterReading),
electricityIndex: parseFloat(electricityReading)
});
if (response.status === 200) {
alert("Email đã được gửi thành công!");
// Reset form sau khi gửi email thành công
setElectricityReading('');
setWaterReading('');
} else {
alert("Gửi email thất bại!");
}
} catch (error) {
console.error("Lỗi khi gửi email:", error);
alert("Gửi email thất bại!");
}
};
return (
<div className={cx('meter-reading')}>
<div className={cx('meter-reading__form')}>
<h2>Nhập Chỉ Số Điện Và Nước</h2>
<form onSubmit={handleSubmit}>
<div className={cx('form-group')}>
<label>Chỉ Số Điện (kWh)</label>
<input
type="number"
value={electricityReading}
onChange={(e) => setElectricityReading(e.target.value)}
placeholder="Nhập chỉ số điện"
required
/>
</div>
<div className={cx('form-group')}>
<label>Chỉ Số Nước (m³)</label>
<input
type="number"
value={waterReading}
onChange={(e) => setWaterReading(e.target.value)}
placeholder="Nhập chỉ số nước"
required
/>
</div>
<button type="submit">Gửi Email</button>
</form>
</div>
</div>
);
}
export default InputWaterElectric;
Thay đổi:
process.env.REACT_APP_API_BASE_URL để lấy URL backend từ biến môi trường. Đảm bảo bạn đã khai báo biến này trong file .env của dự án React.electricityReading và waterReading về chuỗi rỗng.Với những thay đổi này, ứng dụng của bạn sẽ sử dụng đúng URL backend từ biến môi trường và form sẽ được dọn dẹp sau khi gửi email thành công.