package com.gcc.communityHall.paymentService.controller; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.security.Timestamp; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.gcc.communityHall.configuration.EncryptionUtil; import com.gcc.communityHall.entity.*; import com.gcc.communityHall.others.AppConfig; //import com.gcc.communityHall.repository.ErpPostDataRepository; import com.gcc.communityHall.service.PaymentsService; import org.apache.tomcat.util.json.JSONParser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigurationPackage; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.gcc.communityHall.entity.BookingDetails.BookingStatus; import com.gcc.communityHall.entity.BookingDetails.RefundStatus; import com.gcc.communityHall.paymentService.config.PaymentConfig; import com.gcc.communityHall.paymentService.entity.TransactionResponse; import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository; import com.gcc.communityHall.paymentService.service.PaymentGatewayService; import com.gcc.communityHall.repository.BookingDetailsRepository; import com.gcc.communityHall.repository.ExtraPaymentsRepository; import com.gcc.communityHall.repository.PaymentsRepository; import com.gcc.communityHall.service.Impl.BookingServiceImpl; import com.gcc.communityHall.service.UserService; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @Controller @RequestMapping("/communityhall/payment") public class PaymentController { // ak @Autowired private EncryptionUtil encryptionUtil; @Autowired PaymentGatewayService paymentService; @Autowired private PaymentConfig paymentConfig; @Autowired private BookingServiceImpl bookser; @Autowired private TransactionResponseRepository transactionResRepo; @Autowired private PaymentsRepository paymentRepo; @Autowired private ExtraPaymentsRepository extraPaymentsRepository; @Autowired private BookingDetailsRepository bookingDetailsRepository; @Autowired private AppConfig appConfig; // @Autowired // private ErpPostDataRepository erpPostDataRepository; @Autowired private PaymentsService paymentsService; // ak @PostMapping(value = "/response") public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { System.out.println("Payment Response receiving from Payment Gateway..."); String salt = this.paymentConfig.getEncryptionKey(); String confirmToken = ""; String status = this.paymentConfig.getTransactionSuccessCode(); String refId = ""; String[] res = msg.split("\\|"); String c = ""; TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); Payments payment = new Payments(); payment.setTransactionId(response.getTxansactionId()); double amount = 0; // ------------------ PAYMENT STRING PROCESSING ------------------ for (int i = 0; i < res.length; i++) { if (i == res.length - 1) { c = c + salt; confirmToken = res[i]; } else if (res[i].isEmpty()) { c = c + "|"; } else if (res[i].equals("NA")) { c = c + "NA|"; } else { c = c + res[i] + "|"; } if (i == 5) { response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); response.setDate(res[8]); } } int bookingId = response.getBookingId(); try { amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { } payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); // JPA fetch payment.setBookingDetails(bookingsDetails); response.setResponse(msg); response.setStatusCode(res[0]); bookingsDetails.setPayments(payment); payment.setCdate(new Date()); // save transaction response transactionResRepo.save(response); // ============================================================= // CASE 1: FAILURE - AMOUNT MISMATCH // ============================================================= if (bookingsDetails.getAmountReceived() != amount) { if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); paymentRepo.save(payment); // booking failure logic bookser.bookingFailure(bookingsDetails, 1); } // Fetch OR Generate booking_ref_id refId = bookser.getBookingRefIdByBookingId(bookingId); // encrypt bookingId (coworkspace logic) String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); model.addAttribute("ref_id", refId); model.addAttribute("encryptedId", encryptedId); return "redirect:/communityhall/user/acknowledgement?ref_id=" + refId; } // ============================================================= // CASE 2: SUCCESS FLOW // ============================================================= if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); paymentRepo.save(payment); // 🔥 Fetch OR Generate booking_ref_id refId = bookser.getBookingRefIdByBookingId(bookingId); try { bookser.confirmBooking(bookingId); } catch (Exception e) { e.printStackTrace(); System.out.println("Exception Occured inside /response end point : " + e.getMessage()); // ignore } } // 🔐 Encrypt bookingId String encryptedId = encryptionUtil.encrypt(String.valueOf(bookingId)); model.addAttribute("ref_id", refId); model.addAttribute("encryptedId", encryptedId); return "redirect:/communityhall/user/acknowledgement?ref_id=" + refId; } /* * @PostMapping(value = "/response") * public String response(Model model, @RequestParam(required = false) String * msg) throws NoSuchAlgorithmException { * * String salt = this.paymentConfig.getEncryptionKey(); * * String confirmToken = ""; * String status = this.paymentConfig.getTransactionSuccessCode(); * String s = new String(msg); * String c = new String(); * String res[] = s.split("\\|"); * * TransactionResponse response = * this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); * Payments payment = new Payments(); * payment.setTransactionId(response.getTxansactionId()); * double amount = 0; * * * for (int i = 0; i < res.length; i++) { * if (i == res.length - 1) { * c = c + salt; * confirmToken = res[i]; * } else if (res[i].isEmpty()) { * c = c + "|"; * } else if (res[i].equals("NA")) { * c = c + "NA|"; * } else { * c = c + res[i] + "|"; * } * * if (i == 5) { * response.setTpslTxnId(res[i]); * response.setAmount(res[6]); * response.setTxansactionId(res[3]); * //String[] tDate = res[8].split(" "); * response.setDate(res[8]); * } * } * int bookingId = response.getBookingId(); * try { * amount = Double.parseDouble(response.getAmount()); * } catch (Exception e) { * // TODO: handle exception * //System.out.println("payment Controller lineNo-67"); * } * payment.setAmountReceived(amount); * payment.setPaymentStatus("Not Completed"); * * BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); * payment.setBookingDetails(bookingsDetails); * response.setResponse(msg); * response.setStatusCode(res[0]); * bookingsDetails.setPayments(payment); * payment.setCdate(new Date()); * * System.out.println("bookingsDetails.getAmountReceived().." + * bookingsDetails.getAmountReceived()); * System.out.println("amount: " + amount); * * TransactionResponse save = transactionResRepo.save(response); * * if (bookingsDetails.getAmountReceived() != amount) { // Reject booking if the * amount is incorrect * if(paymentService.generateToken(c).equals(confirmToken) && * status.equals(res[0])){ * payment.setPaymentStatus("Success"); * bookingsDetails.setPayments(payment); * paymentRepo.save(payment); * bookser.bookingFailure(bookingsDetails, 1); * } * //ak * * * * model.addAttribute("bookingsDetails", bookingsDetails); * return "redirect:/communityhall/user/acknowledgement?bookingId=" + * bookingsDetails.getBookingId(); * } * * * if (paymentService.generateToken(c).equals(confirmToken) && * status.equals(res[0])) { * payment.setPaymentStatus("Success"); * bookingsDetails.setPayments(payment); * try { * String confirmBooking = bookser.confirmBooking(response.getBookingId()); * }catch (Exception e){ * // return "redirect:/communityhall/user/acknowledgement?bookingId=" + * bookingsDetails.getBookingId(); * * } * // postDataToERP(payment, response); // post payment details to ERP * // * System.out.println("\n confirmBooking:- paymentController 111"+confirmBooking * +"\n"); * // if(confirmBooking.equals("Booking confirmed successfully")) { * // //bookser.updateBookingStatusById(bookingsDetails.getBookingId(), * BookingDetails.BookingStatus.APPROVED, "confirm"); * // // String bookingconfimationsms = * "Your booking with ID "+bookingsDetails.getBookingId()+" on" * +bookingsDetails.getBookingId() * +" has been successfully confirmed. Thanks for using GCC Community Hall Booking System." * ; * // }else if(confirmBooking.equals("Slot occupied")) { * //// System.out.println("Slot occupied line 115"); * //// BookingDetails crrSts = * bookser.updateBookingStatusById(bookingsDetails.getBookingId(), * BookingDetails.BookingStatus.REFUNDED, * "slot occupied Refund will happen shortly"); * //// System.out.println("BookingDetails:-"+crrSts.getBookingStatus()); * // } * // else if(confirmBooking.equals("Error confirming booking")) { * // bookser.updateBookingStatusById(bookingsDetails.getBookingId(), * BookingDetails.BookingStatus.PENDING, "Error"); * // * // } * * } * * // System.out.println(response.toString()); * model.addAttribute("bookingsDetails", bookingsDetails); // Add single * BookingDetails object * //System.out.println(save.toString()); * paymentRepo.save(payment); * return "redirect:/communityhall/user/acknowledgement?bookingId=" + * bookingsDetails.getBookingId(); * } */ /* * public void postDataToERP(Payments payment, TransactionResponse res) { * RestTemplate restTemplate = new RestTemplate(); * erpPostData erpData = new erpPostData(); * * SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); * String txDate = outputFormat.format(payment.getCdate()); * String assesNo = LocalDate.now().getYear() + "/COMM/" + res.getBookingId(); * * Map data = new TreeMap<>(); *//* static mandatory input to be sent *//* * data.put("serviceId", "getOtherCollection"); * data.put("COLLECTION_TYPE", "Community Hall"); * data.put("TOTALTRANSACTIONCODE", "450310000"); * // /end of static/ * // /unique data to be send/ * data.put("ASSESSMENTNO", assesNo); * data.put("UNIQUERECEIPTID", res.getBookingId()); * data.put("TRANSACTIONNO", payment.getTransactionId()); * data.put("TRANSACTIONREFNO", res.getTpslTxnId()); * data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy * -> 19/02/2025 * data.put("TOTALTRANSACTIONAMOUNT", * payment.getBookingDetails().getAmountReceived()); * * data.put("MSTRCODEONE", "061"); * data.put("SPLITAMOUNTONE", * payment.getBookingDetails().getHallAmount()); * data.put("MSTRCODETWO", "062"); * data.put("SPLITAMOUNTTWO", * payment.getBookingDetails().getDepositAmount()); * data.put("MSTRCODETHREE", "063"); * data.put("SPLITAMOUNTTHREE", payment.getBookingDetails().getGst()); * // /Amount Collected from party/ * data.put("PARTYNAME", * payment.getBookingDetails().getUsers().getName()); * data.put("PARTYADDRESS", * payment.getBookingDetails().getUsers().getStreet() + "," + * payment.getBookingDetails().getUsers().getArea() + "," + * payment.getBookingDetails().getUsers().getLocation() + "," + * payment.getBookingDetails().getUsers().getPinCode()); * data.put("PARTYMOBILE", * payment.getBookingDetails().getUsers().getMobileNo()); *//* end *//* * System.out.println(data); * System.out.println(appConfig.getCommErpUrl()); * // ResponseEntity stringResponseEntity = * restTemplate.postForEntity(appConfig.getErpUrl(), data, * String.class); * // System.out.println(stringResponseEntity.getBody()); * * erpData.setTx_id(payment.getTransactionId()); * erpData.setBooking_det_booking_id(res.getBookingId()); * erpData.setStatus(true); * erpData.setCdate(LocalDate.now()); * erpData.setPay_status(1); * erpPostDataRepository.save(erpData); * * UriComponentsBuilder builder = * UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()) * ; * for (Map.Entry entry : data.entrySet()) { * builder.queryParam(entry.getKey(), entry.getValue()); * } * * String urlMsg = builder.toUriString(); * System.out.println(urlMsg); * * try { * HttpURLConnection connection = null; * * URL url = new URL(urlMsg); * connection = (HttpURLConnection) url.openConnection(); * connection.setRequestMethod("GET"); * * int responseCode = connection.getResponseCode(); * // response=responseCode+""; * System.out.println("Response Code: " + responseCode); * * if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK * BufferedReader in = new BufferedReader(new * InputStreamReader(connection.getInputStream())); * String inputLine; * StringBuilder response = new StringBuilder(); * while ((inputLine = in.readLine()) != null) { * response.append(inputLine); * } * in.close(); * System.out.println("Response: " + response.toString()); * * ObjectMapper objectMapper = new ObjectMapper(); * JsonNode jsonNode = * objectMapper.readTree(response.toString()); * * String resultStatus = * jsonNode.get("ResultStatus").asText(); * * if (!resultStatus.isEmpty() && * resultStatus.equals("false")) { * erpData.setStatus(false); * erpPostDataRepository.save(erpData); * } * * } else { * System.out.println("GET request failed."); * } * * } catch (Exception e) { * e.printStackTrace(); * } * } */ @PostMapping(value = "/additionaldamage-response") public String additionaldamagePaymentresponse(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { String salt = this.paymentConfig.getEncryptionKey(); String confirmToken = ""; String status = this.paymentConfig.getTransactionSuccessCode(); String s = new String(msg); String c = new String(); String res[] = s.split("\\|"); TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); ExtraPayments payment = new ExtraPayments(); payment.setTransactionId(response.getTxansactionId()); double amount = 0; for (int i = 0; i < res.length; i++) { if (i == res.length - 1) { c = c + salt; confirmToken = res[i]; } else if (res[i].isEmpty()) { c = c + "|"; } else if (res[i].equals("NA")) { c = c + "NA|"; } else { c = c + res[i] + "|"; } if (i == 5) { response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); // String[] tDate = res[8].split(" "); response.setDate(res[8]); } } int bookingId = response.getBookingId(); try { amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { // TODO: handle exception // System.out.println("payment Controller lineNo-67"); } payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); payment.setBookingDetails(bookingsDetails); response.setResponse(msg); response.setStatusCode(res[0]); bookingsDetails.setExtrapayments(payment); payment.setCdate(new Date()); TransactionResponse save = transactionResRepo.save(response); if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { payment.setPaymentStatus("Success"); bookingsDetails.setExtrapayments(payment); bookingsDetails.getSettlement().setCollectionStatus("Paid"); bookingsDetails.setBookingStatus(BookingStatus.COMPLETED); bookingsDetails.setRefundStatus(RefundStatus.CLOSED); bookingsDetails.setComments("Collection Amount Paid Successfully"); bookingDetailsRepository.save(bookingsDetails); } model.addAttribute("bookingsDetails", bookingsDetails); extraPaymentsRepository.save(payment); // postEPDataToERP(payment, response); //post extra payments details to ERP // return // "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" + // bookingsDetails.getBookingId(); return "redirect:/communityhall/user/collectionpendingacknowledgement?bookingId=" + bookingsDetails.getBookingId(); } /* * public void postEPDataToERP(ExtraPayments payment, TransactionResponse res) { * RestTemplate restTemplate = new RestTemplate(); * erpPostData erpData = new erpPostData(); * * SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy"); * String txDate = outputFormat.format(payment.getCdate()); * String assesNo = LocalDate.now().getYear() + "/COMM/ED/" + * res.getBookingId(); * * Map data = new TreeMap<>(); *//* static mandatory input to be sent *//* * data.put("serviceId", "getOtherCollection"); * data.put("COLLECTION_TYPE", "Community Hall"); * data.put("TOTALTRANSACTIONCODE", "450310000"); * // /end of static/ * // /unique data to be send/ * data.put("ASSESSMENTNO", assesNo); * data.put("UNIQUERECEIPTID", res.getBookingId()); * data.put("TRANSACTIONNO", payment.getTransactionId()); * data.put("TRANSACTIONREFNO", res.getTpslTxnId()); * data.put("TRANSACTIONDATE", txDate); //payment date format dd/mm/yyyy * -> 19/02/2025 * data.put("TOTALTRANSACTIONAMOUNT", payment.getAmountReceived()); * * data.put("MSTRCODEONE", "061"); * data.put("SPLITAMOUNTONE", 0); * data.put("MSTRCODETWO", "062"); * data.put("SPLITAMOUNTTWO", payment.getAmountReceived()); * data.put("MSTRCODETHREE", "063"); * data.put("SPLITAMOUNTTHREE", 0); * // /Amount Collected from party/ * data.put("PARTYNAME", * payment.getBookingDetails().getUsers().getName()); * data.put("PARTYADDRESS", * payment.getBookingDetails().getUsers().getStreet() + "," + * payment.getBookingDetails().getUsers().getArea() + "," + * payment.getBookingDetails().getUsers().getLocation() + "," + * payment.getBookingDetails().getUsers().getPinCode()); * data.put("PARTYMOBILE", * payment.getBookingDetails().getUsers().getMobileNo()); *//* end *//* * System.out.println(data); * System.out.println(appConfig.getCommErpUrl()); * // ResponseEntity stringResponseEntity = * restTemplate.postForEntity(appConfig.getErpUrl(), data, * String.class); * // System.out.println(stringResponseEntity.getBody()); * * erpData.setTx_id(payment.getTransactionId()); * erpData.setBooking_det_booking_id(res.getBookingId()); * erpData.setStatus(true); * erpData.setCdate(LocalDate.now()); * erpData.setPay_status(2); * erpPostDataRepository.save(erpData); * * UriComponentsBuilder builder = * UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl()) * ; * for (Map.Entry entry : data.entrySet()) { * builder.queryParam(entry.getKey(), entry.getValue()); * } * * String urlMsg = builder.toUriString(); * System.out.println(urlMsg); * * try { * HttpURLConnection connection = null; * * URL url = new URL(urlMsg); * connection = (HttpURLConnection) url.openConnection(); * connection.setRequestMethod("GET"); * * int responseCode = connection.getResponseCode(); * // response=responseCode+""; * System.out.println("Response Code: " + responseCode); * * if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK * BufferedReader in = new BufferedReader(new * InputStreamReader(connection.getInputStream())); * String inputLine; * StringBuilder response = new StringBuilder(); * while ((inputLine = in.readLine()) != null) { * response.append(inputLine); * } * in.close(); * System.out.println("Response: " + response.toString()); * * ObjectMapper objectMapper = new ObjectMapper(); * JsonNode jsonNode = * objectMapper.readTree(response.toString()); * * String resultStatus = * jsonNode.get("ResultStatus").asText(); * * if (!resultStatus.isEmpty() && * resultStatus.equals("false")) { * erpData.setStatus(false); * erpPostDataRepository.save(erpData); * } * * } else { * System.out.println("GET request failed."); * } * * } catch (Exception e) { * e.printStackTrace(); * } * } */ @PostMapping(value = "/updatetransaction") public String updatetransaction(Model model, @RequestParam(required = false) String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { Optional transactionresponse = transactionResRepo.findByTxansactionId(txansactionId); TransactionResponse transactionres = transactionresponse.get(); if ("temp".equals(transactionres.getStatusCode()) && !"0300".equals(transactionres.getStatusCode())) { String salt = this.paymentConfig.getEncryptionKey(); String confirmToken = ""; String status = this.paymentConfig.getTransactionSuccessCode(); String s = new String(msg); String c = new String(); String res[] = s.split("\\|"); TransactionResponse response = this.paymentService.getTransactionResponseByTxansactionId(res[3], "temp"); Payments payment = new Payments(); payment.setTransactionId(response.getTxansactionId()); double amount = 0; for (int i = 0; i < res.length; i++) { if (i == res.length - 1) { c = c + salt; confirmToken = res[i]; } else if (res[i].isEmpty()) { c = c + "|"; } else if (res[i].equals("NA")) { c = c + "NA|"; } else { c = c + res[i] + "|"; } if (i == 5) { response.setTpslTxnId(res[i]); response.setAmount(res[6]); response.setTxansactionId(res[3]); // String[] tDate = res[8].split(" "); response.setDate(res[8]); } } int bookingId = response.getBookingId(); try { amount = Double.parseDouble(response.getAmount()); } catch (Exception e) { // TODO: handle exception // System.out.println("payment Controller lineNo-67"); } payment.setAmountReceived(amount); payment.setPaymentStatus("Not Completed"); BookingDetails bookingsDetails = bookser.getBookingsById(bookingId); payment.setBookingDetails(bookingsDetails); response.setResponse(msg); response.setStatusCode(res[0]); bookingsDetails.setPayments(payment); payment.setCdate(new Date()); TransactionResponse save = transactionResRepo.save(response); if (paymentService.generateToken(c).equals(confirmToken) && status.equals(res[0])) { payment.setPaymentStatus("Success"); bookingsDetails.setPayments(payment); String confirmBooking = bookser.confirmBooking(response.getBookingId()); } // System.out.println(response.toString()); model.addAttribute("bookingsDetails", bookingsDetails); // Add single BookingDetails object // System.out.println(save.toString()); paymentRepo.save(payment); return "success"; } else { return "already exists"; } } @PostMapping(value = "/refundcompleted") public String refundCompleted(Model model, @RequestParam String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException { Optional transactionresponse = transactionResRepo.findByTxansactionId(txansactionId); if (transactionresponse.isPresent()) { TransactionResponse transactionres = transactionresponse.get(); Optional bookings = bookingDetailsRepository.findById(transactionres.getBookingId()); if (bookings.isPresent()) { BookingDetails bookingDetails = bookings.get(); bookingDetails.setRefundStatus(RefundStatus.CLOSED); bookingDetailsRepository.save(bookingDetails); return "success"; } else { return "failure"; } } else { return "failure"; } } }