Browse Source

post data to ERP and it's scheduler

Refund scheduler code added
master
kanimozhi 2 years ago
parent
commit
75a1ef6b93
  1. 82
      src/main/java/com/gcc/communityHall/entity/erpPostData.java
  2. 9
      src/main/java/com/gcc/communityHall/others/AppConfig.java
  3. 250
      src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java
  4. 326
      src/main/java/com/gcc/communityHall/paymentService/controller/RefundController.java
  5. 140
      src/main/java/com/gcc/communityHall/paymentService/entity/RefundClientInfo.java
  6. 19
      src/main/java/com/gcc/communityHall/paymentService/entity/TransactionResponse.java
  7. 160
      src/main/java/com/gcc/communityHall/paymentService/entity/TransactionStatusLog.java
  8. 8
      src/main/java/com/gcc/communityHall/paymentService/repository/RefundClientInfoRepository.java
  9. 15
      src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java
  10. 7
      src/main/java/com/gcc/communityHall/paymentService/repository/TransactionStatusLogRepository.java
  11. 291
      src/main/java/com/gcc/communityHall/paymentService/scheduler/ERPScheduler.java
  12. 335
      src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java
  13. 25
      src/main/java/com/gcc/communityHall/repository/ErpPostDataRepository.java
  14. 7
      src/main/java/com/gcc/communityHall/repository/ExtraPaymentsRepository.java
  15. 10
      src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java
  16. 8
      src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java
  17. 1
      src/main/java/com/gcc/communityHall/service/Impl/PaymentsServiceImpl.java
  18. 22
      src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java
  19. 1
      src/main/java/com/gcc/communityHall/service/PaymentsService.java
  20. 6
      src/main/java/com/gcc/communityHall/service/TransactionService.java
  21. 1
      src/main/resources/application-dev.properties
  22. 22
      src/main/resources/paymentConfig.properties
  23. 264
      src/main/resources/templates/officiallogin.html

82
src/main/java/com/gcc/communityHall/entity/erpPostData.java

@ -0,0 +1,82 @@
package com.gcc.communityHall.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import java.time.LocalDate;
import java.util.Date;
@Entity
public class erpPostData {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String tx_id;
private int booking_det_booking_id;
private boolean status;
private LocalDate cdate;
private int pay_status;
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getTx_id() {
return tx_id;
}
public void setTx_id(String tx_id) {
this.tx_id = tx_id;
}
public int getBooking_det_booking_id() {
return booking_det_booking_id;
}
public void setBooking_det_booking_id(int booking_det_booking_id) {
this.booking_det_booking_id = booking_det_booking_id;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public LocalDate getCdate() {
return cdate;
}
public void setCdate(LocalDate cdate) {
this.cdate = cdate;
}
public int getPay_status() {
return pay_status;
}
public void setPay_status(int pay_status) {
this.pay_status = pay_status;
}
@Override
public String toString() {
return "erpPostData{" +
"id=" + id +
", tx_id='" + tx_id + '\'' +
", booking_det_booking_id=" + booking_det_booking_id +
", status=" + status +
", cdate=" + cdate +
", pay_status=" + pay_status +
'}';
}
}

9
src/main/java/com/gcc/communityHall/others/AppConfig.java

@ -13,6 +13,7 @@ public class AppConfig {
private String erpUrl;
private String assetURL;
private String manualRefundCode;
private String commErpUrl;
private String fullUrl;
@ -71,4 +72,12 @@ public class AppConfig {
public void setFullUrl(String fullUrl) {
this.fullUrl = fullUrl;
}
public String getCommErpUrl() {
return commErpUrl;
}
public void setCommErpUrl(String commErpUrl) {
this.commErpUrl = commErpUrl;
}
}

250
src/main/java/com/gcc/communityHall/paymentService/controller/PaymentController.java

@ -1,24 +1,33 @@
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.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.time.format.DateTimeFormatter;
import java.util.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcc.communityHall.entity.*;
import com.gcc.communityHall.others.AppConfig;
import com.gcc.communityHall.repository.ErpPostDataRepository;
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;
import com.gcc.communityHall.entity.ExtraPayments;
import com.gcc.communityHall.entity.BookingDetails.BookingStatus;
import com.gcc.communityHall.entity.BookingDetails.RefundStatus;
import com.gcc.communityHall.entity.Payments;
import com.gcc.communityHall.entity.Users;
import com.gcc.communityHall.paymentService.config.PaymentConfig;
import com.gcc.communityHall.paymentService.entity.TransactionResponse;
import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository;
@ -27,10 +36,9 @@ 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
@ -58,6 +66,12 @@ public class PaymentController {
@Autowired
private BookingDetailsRepository bookingDetailsRepository;
@Autowired
private AppConfig appConfig;
@Autowired
private ErpPostDataRepository erpPostDataRepository;
@PostMapping(value = "/response")
public String response(Model model, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
@ -80,11 +94,9 @@ public class PaymentController {
if (i == res.length - 1) {
c = c + salt;
confirmToken = res[i];
}
else if(res[i].isEmpty()) {
} else if (res[i].isEmpty()) {
c = c + "|";
}
else if(res[i].equals("NA")) {
} else if (res[i].equals("NA")) {
c = c + "NA|";
} else {
c = c + res[i] + "|";
@ -121,6 +133,7 @@ public class PaymentController {
payment.setPaymentStatus("Success");
bookingsDetails.setPayments(payment);
String confirmBooking = bookser.confirmBooking(response.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");
@ -143,10 +156,104 @@ public class PaymentController {
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<String, Object> 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<String> 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<String, Object> 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 = "";
@ -165,11 +272,9 @@ public class PaymentController {
if (i == res.length - 1) {
c = c + salt;
confirmToken = res[i];
}
else if(res[i].isEmpty()) {
} else if (res[i].isEmpty()) {
c = c + "|";
}
else if(res[i].equals("NA")) {
} else if (res[i].equals("NA")) {
c = c + "NA|";
} else {
c = c + res[i] + "|";
@ -213,9 +318,105 @@ public class PaymentController {
}
model.addAttribute("bookingsDetails", bookingsDetails);
extraPaymentsRepository.save(payment);
postEPDataToERP(payment, response); //post extra payments details to ERP
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<String, Object> 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<String> 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<String, Object> 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 {
@ -240,11 +441,9 @@ public class PaymentController {
if (i == res.length - 1) {
c = c + salt;
confirmToken = res[i];
}
else if(res[i].isEmpty()) {
} else if (res[i].isEmpty()) {
c = c + "|";
}
else if(res[i].equals("NA")) {
} else if (res[i].equals("NA")) {
c = c + "NA|";
} else {
c = c + res[i] + "|";
@ -293,6 +492,7 @@ public class PaymentController {
return "already exists";
}
}
@PostMapping(value = "/refundcompleted")
public String refundCompleted(Model model, @RequestParam String txansactionId, @RequestParam(required = false) String msg) throws NoSuchAlgorithmException {
Optional<TransactionResponse> transactionresponse = transactionResRepo.findByTxansactionId(txansactionId);

326
src/main/java/com/gcc/communityHall/paymentService/controller/RefundController.java

@ -0,0 +1,326 @@
package com.gcc.communityHall.paymentService.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcc.communityHall.entity.BookingDetails;
import com.gcc.communityHall.entity.Payments;
import com.gcc.communityHall.entity.RefundTransaction;
import com.gcc.communityHall.paymentService.config.PaymentConfig;
import com.gcc.communityHall.paymentService.entity.RefundClientInfo;
import com.gcc.communityHall.paymentService.entity.RefundResponse;
import com.gcc.communityHall.paymentService.entity.TransactionResponse;
import com.gcc.communityHall.paymentService.entity.TransactionStatusLog;
import com.gcc.communityHall.paymentService.repository.RefundClientInfoRepository;
import com.gcc.communityHall.paymentService.repository.TransRefundResRepository;
import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository;
import com.gcc.communityHall.paymentService.repository.TransactionStatusLogRepository;
import com.gcc.communityHall.paymentService.service.PaymentGatewayServiceImpl;
import com.gcc.communityHall.repository.PaymentsRepository;
import com.gcc.communityHall.service.BookingService;
import com.gcc.communityHall.service.TransactionService;
import com.google.gson.Gson;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class RefundController {
@Autowired
public RefundClientInfoRepository refundClientInfoRepository;
@Autowired
public TransactionResponseRepository transactionResponseRepository;
@Autowired
private TransactionStatusLogRepository transactionStatusLogRepository;
@Autowired
private PaymentConfig paymentConfig;
@Autowired
private PaymentsRepository paymentsRepository;
@Autowired
private BookingService bookingService;
@Autowired
private PaymentGatewayServiceImpl paymentGatewayService;
@Autowired
private TransRefundResRepository transRefundResRepository;
@Autowired
private TransactionService transactionService;
@Autowired
private PaymentGatewayServiceImpl paymentGatewayServiceImpl;
@GetMapping(value = "/refundProcess")
public ResponseEntity refundProcess() {
try {
List<Map<String, Object>> pendingTransactions = transactionResponseRepository.getTransactionResponseByStatus("temp");
for (Map<String, Object> transactionRecord : pendingTransactions) {
try {
Map<String, Object> status = new HashMap<>();
Map<String, Object> merchant = new HashMap<>();
Map<String, Object> transaction = new HashMap<>();
status.put("merchant", merchant);
status.put("transaction", transaction);
merchant.put("identifier", paymentConfig.getMerchantId());
transaction.put("identifier", transactionRecord.get("txansaction_id"));
transaction.put("requestType", "O");
transaction.put("token", "");
transaction.put("reference", "");
System.out.println("=====================================" + transactionRecord.get("txansaction_id"));
System.out.println(merchant);
System.out.println(transaction);
System.out.println(status);
System.out.println("======================================");
String bookingDate = transactionRecord.get("booking_date").toString();
if (bookingDate != null && !bookingDate.isEmpty()) {
String[] dateParts = bookingDate.split("-");
String formattedDate = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0];
transaction.put("dateTime", formattedDate);
} else {
transaction.put("dateTime", "");
}
Gson gson = new Gson();
String json = gson.toJson(status);
System.out.println("Hello json " + json);
String encryptHxRefund = paymentGatewayService.encryptHxRefund(json);
RestTemplate restTemplate = new RestTemplate();
String url = "https://www.tpsl-india.in/PaymentGateway/merchant2.pg/" + paymentConfig.getMerchantId();
ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, encryptHxRefund, String.class);
String decryptHxTRefund = paymentGatewayService.decryptHxTRefund(postForEntity.getBody());
Map<String, Object> myObj = new ObjectMapper().readValue(decryptHxTRefund, Map.class);
Map<String, Object> paymentMethod = (Map<String, Object>) myObj.get("paymentMethod");
Map<String, Object> response = (Map<String, Object>) paymentMethod.get("paymentTransaction");
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println("hello2" + response);
System.out.println("hello " + myObj);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
TransactionStatusLog log = new TransactionStatusLog();
log.setBookingId(transactionRecord.get("booking_id").toString());
log.setUserId(transactionRecord.get("user_id").toString());
log.setTransactionId(transactionRecord.get("txansaction_id").toString());
// log.setStatus(response.get("status").toString());
log.setErrorMessage(response.get("errorMessage").toString());
log.setStatusMessage(response.get("statusMessage").toString());
log.setStatusCode(response.get("statusCode").toString());
log.setRefundIdentifier(response.get("refundIdentifier").toString());
// log.setResponse(response.toString());
log.setAmount(response.get("amount").toString());
log.setBalanceAmt(response.get("balanceAmount").toString());
log.setReceivedDate(response.get("dateTime").toString());
TransactionStatusLog saveLog = transactionStatusLogRepository.save(log);
TransactionResponse transRes = transactionResponseRepository.findById(Integer.parseInt(transactionRecord.get("id").toString())
).orElseThrow(() -> new Exception("TransactionResponse not found"));
transRes.setStatusCode(log.getStatusCode());
transRes.setAmount(log.getAmount());
transRes.setTpslTxnId(response.get("identifier").toString());
transRes.setResponse(response.toString());
transRes.setDate(log.getReceivedDate());
transactionResponseRepository.save(transRes);
Payments payments = paymentsRepository.findByBookingId(Integer.valueOf(String.valueOf(transRes.getBookingId())));
System.out.println("payments hello" + payments);
if (payments != null && response.get("statusCode").toString().equals("0300")) {
// payments.setBookingDetails(payments.getBookingDetails());
payments.setTransactionId(transRes.getTxansactionId());
payments.setAmountReceived(Double.parseDouble(response.get("amount").toString()));
payments.setPaymentStatus("Success");
payments.setCdate(new Date());
paymentsRepository.save(payments);
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly.");
intiateRefund(transRes.getBookingId(), Integer.parseInt(transRes.getUserId()));
} else if (response.get("statusCode").toString().equals("0300")) {
payments = new Payments();
BookingDetails bookingsById = bookingService.getBookingsById(transRes.getBookingId());
payments.setBookingDetails(bookingsById);
payments.setTransactionId(transRes.getTxansactionId());
payments.setAmountReceived(Double.parseDouble(response.get("amount").toString()));
payments.setPaymentStatus("Success");
payments.setCdate(new Date());
paymentsRepository.save(payments);
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly.");
intiateRefund(transRes.getBookingId(), Integer.parseInt(transRes.getUserId()));
} else {
payments = new Payments();
payments.setBookingDetails(payments.getBookingDetails());
payments.setTransactionId(transRes.getTxansactionId());
try {
payments.setAmountReceived(Double.parseDouble(response.get("amount") != null ? response.get("amount").toString() : "0"));//error here
}catch (Exception e ){
payments.setAmountReceived(0);
}
payments.setPaymentStatus("Not Completed");
payments.setCdate(new Date());
paymentsRepository.save(payments);
System.out.println("bookingId "+transRes.getBookingId());
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.PAYMENT_FAILURE, "Booking Not Confirmed. Amount Not Received.");
}
updateRefundInfo(response, log);
} catch (Exception ex) {
System.err.println("Error processing transaction record: " + ex.getMessage());
ex.printStackTrace();
}
}
} catch (Exception e) {
System.err.println("Error fetching or saving payment status: " + e.getMessage());
e.printStackTrace();
}
return ResponseEntity.ok("refundProcess");
}
public void updateRefundInfo(Map<String, Object> response, TransactionStatusLog log) {
if (response.get("refundDdetails") != null) {
Map<String, Object> refundInfo = (Map<String, Object>) response.get("refundDdetails");
List<Map<String, Object>> refundDetails = (List<Map<String, Object>>) refundInfo.get("RefundDetails");
System.out.println("inifcon :" + refundDetails);
if (refundDetails != null && !refundDetails.isEmpty()) {
RefundResponse refundResponse = new RefundResponse();
refundResponse.setAmount(response.get("amount") != null ? response.get("amount").toString() : "");
refundResponse.setBalaceAmount(response.get("balanceAmount") != null ? response.get("balanceAmount").toString() : "");
refundResponse.setTxansactionId(log.getTransactionId());
Map<String, Object> mapRef = refundDetails.get(refundDetails.size() - 1);
LocalDate df = LocalDate.now();
try {
df = LocalDate.parse(mapRef.get("REF_TXN_DATE").toString());
} catch (Exception e) {
df = LocalDate.now();
}
;
refundResponse.setDate(df);
if (mapRef.get("STATUS") != null && mapRef.get("STATUS").toString().equals("INITIATED")) {
refundResponse.setStatusCode("0400");
} else {
refundResponse.setStatusCode("0399");
}
refundResponse.setResponse(refundDetails.toString());
refundResponse.setBookingId(Integer.parseInt(log.getBookingId()));
refundResponse.setUserId(log.getUserId());
RefundResponse saverRefundResponse = transRefundResRepository.save(refundResponse);
Double amt = Double.parseDouble(response.get("amount").toString());
Double balAmt = Double.parseDouble(response.get("balanceAmount").toString());
if (amt != balAmt) {
RefundTransaction refundTrans = transactionService.getRefundTrans(saverRefundResponse.getBookingId());
if (refundTrans != null) {
refundTrans.setAmountRefunded(amt - balAmt);
refundTrans.setRefundStatus("0400");
refundTrans.setRefundIdentifier(response.get("refundIdentifier").toString());
refundTrans.setCdate(new Date());
transactionService.saveRefundTransaction(refundTrans);
} else {
refundTrans = new RefundTransaction();
refundTrans.setAmountRefunded(amt - balAmt);
refundTrans.setRefundStatus("0400");
refundTrans.setRefundIdentifier(response.get("refundIdentifier").toString());
refundTrans.setCdate(new Date());
refundTrans.setTransactionId(log.getTransactionId());
BookingDetails bookingsById = bookingService.getBookingsById(Integer.parseInt(log.getBookingId()));
refundTrans.setBookingDetails(bookingsById);
transactionService.saveRefundTransaction(refundTrans);
}
bookingService.updateRefundStatus(saverRefundResponse.getBookingId(), BookingDetails.RefundStatus.COMPLETED);
}
saveRefundClientInfo(refundDetails, log.getUserId(), log.getBookingId(), log.getTransactionId());
}
}
}
public String saveRefundClientInfo(List<Map<String, Object>> refundDetail, String userId, String bookingId, String transactionId) {
if (refundDetail == null || refundDetail.isEmpty()) {
return "error";
}
for (Map<String, Object> refund : refundDetail) {
RefundClientInfo refundClientInfo = new RefundClientInfo();
refundClientInfo.setUserId(Integer.parseInt(userId));
refundClientInfo.setBookingId(Integer.parseInt(bookingId));
refundClientInfo.setTransactionId(transactionId);
refundClientInfo.setClntRfndId(refund.get("clnt_rfnd_id") != null ? refund.get("clnt_rfnd_id").toString() : "");
refundClientInfo.setArnNo(refund.get("ARN_Number") != null ? refund.get("ARN_Number").toString() : "");
refundClientInfo.setGetRefTxnDate(refund.get("REF_TXN_DATE") != null ? refund.get("REF_TXN_DATE").toString() : "");
refundClientInfo.setRefTxnAmt(refund.get("REF_TXN_AMT") != null ? refund.get("REF_TXN_AMT").toString() : "");
refundClientInfo.setRefTxnId(refund.get("REF_TXN_ID") != null ? refund.get("REF_TXN_ID").toString() : "");
refundClientInfo.setStatus(refund.get("STATUS") != null ? refund.get("STATUS").toString() : "");
refundClientInfo.setSrno(refund.get("SR_NO") != null ? refund.get("SR_NO").toString() : "");
refundClientInfoRepository.save(refundClientInfo);
}
return "success";
}
@Transactional
public void intiateRefund(int bookingId, int userId) throws Exception {
String s = paymentGatewayServiceImpl.refundTheAmount(bookingId, userId);
if (s.equals("Refunded")) {
bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.COMPLETED);
} else {
bookingService.updateRefundStatus(bookingId, BookingDetails.RefundStatus.FAILURE);
}
}
}

140
src/main/java/com/gcc/communityHall/paymentService/entity/RefundClientInfo.java

@ -0,0 +1,140 @@
package com.gcc.communityHall.paymentService.entity;
import jakarta.persistence.*;
import java.util.Date;
@Entity
public class RefundClientInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String srno;
private String refTxnId;
private String refTxnAmt;
private String getRefTxnDate;
private String Status;
private String clntRfndId;
private String transactionId;
private String arnNo;
private int bookingId;
private int userId;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private Date cdate = new Date();
public String getClntRfndId() {
return clntRfndId;
}
public void setClntRfndId(String clntRfndId) {
this.clntRfndId = clntRfndId;
}
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSrno() {
return srno;
}
public void setSrno(String srno) {
this.srno = srno;
}
public String getRefTxnId() {
return refTxnId;
}
public void setRefTxnId(String refTxnId) {
this.refTxnId = refTxnId;
}
public String getRefTxnAmt() {
return refTxnAmt;
}
public void setRefTxnAmt(String refTxnAmt) {
this.refTxnAmt = refTxnAmt;
}
public String getGetRefTxnDate() {
return getRefTxnDate;
}
public void setGetRefTxnDate(String getRefTxnDate) {
this.getRefTxnDate = getRefTxnDate;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getArnNo() {
return arnNo;
}
public void setArnNo(String arnNo) {
this.arnNo = arnNo;
}
public int getBookingId() {
return bookingId;
}
public void setBookingId(int bookingId) {
this.bookingId = bookingId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public Date getCdate() {
return cdate;
}
public void setCdate(Date cdate) {
this.cdate = cdate;
}
@Override
public String toString() {
return "RefundClientInfo{" +
"id=" + id +
", srno='" + srno + '\'' +
", refTxnId='" + refTxnId + '\'' +
", refTxnAmt='" + refTxnAmt + '\'' +
", getRefTxnDate='" + getRefTxnDate + '\'' +
", Status='" + Status + '\'' +
", clntRfndId='" + clntRfndId + '\'' +
", arnNo='" + arnNo + '\'' +
", bookingId=" + bookingId +
", userId=" + userId +
", cdate=" + cdate +
'}';
}
}

19
src/main/java/com/gcc/communityHall/paymentService/entity/TransactionResponse.java

@ -1,10 +1,8 @@
package com.gcc.communityHall.paymentService.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
public class TransactionResponse {
@ -24,6 +22,17 @@ public class TransactionResponse {
private String response;
private String Amount;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private LocalDateTime cdate = LocalDateTime.now();
public LocalDateTime getCdate() {
return cdate;
}
public void setCdate(LocalDateTime cdate) {
this.cdate = cdate;
}
public TransactionResponse() {
}

160
src/main/java/com/gcc/communityHall/paymentService/entity/TransactionStatusLog.java

@ -0,0 +1,160 @@
package com.gcc.communityHall.paymentService.entity;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
public class TransactionStatusLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String transactionId;
private String bookingId;
private String userId;
private String status;
private String errorMessage;
private String statusMessage;
private String statusCode;
private String refundIdentifier;
@Column(columnDefinition = "TEXT")
private String response;
private String amount;
private String balanceAmt;
private String receivedDate;
@Column(name = "cdate",nullable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
private LocalDateTime cdate = LocalDateTime.now();
public String getStatusCode() {
return statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public Integer getId() {
return id;
}
public String getTransactionId() {
return transactionId;
}
public String getBookingId() {
return bookingId;
}
public String getUserId() {
return userId;
}
public String getStatus() {
return status;
}
public String getErrorMessage() {
return errorMessage;
}
public String getStatusMessage() {
return statusMessage;
}
public void setId(Integer id) {
this.id = id;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public void setBookingId(String bookingId) {
this.bookingId = bookingId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setStatus(String status) {
this.status = status;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
public String getRefundIdentifier() {
return refundIdentifier;
}
public void setRefundIdentifier(String refundIdentifier) {
this.refundIdentifier = refundIdentifier;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public LocalDateTime getCdate() {
return cdate;
}
public void setCdate(LocalDateTime cdate) {
this.cdate = cdate;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getBalanceAmt() {
return balanceAmt;
}
public void setBalanceAmt(String balanceAmt) {
this.balanceAmt = balanceAmt;
}
public String getReceivedDate() {
return receivedDate;
}
public void setReceivedDate(String receivedDate) {
this.receivedDate = receivedDate;
}
@Override
public String toString() {
return "TransactionStatusLog{" +
"id=" + id +
", transactionId='" + transactionId + '\'' +
", bookingId='" + bookingId + '\'' +
", userId='" + userId + '\'' +
", status='" + status + '\'' +
", errorMessage='" + errorMessage + '\'' +
", statusMessage='" + statusMessage + '\'' +
", statusCode='" + statusCode + '\'' +
", refundIdentifier='" + refundIdentifier + '\'' +
", cdate='" + cdate + '\'' +
'}';
}
}

8
src/main/java/com/gcc/communityHall/paymentService/repository/RefundClientInfoRepository.java

@ -0,0 +1,8 @@
package com.gcc.communityHall.paymentService.repository;
import com.gcc.communityHall.paymentService.entity.RefundClientInfo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RefundClientInfoRepository extends JpaRepository<RefundClientInfo, Integer> {
}

15
src/main/java/com/gcc/communityHall/paymentService/repository/TransactionResponseRepository.java

@ -1,6 +1,7 @@
package com.gcc.communityHall.paymentService.repository;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
@ -53,4 +54,18 @@ public interface TransactionResponseRepository extends JpaRepository<Transaction
// void saveTransactionResponse(@Param("id") int id, @Param("amount") String amount, @Param("booking_id") int booking_id ,@Param("date" ) String date,@Param("hall_id" ) int hall_id ,@Param("response")String response,@Param("status_code")String status_code,@Param("tpsl_txn_id")String tpsl_txn_id,@Param("txansaction_id")String txansaction_id,@Param("user_id")String user_id );
//
//@Query (value = "UPDATE transaction_response SET 'amount' = :amount, 'booking_id' =:booking_id , 'date' = :date, 'hall_id' = :hall_id, 'response' = :response, 'status_code' = :status_code, 'tpsl_txn_id' = :tpsl_txn_id, 'txansaction_id' = :txansaction_id, 'user_id' = :user_id WHERE ('id' = :id)", nativeQuery = true)
@Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.status_code, " +
"tr.tpsl_txn_id, tr.txansaction_id, tr.user_id, bd.booking_date " +
"FROM transaction_response tr " +
"INNER JOIN booking_details bd ON tr.booking_id = bd.booking_id " +
"WHERE tr.status_code = ? AND bd.booking_date < CURDATE()", nativeQuery = true)
List<Map<String, Object>> getTransactionResponseByStatus(String status);
@Query(value = "SELECT tr.id, tr.amount, tr.booking_id, tr.hall_id, tr.response, tr.tpsl_txn_id, tr.txansaction_id, tr.cdate, " +
"tr.user_id, bd.booking_date FROM transaction_response tr " +
"INNER JOIN booking_details bd ON tr.booking_id = bd.booking_id " +
"WHERE tr.status_code = 'temp' AND tr.cdate < DATE_SUB(NOW(), INTERVAL 1 HOUR);", nativeQuery = true)
List<Map<String, Object>> getTransResBycdateandStatus(String status);
}

7
src/main/java/com/gcc/communityHall/paymentService/repository/TransactionStatusLogRepository.java

@ -0,0 +1,7 @@
package com.gcc.communityHall.paymentService.repository;
import com.gcc.communityHall.paymentService.entity.TransactionStatusLog;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TransactionStatusLogRepository extends JpaRepository<TransactionStatusLog, Integer> {
}

291
src/main/java/com/gcc/communityHall/paymentService/scheduler/ERPScheduler.java

@ -0,0 +1,291 @@
package com.gcc.communityHall.paymentService.scheduler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcc.communityHall.entity.BookingDetails;
import com.gcc.communityHall.entity.ExtraPayments;
import com.gcc.communityHall.entity.Payments;
import com.gcc.communityHall.entity.erpPostData;
import com.gcc.communityHall.others.AppConfig;
import com.gcc.communityHall.paymentService.entity.TransactionResponse;
import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository;
import com.gcc.communityHall.repository.ErpPostDataRepository;
import com.gcc.communityHall.repository.ExtraPaymentsRepository;
import com.gcc.communityHall.repository.PaymentsRepository;
import com.gcc.communityHall.service.BookingService;
import com.gcc.communityHall.service.PaymentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import javax.swing.text.html.Option;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
@Component
//@EnableScheduling
public class ERPScheduler {
@Autowired
private ErpPostDataRepository erpPostDataRepository;
@Autowired
private AppConfig appConfig;
@Autowired
private PaymentsRepository paymentsRepository;
@Autowired
private TransactionResponseRepository transactionResponseRepository;
@Autowired
private ExtraPaymentsRepository extraPaymentsRepository;
@Scheduled(fixedRate = 30000)
public void checkERPPostData() {
Payments payment = new Payments();
ExtraPayments expayment = new ExtraPayments();
List<erpPostData> notpostedlist = erpPostDataRepository.getNotPostedDetails();
System.out.println("notpostedlist....." + notpostedlist);
if (!notpostedlist.isEmpty()) {
for (erpPostData data : notpostedlist) {
Long bookingId = (long) data.getBooking_det_booking_id();
String txId = data.getTx_id();
int status = data.getPay_status();
if (bookingId == null) {
System.out.println("Invalid Booking ID: " + bookingId);
} else {
System.out.println("Processing Booking ID: " + bookingId);
}
if (status == 1) {
payment = paymentsRepository.findByBookingId(Math.toIntExact(bookingId));
} else if (status == 2) {
expayment = extraPaymentsRepository.getExtraPaymentsByBookingId(Math.toIntExact(bookingId)).orElse(null);
}
// TransactionResponse txRes = transactionResponseRepository.findById(Integer.valueOf(txId)).orElse(null);
TransactionResponse txRes = transactionResponseRepository.findByTxansactionId(txId).orElse(null);
if (payment == null) {
System.out.println("No Payment found for Booking ID: " + bookingId);
}
if (txRes == null) {
System.out.println("No Transaction Response found for TX ID: " + txId);
}
if (expayment == null) {
System.out.println("No Extra Payment found for Booking ID: " + bookingId);
}
if (status == 1) {
if (payment != null && txRes != null) {
postDataToERP(payment, txRes);
}
} else if (status == 2) {
if (expayment != null && txRes != null) {
postEDDataToERP(expayment, txRes);
}
}
}
} else {
System.out.println("No records found to process.");
}
}
public void postDataToERP(Payments payment, TransactionResponse res) {
System.out.println("postDataToERP...");
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<String, Object> 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<String> stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class);
// System.out.println(stringResponseEntity.getBody());
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl());
for (Map.Entry<String, Object> 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")) {
erpPostDataRepository.updateERPStatus(false, erpData.getId());
} else{
erpPostDataRepository.updateERPStatus(true,erpData.getId());
}
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void postEDDataToERP(ExtraPayments payment, TransactionResponse res) {
System.out.println("Post ED Data to ERP....");
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<String, Object> 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<String> stringResponseEntity = restTemplate.postForEntity(appConfig.getErpUrl(), data, String.class);
// System.out.println(stringResponseEntity.getBody());
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appConfig.getCommErpUrl());
for (Map.Entry<String, Object> 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")) {
erpPostDataRepository.updateERPStatus(false,erpData.getId());
} else{
erpPostDataRepository.updateERPStatus(true,erpData.getId());
}
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

335
src/main/java/com/gcc/communityHall/paymentService/scheduler/PaymentStatusScheduler.java

@ -0,0 +1,335 @@
package com.gcc.communityHall.paymentService.scheduler;/*
// Import necessary packages
package com.gcc.communityHall.paymentService.Scheduler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcc.communityHall.entity.BookingDetails;
import com.gcc.communityHall.entity.Payments;
import com.gcc.communityHall.entity.RefundTransaction;
import com.gcc.communityHall.paymentService.config.PaymentConfig;
import com.gcc.communityHall.paymentService.entity.RefundClientInfo;
import com.gcc.communityHall.paymentService.entity.RefundResponse;
import com.gcc.communityHall.paymentService.entity.TransactionResponse;
import com.gcc.communityHall.paymentService.entity.TransactionStatusLog;
import com.gcc.communityHall.paymentService.repository.RefundClientInfoRepository;
import com.gcc.communityHall.paymentService.repository.TransRefundResRepository;
import com.gcc.communityHall.paymentService.repository.TransactionResponseRepository;
import com.gcc.communityHall.paymentService.repository.TransactionStatusLogRepository;
import com.gcc.communityHall.paymentService.service.PaymentGatewayServiceImpl;
import com.gcc.communityHall.repository.PaymentsRepository;
import com.gcc.communityHall.service.BookingService;
import com.gcc.communityHall.service.TransactionService;
import com.google.gson.Gson;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@EnableScheduling
public class PaymentStatusScheduler {
@Autowired
public RefundClientInfoRepository refundClientInfoRepository;
@Autowired
public TransactionResponseRepository transactionResponseRepository;
@Autowired
private TransactionStatusLogRepository transactionStatusLogRepository;
@Autowired
private PaymentConfig paymentConfig;
@Autowired
private PaymentsRepository paymentsRepository;
@Autowired
private BookingService bookingService;
@Autowired
private PaymentGatewayServiceImpl paymentGatewayService;
@Autowired
private TransRefundResRepository transRefundResRepository;
@Autowired
private TransactionService transactionService;
@Autowired
private PaymentGatewayServiceImpl paymentGatewayServiceImpl;
// @Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Kolkata") //executed at 12:00 AM
// @Scheduled(fixedRate = 900000)
@Scheduled(fixedRate = 30000)
public void fetchAndSavePaymentStatus() {
// System.out.println("Fetching Payment Status...At 12:00 AM IST");
System.out.println("Fetching Payment Status...At 15 min Testing");
try {
List<Map<String, Object>> pendingTransactions = transactionResponseRepository.getTransResBycdateandStatus("temp");
for (Map<String, Object> transactionRecord : pendingTransactions) {
try {
Map<String, Object> status = new HashMap<>();
Map<String, Object> merchant = new HashMap<>();
Map<String, Object> transaction = new HashMap<>();
status.put("merchant", merchant);
status.put("transaction", transaction);
merchant.put("identifier", paymentConfig.getMerchantId());
transaction.put("identifier", transactionRecord.get("txansaction_id"));
transaction.put("requestType", "O");
transaction.put("token", "");
transaction.put("reference", "");
System.out.println("====================================="+ transactionRecord.get("txansaction_id"));
System.out.println(merchant);
System.out.println(transaction);
System.out.println(status);
System.out.println(transactionRecord.toString());
System.out.println("======================================");
String bookingDate = transactionRecord.get("booking_date").toString();
// System.out.println("cdate check"+transactionRecord.get("cdate").toString());
String cdate = transactionRecord.get("cdate").toString();
if (cdate != null && !cdate.isEmpty()) {
String[] dateParts1 = cdate.split(" ");
String[] dateParts = dateParts1[0].split("-");
String formattedDate = dateParts[2] + "-" + dateParts[1] + "-" + dateParts[0];
transaction.put("dateTime", formattedDate);
System.out.println("formattedDate"+formattedDate);
} else {
transaction.put("dateTime", "");
}
Gson gson = new Gson();
String json = gson.toJson(status);
System.out.println("Hello json "+json);
String encryptHxRefund = paymentGatewayService.encryptHxRefund(json);
RestTemplate restTemplate = new RestTemplate();
String url = "https://www.tpsl-india.in/PaymentGateway/merchant2.pg/" + paymentConfig.getMerchantId();
ResponseEntity<String> postForEntity = restTemplate.postForEntity(url, encryptHxRefund, String.class);
String decryptHxTRefund = paymentGatewayService.decryptHxTRefund(postForEntity.getBody());
Map<String, Object> myObj = new ObjectMapper().readValue(decryptHxTRefund, Map.class);
Map<String, Object> paymentMethod = (Map<String, Object>)myObj.get("paymentMethod");
Map<String, Object> response = (Map<String, Object>)paymentMethod.get("paymentTransaction");
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println("hello2" + response);
System.out.println("hello "+myObj);
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
TransactionStatusLog log = new TransactionStatusLog();
log.setBookingId(transactionRecord.get("booking_id").toString());
log.setUserId(transactionRecord.get("user_id").toString());
log.setTransactionId(transactionRecord.get("txansaction_id").toString());
// log.setStatus(response.get("status").toString());
log.setErrorMessage(response.get("errorMessage").toString());
log.setStatusMessage(response.get("statusMessage").toString());
log.setStatusCode(response.get("statusCode").toString());
log.setRefundIdentifier(response.get("refundIdentifier").toString());
// log.setResponse(response.toString());
log.setAmount(response.get("amount").toString());
log.setBalanceAmt(response.get("balanceAmount").toString());
log.setReceivedDate(response.get("dateTime").toString());
TransactionStatusLog saveLog = transactionStatusLogRepository.save(log);
TransactionResponse transRes = transactionResponseRepository.findById(Integer.parseInt(transactionRecord.get("id").toString())
).orElseThrow(() -> new Exception("TransactionResponse not found"));
transRes.setStatusCode(log.getStatusCode());
transRes.setAmount(log.getAmount());
transRes.setTpslTxnId(response.get("identifier").toString());
transRes.setResponse(response.toString());
transRes.setDate(log.getReceivedDate());
transactionResponseRepository.save(transRes);
Payments payments = paymentsRepository.findByBookingId(Integer.valueOf(String.valueOf(transRes.getBookingId())));
System.out.println("payments hello"+payments);
if(payments!=null && response.get("statusCode").toString().equals("0300")) {
// payments.setBookingDetails(payments.getBookingDetails());
payments.setTransactionId(transRes.getTxansactionId());
payments.setAmountReceived(Double.parseDouble(response.get("amount").toString()));
payments.setPaymentStatus("Success");
Date date = new Date(payments.getCdate().getTime());
//paymentsRepository.updatePaymentInfo(payments.getPaymentId(),payments.getTransactionId(),payments.getAmountReceived(),payments.getPaymentStatus(),transRes.getBookingId());
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly.");
intiateRefund(transRes.getBookingId(),Integer.parseInt(transRes.getUserId()));
}else if(response.get("statusCode").toString().equals("0300")){
payments = new Payments();
BookingDetails bookingsById = bookingService.getBookingsById(transRes.getBookingId());
payments.setBookingDetails(bookingsById);
payments.setTransactionId(transRes.getTxansactionId());
payments.setAmountReceived(Double.parseDouble(response.get("amount").toString()));
payments.setPaymentStatus("Success");
payments.setCdate(new Date());
//paymentsRepository.insertPaymentinfo(payments.getPaymentId(),payments.getTransactionId(),payments.getAmountReceived(),payments.getPaymentStatus(),transRes.getBookingId(),payments.getCdate() );
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.REFUNDED, "Booking Not Confirmed. Amount will be refunded shortly.");
intiateRefund(transRes.getBookingId(),Integer.parseInt(transRes.getUserId()));
}
else{
payments.setBookingDetails(payments.getBookingDetails());
payments.setTransactionId(transRes.getTxansactionId());
payments.setAmountReceived(Double.parseDouble(response.get("amount")!=null?response.get("amount").toString():"0")); payments.setPaymentStatus("Not Completed");
payments.setCdate(new Date());
paymentsRepository.save(payments);
bookingService.updateBookingStatus(transRes.getBookingId(), BookingDetails.BookingStatus.PAYMENT_FAILURE, "Booking Not Confirmed. Amount Not Received.");
}
updateRefundInfo(response,log);
} catch (Exception ex) {
System.err.println("Error processing transaction record: " + ex.getMessage());
ex.printStackTrace();
}
}
} catch (Exception e) {
System.err.println("Error fetching or saving payment status: " + e.getMessage());
e.printStackTrace();
}
}
public void updateRefundInfo(Map<String,Object> response,TransactionStatusLog log){
if(response.get("refundDdetails") != null ){
Map<String,Object> refundInfo= (Map<String, Object>) response.get("refundDdetails");
List<Map<String ,Object>> refundDetails = (List<Map<String, Object>>) refundInfo.get("RefundDetails");
System.out.println("inifcon :"+ refundDetails);
if(refundDetails != null && !refundDetails.isEmpty()){
RefundResponse refundResponse = new RefundResponse();
refundResponse.setAmount(response.get("amount")!=null?response.get("amount").toString():"");
refundResponse.setBalaceAmount(response.get("balanceAmount")!=null?response.get("balanceAmount").toString():"");
refundResponse.setTxansactionId(log.getTransactionId());
Map<String ,Object> mapRef = refundDetails.get(refundDetails.size()-1);
LocalDate df = LocalDate.now();
try{df =LocalDate.parse(mapRef.get("REF_TXN_DATE").toString());}catch (Exception e){df = LocalDate.now();};
refundResponse.setDate(df);
if(mapRef.get("STATUS")!=null && mapRef.get("STATUS").toString().equals("INITIATED")){
refundResponse.setStatusCode("0400");
}else{
refundResponse.setStatusCode("0399");
}
refundResponse.setResponse(refundDetails.toString());
refundResponse.setBookingId(Integer.parseInt(log.getBookingId()));
refundResponse.setUserId(log.getUserId());
RefundResponse saverRefundResponse = transRefundResRepository.save(refundResponse);
Double amt = Double.parseDouble(response.get("amount").toString());
Double balAmt = Double.parseDouble(response.get("balanceAmount").toString());
if(amt != balAmt ) {
RefundTransaction refundTrans = transactionService.getRefundTrans(saverRefundResponse.getBookingId());
if (refundTrans != null) {
refundTrans.setAmountRefunded(amt - balAmt);
refundTrans.setRefundStatus("0400");
refundTrans.setRefundIdentifier(response.get("refundIdentifier").toString());
refundTrans.setCdate(new Date());
transactionService.saveRefundTransaction(refundTrans);
} else {
refundTrans = new RefundTransaction();
refundTrans.setAmountRefunded(amt - balAmt);
refundTrans.setRefundStatus("0400");
refundTrans.setRefundIdentifier(response.get("refundIdentifier").toString());
refundTrans.setCdate(new Date());
refundTrans.setTransactionId(log.getTransactionId());
BookingDetails bookingsById = bookingService.getBookingsById(Integer.parseInt(log.getBookingId()));
refundTrans.setBookingDetails(bookingsById);
transactionService.saveRefundTransaction(refundTrans);
}
bookingService.updateRefundStatus(saverRefundResponse.getBookingId(),BookingDetails.RefundStatus.COMPLETED); }
saveRefundClientInfo(refundDetails,log.getUserId() ,log.getBookingId(), log.getTransactionId());
}
}
}
public String saveRefundClientInfo(List<Map<String, Object>> refundDetail,String userId,String bookingId,String transactionId) {
if (refundDetail == null || refundDetail.isEmpty()) {
return "error";
}
for (Map<String, Object> refund : refundDetail) {
RefundClientInfo refundClientInfo = new RefundClientInfo();
refundClientInfo.setUserId(Integer.parseInt(userId));
refundClientInfo.setBookingId(Integer.parseInt(bookingId));
refundClientInfo.setTransactionId(transactionId);
refundClientInfo.setClntRfndId(refund.get("clnt_rfnd_id")!=null?refund.get("clnt_rfnd_id").toString():"");
refundClientInfo.setArnNo(refund.get("ARN_Number")!=null?refund.get("ARN_Number").toString():"");
refundClientInfo.setGetRefTxnDate(refund.get("REF_TXN_DATE")!=null?refund.get("REF_TXN_DATE").toString():"");
refundClientInfo.setRefTxnAmt(refund.get("REF_TXN_AMT")!=null?refund.get("REF_TXN_AMT").toString():"");
refundClientInfo.setRefTxnId(refund.get("REF_TXN_ID")!=null?refund.get("REF_TXN_ID").toString():"");
refundClientInfo.setStatus(refund.get("STATUS")!=null?refund.get("STATUS").toString():"");
refundClientInfo.setSrno(refund.get("SR_NO")!=null?refund.get("SR_NO").toString():"");
refundClientInfoRepository.save(refundClientInfo);
}
return "success";
}
@Transactional
public void intiateRefund(int bookingId,int userId) throws Exception {
String s = paymentGatewayServiceImpl.refundTheAmount(bookingId, userId);
if(s.equals("Refunded")){
bookingService.updateRefundStatus(bookingId,BookingDetails.RefundStatus.COMPLETED);
}else
{
bookingService.updateRefundStatus(bookingId,BookingDetails.RefundStatus.FAILURE);
}
}
}
*/

25
src/main/java/com/gcc/communityHall/repository/ErpPostDataRepository.java

@ -0,0 +1,25 @@
package com.gcc.communityHall.repository;
import com.gcc.communityHall.entity.erpPostData;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.swing.text.html.Option;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Repository
public interface ErpPostDataRepository extends JpaRepository<erpPostData, Long> {
@Query(value = "SELECT * FROM erp_post_data WHERE status = false", nativeQuery = true)
List<erpPostData> getNotPostedDetails();
@Modifying
@Transactional
@Query(value = "update erp_post_data set status = ? where id =?", nativeQuery = true)
void updateERPStatus(boolean status, Long id);
}

7
src/main/java/com/gcc/communityHall/repository/ExtraPaymentsRepository.java

@ -1,12 +1,19 @@
package com.gcc.communityHall.repository;
import com.gcc.communityHall.entity.Payments;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.communityHall.entity.EbDetails;
import com.gcc.communityHall.entity.ExtraPayments;
import java.util.Optional;
@Repository
public interface ExtraPaymentsRepository extends JpaRepository<ExtraPayments,Integer> {
@Query(value = "SELECT * FROM extra_payments WHERE booking_details_booking_id = ? ",nativeQuery = true)
Optional<ExtraPayments> getExtraPaymentsByBookingId(int id);
}

10
src/main/java/com/gcc/communityHall/repository/PaymentsRepository.java

@ -1,17 +1,17 @@
package com.gcc.communityHall.repository;
import java.util.List;
import com.gcc.communityHall.entity.Payments;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.gcc.communityHall.entity.Payments;
import java.util.List;
import java.util.Optional;
@Repository
public interface PaymentsRepository extends JpaRepository<Payments,Integer> {
@Query(value = "SELECT * FROM payments WHERE payment_status in ('paid') ",nativeQuery = true)
@ -23,4 +23,6 @@ public interface PaymentsRepository extends JpaRepository<Payments,Integer> {
+ "WHERE h.zone = :zone", nativeQuery = true)
List<Payments> getPaymentListByzone(@Param("zone") String zone);
//List<Payments> findAllWithBookingDetailsAndUsers();
@Query(value = "select * from payments where booking_details_booking_id=?",nativeQuery = true)
Payments findByBookingId(int bookingId);
}

8
src/main/java/com/gcc/communityHall/repository/RefundTransactionRepository.java

@ -1,16 +1,16 @@
package com.gcc.communityHall.repository;
import java.util.List;
import com.gcc.communityHall.entity.RefundTransaction;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.gcc.communityHall.entity.RefundTransaction;
@Repository
public interface RefundTransactionRepository extends JpaRepository<RefundTransaction,Integer> {
@Query(value = "select * from refund_transaction where booking_details_booking_id = ?",nativeQuery = true)
RefundTransaction findByBookingId(int bookingId);
}

1
src/main/java/com/gcc/communityHall/service/Impl/PaymentsServiceImpl.java

@ -87,4 +87,5 @@ public class PaymentsServiceImpl implements PaymentsService{
return paymentsDTO;
}
}

22
src/main/java/com/gcc/communityHall/service/Impl/TransactionServiceImpl.java

@ -1,4 +1,24 @@
package com.gcc.communityHall.service.Impl;
public class TransactionServiceImpl {
import com.gcc.communityHall.entity.RefundTransaction;
import com.gcc.communityHall.repository.RefundTransactionRepository;
import com.gcc.communityHall.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TransactionServiceImpl implements TransactionService {
@Autowired
private RefundTransactionRepository refundTransactionRepository;
@Override
public RefundTransaction getRefundTrans(int bookingId) {
return refundTransactionRepository.findByBookingId(bookingId);
}
@Override
public RefundTransaction saveRefundTransaction(RefundTransaction refundTransaction) {
return refundTransactionRepository.save(refundTransaction);
}
}

1
src/main/java/com/gcc/communityHall/service/PaymentsService.java

@ -10,5 +10,4 @@ public interface PaymentsService {
List<Payments> getPaymentsByZone(String zone);
List<PaymentsDTO> getAllPaymentDetails();
}

6
src/main/java/com/gcc/communityHall/service/TransactionService.java

@ -1,4 +1,10 @@
package com.gcc.communityHall.service;
import com.gcc.communityHall.entity.RefundTransaction;
public interface TransactionService {
RefundTransaction getRefundTrans(int bookingId);
RefundTransaction saveRefundTransaction(RefundTransaction refundTransaction);
}

1
src/main/resources/application-dev.properties

@ -70,3 +70,4 @@ app.getOtpUrl=https://tmegov.onex-aura.com/api/sms?
app.manualRefundCode=8520
app.fullUrl=http://localhost:8080
app.commErpUrl=http://coc-staging.egovernments.org:9980/pgr/external/mobileservice

22
src/main/resources/paymentConfig.properties

@ -1,15 +1,15 @@
payment.worldline.merchantId=T955031
payment.worldline.encryptionKey=1025180466GPADTD
payment.worldline.encryptionIV=3232693456UWOWHC
payment.worldline.schemeCode=FIRST
payment.worldline.merchantName=Greater Chennai Corporation
payment.worldline.transactionSuccessCode=0300
payment.worldline.refundSuccessCode=0400
#payment.worldline.merchantId=L1037717
#payment.worldline.encryptionKey=6207149300MFLGNY
#payment.worldline.encryptionIV=3422107798TKQCNG
#payment.worldline.merchantId=T955031
#payment.worldline.encryptionKey=1025180466GPADTD
#payment.worldline.encryptionIV=3232693456UWOWHC
#payment.worldline.schemeCode=FIRST
#payment.worldline.merchantName=Greater Chennai Corporation
#payment.worldline.transactionSuccessCode=0300
#payment.worldline.refundSuccessCode=0400
payment.worldline.merchantId=T1037717
payment.worldline.encryptionKey=6207149300MFLGNY
payment.worldline.encryptionIV=3422107798TKQCNG
payment.worldline.schemeCode=FIRST
payment.worldline.merchantName=Greater Chennai Corporation
payment.worldline.transactionSuccessCode=0300
payment.worldline.refundSuccessCode=0400

264
src/main/resources/templates/officiallogin.html

@ -4,6 +4,8 @@
<head th:replace="~{fragments/loginhead :: head}"></head>
<body>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<style>
.otp-input-box {
/*display: flex;
@ -20,6 +22,7 @@
font-size: 16px;
margin-right: 10px;
}
.required-field {
color: red;
}
@ -42,6 +45,7 @@
z-index: 999999999999999 !important;
/* Adjust this value if needed */
}
.form-check-label {
padding-left: 0px
}
@ -93,11 +97,12 @@
<!-- Sign In Form -->
<!-- jQuery Validation (.js-validation-signin class is initialized in js/pages/op_auth_signin.min.js which was auto compiled from _js/pages/op_auth_signin.js) -->
<!-- For more info and examples you can check out https://github.com/jzaefferer/jquery-validation -->
<form class="js-validation-signin" action="/gcc-public" onsubmit="return login();">
<!--<form class="js-validation-signin" id="loginForm" action="/communityhall/careTaker/api/checkLogin" onsubmit="return login();">-->
<form class="js-validation-signin" action="/gcc-public" onsubmit="return login(2);">
<div class="mb-4">
<div class="input-group input-group-lg">
<span class="input-group-text">
<i class="fa fa-user-circle"></i>
<i class="fa fa-mobile"></i>
</span>
<input type="text" class="form-control" id="mobii" name="mobii"
placeholder="Mobile Number" value="" required minlength="10"
@ -109,10 +114,19 @@
<div class="mb-4">
<div class="input-group input-group-lg">
<span class="input-group-text">
<i class="fa fa-asterisk"></i>
<i class="fa fa-lock"></i>
</span>
<input type="password" maxlength="4" minlength="4" class="form-control"
id="password" name="password" placeholder="Password" value="" required>
id="password" name="PIN" placeholder="pin" value="" required>
</div>
</div>
<div class="mb-4" id="otpInput" style="display: none">
<div class="input-group input-group-lg">
<span class="input-group-text">
<i class="fa fa-asterisk"></i>
</span>
<input type="text" maxlength="5" minlength="5" class="form-control"
id="loginOTP" placeholder="OTP" value="" required>
</div>
</div>
<div class="d-sm-flex justify-content-sm-between align-items-sm-center text-center text-sm-start mb-2 row">
@ -120,12 +134,29 @@
<a href="javascript:newPinCall();">Forgot PIN?</a>
</div>
</div>
<div class="text-center mb-2">
<div class="text-center mb-2" id="sendBtn">
<button type="button" class="btn btn-hero btn-primary" onclick="checkofficialMobileNo(1)">
<i class="fa fa-fw fa-sign-in-alt opacity-50 me-1"></i> Send OTP
</button>
</div>
<div class="text-center mb-2" id="verifyBtn" style="display:none" onclick="verifyOTP()">
<button type="button" class="btn btn-hero btn-primary">
<i class="fa fa-fw fa-sign-in-alt opacity-50 me-1"></i> Verify OTP
</button>
</div>
<div class="mb-3 text-center">
<div id="resend-container1" style="display:none">
<p class="mb-0">Didn't receive OTP?</p>
<p class="mb-0 text-info" id="resendlink1">Please wait..<span
id="countdown1">60</span>s
</p>
</div>
</div>
<div class="text-center mb-2" id="loginBtn" style="display:none">
<button type="submit" class="btn btn-hero btn-primary">
<i class="fa fa-fw fa-sign-in-alt opacity-50 me-1"></i> Log In
</button>
</div>
<br /><br />
</form>
<!-- END Sign In Form -->
@ -141,15 +172,18 @@
<!-- END Page Content -->
</main>
<!-- END Main Container -->
<div class="modal fade backdrop" id="pinForm" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal fade backdrop" id="pinForm" data-backdrop="static" tabindex="-1" role="dialog"
aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="#" th:action="@{/savePIN}" th:object="${savePIN}" onsubmit="return checkofficialMobileNo();">
<form action="#" th:action="@{/savePIN}" th:object="${savePIN}"
onsubmit="return checkofficialMobileNo(2);">
<div class="block block-rounded block-themed block-transparent mb-0">
<div class="block-header bg-primary-dark">
<h3 class="block-title" id="mtitl">Forgot PIN</h3>
<div class="block-options">
<button type="button" class="btn-block-option" data-bs-dismiss="modal" aria-label="Close">
<button type="button" class="btn-block-option" data-bs-dismiss="modal"
aria-label="Close">
<i class="fa fa-fw fa-times"></i>
</button>
</div>
@ -157,16 +191,24 @@
<div class="block-content">
<div class="mb-4">
<label class="form-label">Registered Mobile Number <span class="text-danger">*</span></label>
<input type="text" minlength="10" maxlength="10" class="form-control text-center" name="mobileNo" id="officialmobileno" pattern="[6-9]{1}[0-9]{9}" placeholder="Numbers Only" oninvalid="setCustomValidity('Please enter correct Mobile Number')" oninput="setCustomValidity('')" required />
<label class="form-label">Registered Mobile Number <span
class="text-danger">*</span></label>
<input type="text" minlength="10" maxlength="10" class="form-control text-center"
name="mobileNo" id="officialmobileno" pattern="[6-9]{1}[0-9]{9}"
placeholder="Numbers Only"
oninvalid="setCustomValidity('Please enter correct Mobile Number')"
oninput="setCustomValidity('')" required/>
</div>
<div class="mb-4">
<label class="form-label">New 4 Digit PIN <span class="text-danger">*</span></label>
<input type="password" maxlength="4" class="form-control text-center" name="newPinNo" id="updatedpassword" placeholder="Numbers Only" minlength="4" required />
<input type="password" maxlength="4" class="form-control text-center" name="newPinNo"
id="updatedpassword" placeholder="Numbers Only" minlength="4" required/>
</div>
</div>
<div class="block-content block-content-full text-end bg-body" id="mbutton">
<button type="button" class="btn btn-sm btn-alt-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-sm btn-alt-secondary" data-bs-dismiss="modal">Close
</button>
<button type="submit" class="btn btn-sm btn-primary">Submit</button>
</div>
</div>
@ -181,7 +223,8 @@
<div class="modal fade" id="otpForm" tabindex="-1" role="dialog" aria-labelledby="otpFormLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="#" th:action="@{/otpForm}" th:object="${otpForm}" method="post" onsubmit="return verifyOtp();">
<form action="#" th:action="@{/otpForm}" th:object="${otpForm}" method="post"
onsubmit="return verifyOtp2();">
<div class="modal-header">
<h6 class="modal-title m-0" id="exampleModalDefaultLabel">OTP Login</h6>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
@ -208,7 +251,8 @@
<div class="mb-3 text-center">
<div id="resend-container">
<p class="mb-0">Didn't receive OTP?</p>
<p class="mb-0 text-info" id="resendlink">Please wait..<span id="countdown">60</span>s</p>
<p class="mb-0 text-info" id="resendlink">Please wait..<span id="countdown">60</span>s
</p>
</div>
</div>
</div><!--end row-->
@ -226,10 +270,147 @@
<!-- Scripts -->
<script th:replace="~{fragments/loginscript :: script}"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function sendOTP() {
document.getElementById("error").style.display="none";
//alert($('#mobii').val());
var mobileNo = $('#mobii').val();
var pin = $('#password').val();
if (mobileNo.length != 10) {
alert("Please Enter Mobile Number");
return false;
}
if (pin.trim() == '' || pin.length == 0) {
alert("Please Enter Password ");
return false;
}
$.ajax({
type: "GET",
url: '/communityhall/user/api/sendOTP',
data: {'mobileNo': mobileNo, 'purpose': 'Officer Login'},
success: function (bodyMessage) {
document.getElementById("otpInput").style.display = "block";
document.getElementById("sendBtn").style.display = "none";
document.getElementById("verifyBtn").style.display = "block";
document.getElementById("resend-container1").style.display="block";
// console.log(mobileNo);
// Calculate the elapsed time since the request started
var resendTimeout;
// var resendLink = $("#resend-link1");
$("#resend-link1").html('Please wait..<span id="countdown1">60</span>s');
var countdown = $("#countdown1");
// Function to start the countdown timer
function startCountdown2() {
var timeleft = 60;
countdown.text(timeleft);
resendTimeout = setInterval(function () {
timeleft--;
countdown.text(timeleft);
if (timeleft <= 0) {
clearInterval(resendTimeout);
$("#resendlink1").html('<a href="#" id="resend-link1" class="text-info" onclick="return sendOTP(' + mobileNo + ');">Resend OTP</a>');
}
}, 1000);
}
startCountdown2(); // Start Resend OTP count
},
error: function () {
// Handle error case if the AJAX request fails
let elapsedTime = new Date().getTime() - startTime;
let delay = Math.max(0, minDisplayTime - elapsedTime);
setTimeout(function () {
Swal.close(); // Close the Swal loading dialog
// Show network error Swal
Swal.fire(
'Network Error!',
'Please try again later.',
'error'
);
}, delay); // Delay closing the loading dialog before showing the error
}
});
return false;
}
function login() {
function verifyOTP() {
// Get all the input fields with class `otp-input`
var otpInputs = $('#loginOTP').val();
var mobileNo = $('#mobii').val();
if (mobileNo.length != 10) {
alert("Please Enter Mobile Number");
return false;
}
//alert(otpInputs);
if (otpInputs.trim() == '') {
alert("Please Enter OTP ");
return false;
}
if (otpInputs.length != 5) {
alert("Please Enter Correct OTP");
return false;
}
//document.getElementById("saveFeedbackForm").submit();
$.ajax({
type: "GET",
url: '/communityhall/user/api/verifyOTP',
data: {'otp': otpInputs, 'mobileNo': mobileNo},
dataType: 'text',
success: function (bodyMessage) {
//alert(bodyMessage);
if (bodyMessage.trim() == "Success") {
console.log("OTP is Verified!!!");
document.getElementById("loginBtn").style.display = "block";
document.getElementById("verifyBtn").style.display = "none";
document.getElementById("otpInput").style.display = "none";
document.getElementById("resend-container1").style.display="none";
Swal.fire({
title: 'Login OTP',
text: ' OTP is Verified!!',
icon: 'success',
confirmButtonText: 'OK'
}).then((result) => {
login(2);
});
return false;
// callSave();
} else {
Swal.fire({
title: 'OTP',
text: 'Entered OTP is Incorrect!!',
icon: 'warning',
confirmButtonText: 'OK'
}).then((result) => {
$("#loginOTP").val('');
});
}
},
error: function () {
console.log("Error");// Handle error here
return false;
}
});
return false;
}
function login(flag) {
document.getElementById("resend-container1").style.display="none";
var mobileNo = $("#mobii").val();
var pin = $("#password").val();
$.ajax({
@ -244,9 +425,12 @@
$("#mobii").val("");
$("#password").val("");
} else {
// Redirect based on the user type
if(flag==1){
sendOTP();
} if(flag==2){
redirectToDashboard(response);
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// Log the error and any relevant information
if (jqXHR.status === 400) {
@ -293,6 +477,7 @@
console.error("Invalid user type:", userType);
}
}
$('.otp-input').on('keyup', function (e) {
var $this = $(this);
if ($this.val().length === 1) {
@ -317,11 +502,13 @@
keyboard: false
});
$("#mobii").val('');
$("#passwordd").val('');
$("#password").val('');
$("#loginOTP").val('');
$('#otpForm').modal('hide');
$('#pinForm').modal('show');
return false;
}
var password = document.getElementById("password"),
confirm_password = document.getElementById("confirm_password");
@ -333,9 +520,21 @@
}
}
function checkofficialMobileNo(){
function checkofficialMobileNo(flag) {
if(flag==1){
var mobileNo = $("#mobii").val();
if (mobileNo.trim() == '' || mobileNo.length == 0) {
alert("Please Enter Mobile No ");
}
}
if(flag==2){
var pincode = $("#pincode").val('');
var mobileNo = $("#officialmobileno").val();
if (mobileNo.trim() == '' || mobileNo.length == 0) {
alert("Please Enter Mobile No ");
}
}
$.ajax({
type: "GET",
url: '/communityhall/careTaker/api/checkofficialMobileExits',
@ -344,17 +543,26 @@
success: function (bodyMessage) {
//alert(bodyMessage);
if (bodyMessage == "success") {
if(flag==1){
login(1);
}
if(flag==2){
sendOTP2(mobileNo);
}
return false;
} else {
alert("This Mobile Number Is Not Registered!");
return false;
}
},
error: function (errortxt) {
console.error(errortxt);// Handle error here
return false;
}
});
return false;
}
function sendOTP2(mobileNo) {
// var mobileNo = $("#mobii").val();
@ -368,6 +576,7 @@
data: {'mobileNo': mobileNo, 'purpose': 'Forget Pin'},
dataType: 'json',
success: function (bodyMessage) {
console.log("bodyMessage....." + bodyMessage);
if (bodyMessage != "Error") {
$('#otpForm').modal({
backdrop: 'static',
@ -395,6 +604,7 @@
}
}, 1000);
}
startCountdown2(); // Start Resend OTP count
/////////////////////////////////////////////////
} else {
@ -405,7 +615,8 @@
return false;
}
function verifyOtp(){
function verifyOtp2() {
// Get all the input fields with class `otp-input`
var otpInputs = $('.otp-input');
@ -437,14 +648,18 @@
return false;
}
function callSave() {
phone = $("#officialmobileno").val();
pin = $("#updatedpassword").val();
$.ajax({
type: "GET",
url: '/communityhall/careTaker/api/updatePIN',
data: {'phone':phone,
'pin':pin},
data: {
'phone': phone,
'pin': pin
},
dataType: 'text',
success: function (bodyMessage) {
if (bodyMessage.trim() == "Success") {
@ -464,6 +679,7 @@
}
});
}
document.addEventListener('DOMContentLoaded', function () {
function clearModalFields(modalId) {
const modal = document.getElementById(modalId);
@ -484,12 +700,16 @@
clearModalFields('pinForm');
});
});
$('#otpForm').on('shown.bs.modal', function () {
$('.otp-input').val('');
$('#otperror').text('');
// $('#mobilenotxt').text('');
});
</script>
</body>
</html>
Loading…
Cancel
Save