add rest client

This commit is contained in:
Mohd-Arham
2025-12-08 10:08:52 +05:30
65 changed files with 1068 additions and 762 deletions
@@ -15,33 +15,33 @@ import org.springframework.web.client.RestClient;
@Configuration
public class RestClientConfig {
@Bean
public RestClient restClient() throws Exception {
@Bean
public RestClient restClient() throws Exception {
// Create Trust-All SSL context
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
// Create Trust-All SSL context
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}
};
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
// Use JDK's Simple HTTP client with custom SSL context
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Apply SSL context to HttpsURLConnection globally
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
// Use JDK's Simple HTTP client with custom SSL context
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);
// Apply SSL context to HttpsURLConnection globally
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true);
return RestClient.builder().requestFactory(requestFactory).build();
}
return RestClient.builder()
.requestFactory(requestFactory)
.build();
}
}
@@ -44,9 +44,8 @@ public class SecurityConfig {
"/webjars/**",
"/error")
.permitAll()
.requestMatchers("/payment/callback/startPayment")
.permitAll().
requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/payment/callback/startPayment")
.permitAll().requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated())
.exceptionHandling(ex -> ex.authenticationEntryPoint(jwtAuthenticationEntryPoint))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
@@ -73,33 +73,34 @@ public class AgentController {
ResponseModel response = agentService.initiateBillValidateByBillId(billRequest);
return ResponseEntity.ok(response);
}
@PostMapping(value = "/fetchBillByClientReqId", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> fetchBillByClientReqId(
@Validated @RequestBody BillFetchByClientIdRequest billFetchByClientIdRequest) {
@Validated @RequestBody BillFetchByClientIdRequest billFetchByClientIdRequest) {
ResponseModel response = agentService.fetchBillByClientReqId(billFetchByClientIdRequest);
return ResponseEntity.ok(response);
}
@PostMapping(value = "/fetchBillValidateByClientReqId", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> fetchBillValidateByClientReqId(
@Validated @RequestBody BillValidateByClientIdRequest billValidateByClientIdRequest) {
@Validated @RequestBody BillValidateByClientIdRequest billValidateByClientIdRequest) {
ResponseModel response = agentService.fetchBillValidateByClientReqId(billValidateByClientIdRequest);
return ResponseEntity.ok(response);
}
@PostMapping(value="/callback/billFetch", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> handleBillFetchCallback(@RequestBody BillDataResponse billDataResponse) {
ResponseModel genralResp=agentService.processBillFetchCallback(billDataResponse);
@PostMapping(value = "/callback/billFetch", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> handleBillFetchCallback(@RequestBody BillDataResponse billDataResponse) {
ResponseModel genralResp = agentService.processBillFetchCallback(billDataResponse);
// Return a response indicating successful receipt
return ResponseEntity.ok(genralResp);
}
@PostMapping(value="/callback/billValidate", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> handleBillValidateCallback(@RequestBody FetchBillValidateResponse fetchBillValidateResponse) {
ResponseModel genralResp=agentService.processBillValidateCallback(fetchBillValidateResponse);
@PostMapping(value = "/callback/billValidate", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> handleBillValidateCallback(
@RequestBody FetchBillValidateResponse fetchBillValidateResponse) {
ResponseModel genralResp = agentService.processBillValidateCallback(fetchBillValidateResponse);
// Return a response indicating successful receipt
return ResponseEntity.ok(genralResp);
}
@@ -10,10 +10,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.billpaymentservice.bbps.dto.ResponseModel;
import com.billpaymentservice.bbps.dto.auth.AuthResponse;
import com.billpaymentservice.bbps.dto.response.AuthResponses;
import com.billpaymentservice.bbps.dto.auth.LoginRequest;
import com.billpaymentservice.bbps.dto.auth.OtpSendResponse;
import com.billpaymentservice.bbps.dto.auth.RegisterRequest;
import com.billpaymentservice.bbps.dto.auth.VerifyOtpRequest;
import com.billpaymentservice.bbps.service.AuthService;
@@ -71,7 +71,7 @@ public class ComplainController {
}
@PostMapping("/viewAllComplaints")
public ResponseEntity<ResponseModel> viewAllComplaints(@RequestBody ViewAllComplaintsTicketsRequest request) {
public ResponseEntity<ResponseModel> viewAllComplaints(@Validated @RequestBody ViewAllComplaintsTicketsRequest request) {
log.info("Received request complaint View All Complaints for Status Type={}", request.getStatusType());
ResponseModel response = complainService.ViewAllComplaints(request);
return ResponseEntity.ok(response);
@@ -1,5 +1,6 @@
package com.billpaymentservice.bbps.dto;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -10,6 +11,7 @@ import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
public class Tag {
private String name;
private String value;
private String name;
private String value;
}
@@ -13,19 +13,20 @@ import lombok.Setter;
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AuthResponse {
private boolean success;
private String message;
private boolean userExists;
private UserDto user;
private String token;
private boolean success;
private String message;
private boolean userExists;
private Object user;
private String token;
public AuthResponse(boolean success, String message, boolean userExists, UserDto user) {
this.success = success;
this.message = message;
this.userExists = userExists;
this.user = user;
}
public AuthResponse(boolean success, String message, String token) {
public AuthResponse(boolean success, String message, String token, Object user) {
this.success = success;
this.message = message;
this.token = token;
this.user = user;
}
public AuthResponse(boolean success, String message, String token) {
this.success = success;
this.message = message;
this.token = token;
@@ -1,19 +1,28 @@
package com.billpaymentservice.bbps.dto.auth;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public class LoginRequest {
private String mobile;
public LoginRequest() {}
@NotNull(message = "Mobile number cannot be null.")
@Size(min = 10, max = 10, message = "Mobile number must be exactly 10 digits.")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must contain only digits.")
private String mobile;
public LoginRequest(String mobile) {
this.mobile = mobile;
}
public LoginRequest() {
}
public String getMobile() {
return mobile;
}
public LoginRequest(String mobile) {
this.mobile = mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
@@ -2,15 +2,31 @@ package com.billpaymentservice.bbps.dto.auth;
import com.billpaymentservice.bbps.dto.request.BaseClass;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RegisterRequest extends BaseClass {
@NotNull(message = "Mobile number cannot be null.")
@Size(min = 10, max = 10, message = "Mobile number must be exactly 10 digits.")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must contain only 10 digits.")
private String mobile;
@NotNull(message = "Name cannot be null.")
@Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters.")
private String name;
@NotNull(message = "Email cannot be null.")
@Email(message = "Email must be a valid email address.")
private String email;
@NotNull(message = "Registration token cannot be null.")
private String registrationToken;
}
@@ -10,7 +10,7 @@ import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
public class UserDto {
private Long id;
private String userId;
private String mobile;
private String name;
private String email;
@@ -1,30 +1,42 @@
package com.billpaymentservice.bbps.dto.auth;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
public class VerifyOtpRequest {
private String mobile;
private String otp;
public VerifyOtpRequest() {
}
@NotNull(message = "Mobile number cannot be null.")
@Size(min = 10, max = 10, message = "Mobile number must be exactly 10 digits.")
@Pattern(regexp = "^[0-9]{10}$", message = "Mobile number must contain only digits.")
private String mobile;
public VerifyOtpRequest(String mobile, String otp) {
this.mobile = mobile;
this.otp = otp;
}
@NotNull(message = "OTP cannot be null.")
@Size(min = 6, max = 6, message = "OTP must be exactly 6 digits.")
@Pattern(regexp = "^[0-9]{6}$", message = "OTP must contain only 6 digits.")
private String otp;
public String getMobile() {
return mobile;
}
public VerifyOtpRequest() {
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public VerifyOtpRequest(String mobile, String otp) {
this.mobile = mobile;
this.otp = otp;
}
public String getOtp() {
return otp;
}
public String getMobile() {
return mobile;
}
public void setOtp(String otp) {
this.otp = otp;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
}
@@ -1,5 +1,7 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@@ -7,4 +9,10 @@ import lombok.Setter;
@Setter
public class AllMasterOptionsRequest extends BaseClass {
private Integer pageNo = 0;
@NotNull(message = "pageEnd is required")
@Min(value = 1, message = "pageEnd must be greater than 0")
private Integer pageSize;
}
@@ -1,6 +1,6 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -12,7 +12,7 @@ import lombok.Setter;
@NoArgsConstructor
public class BillFetchByBillIdRequest extends BaseClass {
@NotNull
@NotBlank(message = "bill id not be null")
private String billId;
}
@@ -1,6 +1,9 @@
package com.billpaymentservice.bbps.dto.request;
import java.util.List;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@@ -8,25 +11,47 @@ import lombok.Setter;
@Setter
public class BillPaymentRequest extends BaseClass {
private String tenantId;
private String refId;
private String billId;
private boolean amountOptions;
private String paymentMode;
private String paymentInformation;
private String billerId;
private String billerName;
private String billerCategory;
private String macAdress;
private String customerMobNo;
private Integer txnAmount;
private String paymentRefId;
private String clientReqId;
private String paymentChannel;
@NotBlank(message = "ref id cannot be null or empty")
private String refId;
private List<DeviceBlockTagRequest> deviceBlockTags;
private List<CustomerParamTagRequest> customerParamsRequest;
private List<RemitterIdentityRequest> remitterIdentity;
private List<AmountBreakRequest> amountBreakSet;
@NotBlank(message = "bill id cannot be null or empty")
private String billId;
// Change the field to Boolean (wrapper) type to allow @NotNull validation
@NotNull(message = "Amount options cannot be null.")
private boolean amountOptions; // Changed to Boolean (wrapper type)
@NotBlank(message = "payment mode cannot be null or empty")
private String paymentMode;
@NotBlank(message = "payment information cannot be null or empty")
private String paymentInformation;
@NotBlank(message = "biller id cannot be null or empty")
private String billerId;
@NotBlank(message = "biller name cannot be null or empty")
private String billerName;
@NotBlank(message = "biller category cannot be null or empty")
private String billerCategory;
private String macAdress;
private String customerMobNo;
@NotNull(message = "Transaction amount cannot be null.")
private Integer txnAmount; // Changed to @NotNull as it's an Integer (non-nullable)
private String paymentRefId;
private String clientReqId;
@NotBlank(message = "payment channel cannot be null or empty")
private String paymentChannel;
private List<DeviceBlockTagRequest> deviceBlockTags;
private List<CustomerParamTagRequest> customerParamsRequest;
private List<RemitterIdentityRequest> remitterIdentity;
private List<AmountBreakRequest> amountBreakSet;
}
@@ -1,5 +1,6 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@@ -10,7 +11,7 @@ import lombok.ToString;
@ToString(callSuper = true)
public class BillerDetailRequest extends BaseClass{
@NotNull
@NotBlank(message = "biller id not be null")
private String billerId;
}
@@ -1,8 +1,13 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotBlank;
public class CallbackRequest {
@NotBlank(message = "mid is mandatory")
private String mid;
@NotBlank(message = "data is mandatory")
private String data;
@NotBlank(message = "signature is mandatory")
private String signature;
public String getMid() {
@@ -1,7 +1,6 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -1,5 +1,7 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@@ -7,9 +9,16 @@ import lombok.Setter;
@Setter
public class ComplaintRequestDTO extends BaseClass {
private String ticketDescription; // Complaint description that the user enters
private String ticketDisposition; // Complaint disposition
private String ticketDispositionCode; // Type of complaint
private String txnId; // Transaction ID (optional)
@NotBlank(message = "Ticket description cannot be null.")
private String ticketDescription;
@NotBlank(message = "Ticket disposition cannot be null.")
private String ticketDisposition;
@NotBlank(message = "Ticket disposition code cannot be null.")
private String ticketDispositionCode;
@NotBlank(message = "Transaction ID cannot be null.")
private String txnId;
}
@@ -1,6 +1,6 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -14,6 +14,6 @@ import lombok.ToString;
@ToString
public class CustomParamRequest extends BaseClass {
@NotNull
@NotBlank(message = "biller id not be null")
private String billerId;
}
@@ -6,11 +6,13 @@ import com.billpaymentservice.bbps.dto.CustomerParamsRequest;
import com.billpaymentservice.bbps.dto.RemitterIdentity;
import com.billpaymentservice.bbps.dto.Tag;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@AllArgsConstructor
@@ -18,19 +20,29 @@ import lombok.ToString;
@ToString
public class FetchBillRequest extends BaseClass {
// private String tenantId; // M
private String billerId; // M
private String billerName; //M
// private String digiledgeKey; // M
// private String agentId; // M
private String billerCategory; // M
private String clientReqId; // C
private String macAdress; // C
private String customerMobNo; // M
private String remitterName; // O
private String paymentChannel; // M
private List<Tag> deviceBlockTags; // M
private CustomerParamsRequest customerParamsRequest; // M
private List<RemitterIdentity> remitterIdentity; // O
@NotBlank(message = "biller id not be null")
private String billerId;
@NotBlank(message = "biller name not be null")
private String billerName;
@NotBlank(message = "biller category not be null")
private String billerCategory;
private String clientReqId;
private String macAdress;
@NotBlank(message = "customer mob no not be null")
private String customerMobNo;
private String remitterName;
@NotBlank(message = "payment channel not be null")
private String paymentChannel;
private List<Tag> deviceBlockTags;
private CustomerParamsRequest customerParamsRequest;
private List<RemitterIdentity> remitterIdentity;
}
@@ -2,6 +2,7 @@ package com.billpaymentservice.bbps.dto.request;
import com.billpaymentservice.bbps.dto.CustomerParamsRequest;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -14,18 +15,18 @@ import lombok.Setter;
@NoArgsConstructor
public class FetchBillValidatestRequest extends BaseClass {
@NotNull
private String billerId; // Alphanumeric, Unique ID assigned by NPCI
@NotNull
private String billerName; // String, Name of the biller
@NotNull
private String billerCategory; // String, CategoryResponseList of the biller
@NotNull
private String customerMobNo; // String, Mobile of the Customer
@NotBlank(message = "biller id not be null")
private String billerId;
@NotBlank(message = "biller name not be null")
private String billerName;
@NotBlank(message = "biller category not be null")
private String billerCategory;
@NotBlank(message = "biller mob no not be null")
private String customerMobNo;
private String clientReqId;
// Optional Fields
private String macAddress; // Alphanumeric MAC Address of the Agent Server
//private String clientReqId; // String, Unique id provided by the client
private String macAddress;
// private String clientReqId;
private CustomerParamsRequest customerParamsRequest; // Customer parameters for identifying the bill
}
@@ -1,6 +1,7 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
@@ -15,7 +16,7 @@ public class MasterCategoryRequest extends BaseClass {
private String billerName;
@NotNull
@NotBlank(message = "category name not be null")
private String category;
private Integer pageNo = 0;
@@ -1,5 +1,7 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
@@ -7,4 +9,10 @@ import lombok.Setter;
@Setter
public class PaymentHistoryRequest extends BaseClass {
private Integer pageNo = 0;
@NotNull(message = "pageEnd is required")
@Min(value = 1, message = "pageEnd must be greater than 0")
private Integer pageSize;
}
@@ -2,6 +2,7 @@ package com.billpaymentservice.bbps.dto.request;
import java.io.Serializable;
import jakarta.validation.constraints.NotBlank;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -13,14 +14,21 @@ import lombok.Setter;
@AllArgsConstructor
// DTO representing the user request payload described by the user
public class PaymentStartUserRequest extends BaseClass implements Serializable {
@NotBlank(message = "amount can not be null")
private String amount;
private String currency;
private String emailId;
@NotBlank(message = "currency can not be null")
String currency;
@NotBlank(message = "customerVpa can not be null")
private String customerVpa;
private String mobileNo;
private String respUrl;
@NotBlank(message = "txnReqType can not be null")
private String txnReqType;
@NotBlank(message = "udf1(Latitude) can not be null")
private String udf1;
@NotBlank(message = "udf2(Longitude) can not be null")
private String udf2;
private String emailId;
private String mobileNo;
private String name;
}
@@ -1,6 +1,8 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@@ -26,8 +28,9 @@ public class PlanRequest extends BaseClass {
private String circle;
// ✅ Optional pagination parameters
private Integer page;
private Integer page = 0;
@NotNull(message = "pageEnd is required")
@Min(value = 1, message = "pageEnd must be greater than 0")
private Integer pagesize;
}
@@ -1,15 +1,18 @@
package com.billpaymentservice.bbps.dto.request;
import jakarta.validation.constraints.Min;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ViewAllComplaintsTicketsRequest extends BaseClass{
public class ViewAllComplaintsTicketsRequest extends BaseClass {
private String statusType; // e.g. COMPLAINT_OPEN_SUCCESS
private Integer pageNo; // default 0
private Integer pageSize; // default 10
@Min(value = 0, message = "Page number must be a non-negative integer.")
private Integer pageNo;
@Min(value = 1, message = "Page size must be at least 1.")
private Integer pageSize;
private String ticketType; // default 10
}
@@ -1,6 +1,7 @@
package com.billpaymentservice.bbps.dto.response;
import com.billpaymentservice.bbps.dto.TicketDetailsDTO;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@@ -9,9 +10,13 @@ public class TicketCheckStatusResponse {
private String refId;
private TicketDetailsDTO ticketDetails;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String message;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String remarks;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String status;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String statusCode;
}
@@ -26,11 +26,9 @@ public class AdditionalInfo {
private Long id; // primary key for the table
@Column(name = "param_config_id", nullable = false)
@NotBlank(message = "Param Config ID cannot be blank")
private String paramConfigId;
@Column(name = "param_name", nullable = false)
@NotBlank(message = "Param name cannot be blank")
private String paramName;
@Column(name = "data_type_dao")
@@ -35,4 +35,7 @@ public class AmountOptionDetails {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -1,4 +1,5 @@
package com.billpaymentservice.bbps.entites;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@@ -13,14 +14,17 @@ import lombok.NoArgsConstructor;
@Entity
@Table(name = "bill_initiate")
public class BillInitiate {
@Id
@Column(name = "req_id")
private String reqId;
@Column(name = "bill_id", nullable = false)
private String billId;
@Column(name = "txn_id")
private String txnId;
@Id
@Column(name = "req_id")
private String reqId;
@Column(name = "bill_id", nullable = false)
private String billId;
@Column(name = "txn_id")
private String txnId;
@Column(name = "client_user_id")
private String clientUserId;
}
@@ -1,7 +1,9 @@
package com.billpaymentservice.bbps.entites;
import java.util.List;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
@@ -23,27 +25,28 @@ import lombok.Setter;
@NoArgsConstructor
public class BillMaster {
@Id
private String billId; // primary key
@Id
private String billId; // primary key
private String reqId; // client se aaya hua
private String txnId; // system-generated
private String refId;
private String billerId;
private String status;
private String actionType;
private String userId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "biller_response_id")
private BillerResponse billerResponse;
@OneToMany(mappedBy = "billMaster", cascade = CascadeType.ALL)
private List<AdditionalInfoBill> additionalInfo;
@OneToMany(mappedBy = "billMaster", cascade = CascadeType.ALL)
private List<CustomerParamBill> customerParams;
private String creationDate;
private String modifiedDate;
private Long createdEpochDate;
private Long modifiedEpochDate;
private String reqId; // client se aaya hua
private String txnId; // system-generated
private String refId;
private String billerId;
private String status;
private String actionType;
private String clientUserId;
private String userId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "biller_response_id")
private BillerResponse billerResponse;
@OneToMany(mappedBy = "billMaster", cascade = CascadeType.ALL)
private List<AdditionalInfoBill> additionalInfo;
@OneToMany(mappedBy = "billMaster", cascade = CascadeType.ALL)
private List<CustomerParamBill> customerParams;
private String creationDate;
private String modifiedDate;
private Long createdEpochDate;
private Long modifiedEpochDate;
// getters and setters
// getters and setters
}
@@ -1,6 +1,5 @@
package com.billpaymentservice.bbps.entites;
import java.util.List;
import jakarta.persistence.*;
@@ -15,47 +14,56 @@ import lombok.NoArgsConstructor;
@NoArgsConstructor
public class BillValidation {
@Id
@Column(name = "bill_id", nullable = false, length = 100)
private String billId;
@Id
@Column(name = "bill_id", nullable = false, length = 100)
private String billId;
@Column(name = "ref_id", length = 100)
private String refId;
@Column(name = "ref_id", length = 100)
private String refId;
@Column(name = "biller_id", length = 100)
private String billerId;
@Column(name = "biller_id", length = 100)
private String billerId;
@Column(name = "status", length = 100)
private String status;
@Column(name = "status", length = 100)
private String status;
@Column(name = "action_type", length = 100)
private String actionType;
@Column(name = "action_type", length = 100)
private String actionType;
@Column(name = "user_id", length = 100)
private String userId;
@Column(name = "user_id", length = 100)
private String userId;
@Column(name = "biller_response", columnDefinition = "TEXT")
private String billerResponse;
@Column(name = "biller_response", columnDefinition = "TEXT")
private String billerResponse;
@OneToMany(mappedBy = "bill", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<AdditionalInfoBillValidate> additionalInfo;
@OneToMany(mappedBy = "bill", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<AdditionalInfoBillValidate> additionalInfo;
// 👇 Proper nested customer params (OneToMany)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "bill")
private List<CustomerParamBillValidation> customerParams;
// 👇 Proper nested customer params (OneToMany)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "bill")
private List<CustomerParamBillValidation> customerParams;
@Column(name = "plan_info_daos", columnDefinition = "TEXT")
private String planInfoDaos;
@Column(name = "plan_info_daos", columnDefinition = "TEXT")
private String planInfoDaos;
@Column(name = "creation_date", length = 50)
private String creationDate;
@Column(name = "creation_date", length = 50)
private String creationDate;
@Column(name = "modified_date", length = 50)
private String modifiedDate;
@Column(name = "modified_date", length = 50)
private String modifiedDate;
@Column(name = "created_epoch_date", length = 50)
private String createdEpochDate;
@Column(name = "created_epoch_date", length = 50)
private String createdEpochDate;
@Column(name = "modified_epoch_date", length = 50)
private String modifiedEpochDate;
@Column(name = "modified_epoch_date", length = 50)
private String modifiedEpochDate;
@Column(name = "txn_id")
private String txnId;
@Column(name = "req_id")
private String reqId;
@Column(name = "client_user_id")
private String clientUserId;
}
@@ -21,11 +21,9 @@ public class BillerAdditionalInfoPayment {
private Long id; // primary key for the table
@Column(name = "param_config_id", nullable = false)
@NotBlank(message = "Param Config ID cannot be blank")
private String paramConfigId;
@Column(name = "param_name", nullable = false)
@NotBlank(message = "Param name cannot be blank")
private String paramName;
@Column(name = "data_type_dao")
@@ -59,6 +59,9 @@ public class BillerCategoryWise extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
// One-to-One mapping with icon
@OneToOne(mappedBy = "biller", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private BillerCategoryIcon icon;
@@ -45,18 +45,15 @@ public class BillerDetails{
private String billerId;
@Column(name = "biller_name")
@NotBlank(message = "Biller name cannot be blank")
private String billerName;
@Column(name = "biller_alias_name")
private String billerAliasName;
@Column(name = "biller_category_name", nullable = false)
@NotBlank(message = "Biller category name cannot be blank")
@Column(name = "biller_category_name")
private String billerCategoryName;
@Column(name = "biller_mode")
@NotBlank(message = "Biller mode cannot be blank")
private String billerMode;
@Column(name = "biller_accepts_adhoc")
@@ -69,14 +66,12 @@ public class BillerDetails{
private String parentBillerId;
@Column(name = "biller_ownership")
@NotBlank(message = "Biller ownership is required (PSU or Private)")
private String billerOwnerShp;
@Column(name = "biller_coverage")
private String billerCoverage;
@Column(name = "fetch_requirement")
@NotBlank(message = "Fetch requirement is mandatory")
private String fetchRequirement;
@Column(name = "payment_amount_exactness")
@@ -24,7 +24,6 @@ public class BillerPlanResponseParams {
private Long id; // Primary Key
@Column(name = "biller_plan_response_id", nullable = false, unique = true)
@NotBlank(message = "Biller Plan Response ID cannot be blank")
private String billerPlanResponseId;
// ✅ params list — since it's not a separate table, we can store as JSON or text
@Column(name = "params", columnDefinition = "TEXT")
@@ -30,4 +30,7 @@ public class CategoryResponseList extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -68,4 +68,7 @@ public class ComplainStatus extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -23,25 +23,27 @@ public class ComplaintHistory extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long id;
@Column(name="history_id")
@Column(name = "history_id")
private String historyId;
@Column(name="ticket_id")
@Column(name = "ticket_id")
private String ticketId;
@Column(name="time")
@Column(name = "time")
private String time;
@Column(name="history_status")
@Column(name = "history_status")
private String historyStatus;
@Column(name = "txn_id")
private String txnId;
@Column(name = "req_id")
private String reqId;
@Column(name = "user_id")
private String userId;
}
@@ -10,10 +10,12 @@ import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Entity
@Getter
@Setter
@ToString
@Table(name = "complaint_responses")
public class ComplaintResponseEntity extends Auditable<String> {
@@ -15,18 +15,21 @@ import lombok.Setter;
@Getter
@Setter
@Table(name = "view_ticket_status")
public class ComplaintStatusDetails extends Auditable<String>{
public class ComplaintStatusDetails extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "req_id")
private String reqId;
@Column(name = "txn_id")
private String systemTxnId;
@Column(name = "user_id")
private String userId;
@Column(name = "total_elements")
private String totalElements;
@@ -33,4 +33,7 @@ public class ContactMasterData extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -1,5 +1,7 @@
package com.billpaymentservice.bbps.entites;
import com.billpaymentservice.bbps.audit.Auditable;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
@@ -15,32 +17,40 @@ import lombok.ToString;
@Entity
@ToString
@Table(name = "custom_param")
public class CustomParam {
public class CustomParam extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "custom_param_name")
private String customParamName;
@Column(name = "custom_param_name")
private String customParamName;
@Column(name = "data_type")
private String dataType;
@Column(name = "data_type")
private String dataType;
@Column(name = "optional")
private Boolean optional;
@Column(name = "optional")
private Boolean optional;
@Column(name = "min_length")
private Integer minLength;
@Column(name = "min_length")
private Integer minLength;
@Column(name = "max_length")
private Integer maxLength;
@Column(name = "max_length")
private Integer maxLength;
@Column(name = "regex")
private String regex;
@Column(name = "regex")
private String regex;
@Column(name = "visibility")
private Boolean visibility;
@Column(name = "visibility")
private Boolean visibility;
@Column(name = "req_id")
private String reqId;
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -56,4 +56,6 @@ public class CustomerParamGroupById extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -15,13 +15,22 @@ import lombok.ToString;
@ToString
public class DispositionDetails {
@Id
@Column(name = "disposition_id", nullable = false, unique = true)
private String dispositionId; // UUID type string
@Id
@Column(name = "disposition_id", nullable = false, unique = true)
private String dispositionId; // UUID type string
@Column(name = "disposition_descr", nullable = false)
private String dispositionDescr;
@Column(name = "disposition_descr", nullable = false)
private String dispositionDescr;
@Column(name = "tenant_id")
private String tenantId;
@Column(name = "tenant_id")
private String tenantId;
@Column(name = "req_id")
private String reqId;
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -29,11 +29,9 @@ public class InterchangeFee {
private Long id; // Primary key
@Column(name = "interchange_fee_id", nullable = false, unique = true)
@NotBlank(message = "Interchange Fee ID cannot be blank")
private String interchangeFeeId;
@Column(name = "fee_code", nullable = false)
@NotBlank(message = "Fee code is mandatory")
private String feeCode;
@Column(name = "fee_description")
@@ -27,7 +27,6 @@ public class InterchangeFeeConf {
private Long id; // Primary Key for DB table
@Column(name = "interchange_fee_conf_id", nullable = false, unique = true)
@NotBlank(message = "Interchange Fee Config ID cannot be blank")
private String interChangeFeeConfId;
@Column(name = "mti")
@@ -24,7 +24,6 @@ public class PaymentChannel {
@Column(name = "payment_channel_limit_id")
private String paymentChannelLimitId; // Primary key (manual, not auto-generated)
@NotBlank(message = "Payment channel is required")
@Column(name = "payment_channel", nullable = false)
private String paymentChannel;
@@ -8,7 +8,6 @@ import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@@ -16,22 +15,25 @@ import lombok.NoArgsConstructor;
@Table(name = "payment_initiate")
public class PaymentInitiate {
@Id
@Column(name = "req_id")
private String reqId;
@Id
@Column(name = "req_id")
private String reqId;
@Column(name = "bank_txn_Id", nullable = false)
private String bankTxnId;
@Column(name = "client_user_id")
private String clientUserId;
@Column(name = "mid")
private String mid;
@Column(name = "bank_txn_Id", nullable = false)
private String bankTxnId;
@Column(name = "txn_id")
private String txnId;
@Column(name = "client_user_id")
private String clientUserId;
@Column(name = "status")
private String status;
@Column(name = "mid")
private String mid;
@Column(name = "txn_id")
private String txnId;
@Column(name = "status")
private String status;
@Column(name = "user_id")
private String userId;
}
@@ -26,11 +26,9 @@ public class PaymentMode {
@Id //
@Column(name = "payment_model_limit_id", unique = true, length = 50)
@NotBlank(message = "Payment model limit ID cannot be blank")
private String paymentModelLimitId;
@Column(name = "payment_mode", nullable = false, length = 50)
@NotBlank(message = "Payment mode is mandatory")
private String paymentMode;
@Column(name = "max_limit")
@@ -42,7 +40,6 @@ public class PaymentMode {
private long minLimit;
@Column(name = "support_pending_status", length = 10)
@Pattern(regexp = "^(Yes|No)?$", message = "Support pending status must be either 'Yes' or 'No'")
private String supportPendingStatus;
// 🔗 Many-to-One relationship with BillerDAO
@@ -47,4 +47,7 @@ public class PlanResponses extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -41,4 +41,6 @@ public class TicketDispositionDetails extends Auditable<String> {
@Column(name = "txn_id")
private String txnId;
@Column(name = "user_id")
private String userId;
}
@@ -27,6 +27,9 @@ public class ViewAllComplaintTicketStatusDetails extends Auditable<String> {
@Column(name = "txn_id")
private String systemTxnId;
@Column(name = "user_id")
private String userId;
@Column(name = "total_elements")
private String totalElements;
@@ -1,7 +1,7 @@
package com.billpaymentservice.bbps.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@@ -12,6 +12,9 @@ import com.billpaymentservice.bbps.entites.ComplaintResponseEntity;
@Repository
public interface ComplaintResponseRepository extends JpaRepository<ComplaintResponseEntity, Long> {
// @Query("SELECT c FROM ComplaintResponseEntity c WHERE c.userId = :userId")
// List<ComplaintResponseEntity> findByUserIdCustom(@Param("userId") String userId);
@Query("SELECT c FROM ComplaintResponseEntity c WHERE c.userId = :userId")
List<ComplaintResponseEntity> findByUserIdCustom(@Param("userId") String userId);
Page<ComplaintResponseEntity> findByUserIdCustom(@Param("userId") String userId, Pageable pageable);
}
@@ -6,14 +6,24 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.billpaymentservice.bbps.entites.TransactionMaster;
public interface TransactionMasterRepository extends JpaRepository<TransactionMaster, String> {
@Query("SELECT t FROM TransactionMaster t WHERE t.mid = :mid OR t.clientUserId = :clientUserId")
List<TransactionMaster> findByMidOrClientUserId(@Param("mid") String mid,
@Param("clientUserId") String clientUserId);
// @Query("SELECT t FROM TransactionMaster t WHERE t.mid = :mid OR t.clientUserId = :clientUserId")
// List<TransactionMaster> findByMidOrClientUserId(@Param("mid") String mid,
// @Param("clientUserId") String clientUserId);
//
@Query("SELECT t FROM TransactionMaster t WHERE t.mid = :mid")
Page<TransactionMaster> findByMid(@Param("mid") String mid, Pageable pageable);
@Query("SELECT t FROM TransactionMaster t WHERE t.mid = :mid AND t.clientUserId = :clientUserId")
Page<TransactionMaster> findByMidOrClientUserId(@Param("mid") String mid,
@Param("clientUserId") String clientUserId, Pageable pageable);
@Query("SELECT t FROM TransactionMaster t WHERE t.txnId = :txnId")
List<TransactionMaster> findByTxnId(@Param("txnId") String txnId);
@@ -120,6 +120,7 @@ public class AgentServiceImpl implements AgentService {
billMaster.setBillId((String) dataMap.get("billId"));
billMaster.setReqId(fetchBillRequest.getReqId());
billMaster.setTxnId(txnId);
billMaster.setClientUserId(fetchBillRequest.getClientUserId());
billMasterRepository.save(billMaster);
LOGGER.info("BillMaster saved for billId: {}", billMaster.getBillId());
@@ -131,6 +132,7 @@ public class AgentServiceImpl implements AgentService {
billInitiate.setBillId((String) dataMap.get("billId"));
billInitiate.setReqId(fetchBillRequest.getReqId());
billInitiate.setTxnId(txnId);
billInitiate.setClientUserId(fetchBillRequest.getClientUserId());
billIntiateRepository.save(billInitiate);
LOGGER.info("BillInitiate entry saved for billId: {}", billInitiate.getBillId());
@@ -162,6 +164,7 @@ public class AgentServiceImpl implements AgentService {
String txnId = helper.generateTxnId(15);
String reqId = billFetchByBillIdRequest.getReqId();
String billId = billFetchByBillIdRequest.getBillId();
String userId = billFetchByBillIdRequest.getClientUserId();
String fullUrl = agentDtaUrl + BBPSConstant.BILL_FETCH_BY_ID + billFetchByBillIdRequest.getBillId();
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, reqId, apiName, fullUrl, BBPSConstant.HTTP_GET,
null);
@@ -195,7 +198,7 @@ public class AgentServiceImpl implements AgentService {
LOGGER.info("Current Bill Status: {}", status);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
mapperHelper.saveOrUpdateBillData(responseWrapper, billFetchByBillIdRequest, txnId);
mapperHelper.saveOrUpdateBillData(responseWrapper, billFetchByBillIdRequest, txnId, reqId, userId);
LOGGER.info("Bill data saved successfully for billId: {}", billId);
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -214,8 +217,9 @@ public class AgentServiceImpl implements AgentService {
String reqId = billFetchByBillIdRequest.getReqId();
String billId = billFetchByBillIdRequest.getBillId();
String mid = billFetchByBillIdRequest.getMid();
String userId = billFetchByBillIdRequest.getClientUserId();
String requestJson = helper.convertObjectToJson(billFetchByBillIdRequest);
LOGGER.info("[{}] START | reqId={} | mid={} | billId={}", apiName, reqId, mid, billId);
LOGGER.info("[{}] START | reqId={} | mid={} | billId={} | userId={}", apiName, reqId, mid, billId, userId);
String fullUrl = agentDtaUrl + BBPSConstant.BILL_FETCH_BY_ID + billFetchByBillIdRequest.getBillId();
String txnId = helper.generateTxnId(15);
InboundTraceLog inboundLog = helper.createInboundLog(reqId, txnId, apiName, billFetchByBillIdRequest.getMid(),
@@ -251,7 +255,7 @@ public class AgentServiceImpl implements AgentService {
// update inbound log success and persist bill data
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
mapperHelper.saveOrUpdateBillData(responseWrapper, billFetchByBillIdRequest, txnId);
mapperHelper.saveOrUpdateBillData(responseWrapper, billFetchByBillIdRequest, txnId, reqId, userId);
LOGGER.info("Bill data saved successfully for billId={} | Status={}", billId, generalResp.getStatus());
LOGGER.info("[{}] END | reqId={} | status={}", apiName, reqId, generalResp.getStatus());
return responseModel;
@@ -394,7 +398,7 @@ public class AgentServiceImpl implements AgentService {
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
System.out.println("responseWrapper:" + responseWrapper);
mapperHelper.saveBillValidation(responseWrapper, billRequest);
mapperHelper.saveBillValidation(responseWrapper, billRequest, txnId);
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
} catch (JsonProcessingException e) {
@@ -412,7 +416,7 @@ public class AgentServiceImpl implements AgentService {
String reqId = billRequest.getReqId();
String billId = billRequest.getBillId();
String mid = billRequest.getMid();
String requestJson = helper.convertObjectToJson(billRequest);
String requestJson = helper.convertObjectToJson(billRequest);
LOGGER.info("[{}] START | reqId={} | mid={} | billId={}", apiName, billRequest, mid, billId);
String txnId = helper.generateTxnId(15);
String fullUrl = agentDtaUrl + BBPSConstant.BILL_VALIDATE_ID_URL + billRequest.getBillId();
@@ -452,7 +456,7 @@ public class AgentServiceImpl implements AgentService {
GeneralResp generalResp = responseWrapper.getGenericResponse();
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
mapperHelper.saveBillValidation(responseWrapper, billRequest);
mapperHelper.saveBillValidation(responseWrapper, billRequest, txnId);
LOGGER.info("Bill validation saved successfully for billId: {}", billId);
LOGGER.info("[{}] END | reqId={} | status={}", apiName, reqId, generalResp.getStatus());
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -484,8 +488,8 @@ public class AgentServiceImpl implements AgentService {
String requestJson = helper.convertObjectToJson(billValidateByClientIdRequest);
LOGGER.info("[{}] START | reqId={} | mid={} | clientReqId={}", apiName, reqId, mid,
billValidateByClientIdRequest.getClientReqId());
InboundTraceLog inboundLog = helper.createInboundLog(reqId, txnId, apiName,
billValidateByClientIdRequest.getMid(), BBPSConstant.HTTP_GET,requestJson);
InboundTraceLog inboundLog = helper.createInboundLog(reqId, txnId, apiName,
billValidateByClientIdRequest.getMid(), BBPSConstant.HTTP_GET, requestJson);
helper.validateMerchant(billValidateByClientIdRequest.getMid());
Optional<BillInitiate> billInitiate = billIntiateRepository.findByReqId(clientReqId);
@@ -142,8 +142,8 @@ public class AuthServiceImpl implements AuthService {
Optional<UserEntity> existing = userRepository.findByMobile(request.getMobile());
if (existing.isPresent()) {
UserEntity u = existing.get();
UserDto dto = new UserDto(u.getId(), u.getMobile(), u.getName(), u.getEmail());
AuthResponse ar = new AuthResponse(false, "User already exists", true, dto);
UserDto dto = new UserDto(u.getUserId(), u.getMobile(), u.getName(), u.getEmail());
AuthResponse ar = new AuthResponse(false, "User already exists", null, dto);
return ResponseModel.builder().message(ar.getMessage()).status("Failure").statusCode(409).data(ar)
.build();
}
@@ -151,9 +151,11 @@ public class AuthServiceImpl implements AuthService {
UserEntity userEntity = helper.createNewUser(request);
userRepository.save(userEntity);
String token = jwtUtil.generateToken(userEntity.getMobile());
UserDto dto = new UserDto(userEntity.getId(), userEntity.getMobile(), userEntity.getName(),
userEntity.getEmail());
AuthResponse ar = new AuthResponse(true, "user registed sucessfully", token);
// UserDto dto = new UserDto(userEntity.getUserId(), userEntity.getMobile(), userEntity.getName(),
// userEntity.getEmail());
Object userDetailsDTO = helper.mapUserToUserDetailsDTO(userEntity);
AuthResponse ar = new AuthResponse(true, "user registered successfully", token, userDetailsDTO);
return ResponseModel.builder().message(ar.getMessage()).status("Success").statusCode(201).data(ar).build();
} catch (ExpiredJwtException e) {
LOGGER.error("Token has expired: {}", e.getMessage());
@@ -8,6 +8,9 @@ import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
@@ -124,8 +127,8 @@ public class ComplainServiceImpl implements ComplainService {
Optional<TransactionMaster> dataById = transactionMasterRepository.findById(complainRequestDTO.getTxnId());
if (dataById == null || dataById.isEmpty()) {
LOGGER.warn("Txn Id is null");
throw new CustomException("Txn Id is required", "FAILED", BBPSConstant.BADREQUEST, null);
LOGGER.warn("Txn Data Not Found This Txn Id is null");
throw new CustomException(BBPSConstant.USER_Txn_IS_NOT_FOUND, "FAILED", BBPSConstant.BADREQUEST, null);
}
TransactionMaster transData = dataById.get();
@@ -216,8 +219,8 @@ public class ComplainServiceImpl implements ComplainService {
String complaintId = request.getTicketId();
String mid = request.getMid();
String ticketId = request.getTicketId();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={}", apiName, reqId, mid, ticketId);
String userId = request.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={} | userId={}", apiName, reqId, mid, ticketId, userId);
String fullUrl = agentDtaUrl + BBPSConstant.COMPALINT_STATUS;
String txnId = helper.generateTxnId(15);
@@ -277,7 +280,7 @@ public class ComplainServiceImpl implements ComplainService {
TicketCheckStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TicketCheckStatusResponse.class);
String saveComplaintStatus = mapperHelper.saveComplaintStatus(responseWrapper, reqId, txnId);
String saveComplaintStatus = mapperHelper.saveComplaintStatus(responseWrapper, reqId, txnId, userId);
LOGGER.info("[{}] Save Status | ticketId={} | status={}", apiName, ticketId, saveComplaintStatus);
helper.updateInboundLogSuccess(inboundLog, responseData, responseWrapper.getStatus());
@@ -298,8 +301,8 @@ public class ComplainServiceImpl implements ComplainService {
String reqId = request.getReqId();
String ticketId = request.getTicketId();
String mid = request.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={}", apiName, reqId, mid, ticketId);
String userId = request.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={} | userId={}", apiName, reqId, mid, ticketId, userId);
String fullUrl = agentDtaUrl + BBPSConstant.COMPLAINT_HISTORY + request.getTicketId();
String txnId = helper.generateTxnId(15);
@@ -345,7 +348,7 @@ public class ComplainServiceImpl implements ComplainService {
LOGGER.info("Current Complaint ReOpen Status: {}", status);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
String saveComplaintHistory = mapperHelper.saveComplaintHistory(responseWrapper, reqId, txnId);
String saveComplaintHistory = mapperHelper.saveComplaintHistory(responseWrapper, reqId, txnId, userId);
LOGGER.info("[{}] Complaint history saved | ticketId={} | entryId={}", apiName, ticketId,
saveComplaintHistory);
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -364,7 +367,8 @@ public class ComplainServiceImpl implements ComplainService {
String reqId = request.getReqId();
String ticketId = request.getTicketId();
String mid = request.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={}", apiName, reqId, mid, ticketId);
String userId = request.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | ticketId={} | userId={}", apiName, reqId, mid, ticketId, userId);
String txnId = helper.generateTxnId(15);
String fullUrl = agentDtaUrl + BBPSConstant.VIEW_COMPLAINT_BY_ID + request.getTicketId();
@@ -408,7 +412,7 @@ public class ComplainServiceImpl implements ComplainService {
LOGGER.info("Current Complaint ReOpen Status: {}", status);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
String saveComplaint = mapperHelper.saveComplainStatusDetail(responseWrapper, reqId, txnId);
String saveComplaint = mapperHelper.saveComplainStatusDetail(responseWrapper, reqId, txnId, userId);
LOGGER.info("[{}] Complaint details saved | ticketId={} | id={}", apiName, ticketId, saveComplaint);
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -540,8 +544,9 @@ public class ComplainServiceImpl implements ComplainService {
String reqId = request.getReqId();
String mid = request.getMid();
String statusType = request.getStatusType();
LOGGER.info("[{}] START | reqId={} | mid={} | statusType={}", apiName, reqId, mid, statusType);
String userId = request.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | statusType={} | userId={}", apiName, reqId, mid, statusType,
userId);
String txnId = helper.generateTxnId(15);
String fullUrl = complainDataUrl + BBPSConstant.VIEW_ALL_COMPLAINTS_BASE + "?pageNo=" + request.getPageNo()
+ "&pageSize=" + request.getPageSize() + "&statusType=" + request.getStatusType() + "&ticketType="
@@ -586,7 +591,7 @@ public class ComplainServiceImpl implements ComplainService {
String status = generalResp.getStatus();
LOGGER.info("Current Complaint ReOpen Status: {}", status);
String saveComplaint = mapperHelper.saveAllComplaints(responseWrapper, reqId, txnId);
String saveComplaint = mapperHelper.saveAllComplaints(responseWrapper, reqId, txnId, userId);
LOGGER.info("[{}] Complaint records saved into DB | count={}", apiName, saveComplaint);
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -632,7 +637,12 @@ public class ComplainServiceImpl implements ComplainService {
// Log the call to external API
LOGGER.info("[{}] Calling external API | URL={}", apiName, apiName);
List<ComplaintResponseEntity> complaintUserData = complaintResponseRepository.findByUserIdCustom(userId);
// List<ComplaintResponseEntity> complaintUserData =
// complaintResponseRepository.findByUserIdCustom(userId);
Pageable pageable = PageRequest.of(request.getPageNo(), request.getPageSize());
Page<ComplaintResponseEntity> complaintUserData = complaintResponseRepository.findByUserIdCustom(userId,
pageable);
// Check if complaints were found
if (complaintUserData == null || complaintUserData.isEmpty()) {
@@ -642,15 +652,17 @@ public class ComplainServiceImpl implements ComplainService {
}
// Log the number of complaints fetched
LOGGER.info("[{}] Complaints found for userId={} | count={}", apiName, userId, complaintUserData.size());
LOGGER.info("[{}] Complaints found for userId={} | count={}", apiName, userId,
complaintUserData.getContent().size());
// Update outbound log with the count
String count = String.valueOf(complaintUserData.size());
String count = String.valueOf(complaintUserData.getContent().size());
helper.updateOutboundLogResponse(outboundLog, count);
// Return successful response with complaints data
return new ResponseModel(BBPSConstant.ALL_COMPLAINT_FIELDS_FETCH, BBPSConstant.SUCCESS_RESPONSE,
BBPSConstant.HTTP_OK_INT, complaintUserData, complaintUserData.size());
BBPSConstant.HTTP_OK_INT, complaintUserData.getContent(), // Only the list of complaints (data)
complaintUserData.getContent().size());
} catch (CustomException e) {
// Rethrow custom exception for handling at the controller level
@@ -220,7 +220,7 @@ public class MasterDataServiceImpl implements MasterDataService {
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
BillerDetails entity = mapper.map(responseWrapper.getBillerDAO(), BillerDetails.class);
EntityRelationshipUtil.linkBillerRelationships(entity);// linking nesting entity foreign key
//mapperHelper.saveOrUpdateBillerData(entity);
// mapperHelper.saveOrUpdateBillerData(entity);
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
@@ -239,9 +239,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_GET_CUSTOMER_PARAM_BY_BILLER_ID;
String requestId = customerParamRequest.getReqId();
String mid = customerParamRequest.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={}", apiName, requestId, mid,
customerParamRequest.getBillerId());
String userId = customerParamRequest.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={} | userId={}", apiName, requestId, mid,
customerParamRequest.getBillerId(), userId);
String txnID = helper.generateTxnId(15);
String billerId = customerParamRequest.getBillerId();
String fullUrl = masterRegisterUrl + BBPSConstant.CUSTOMPARAM_URL + billerId;
@@ -282,8 +282,13 @@ public class MasterDataServiceImpl implements MasterDataService {
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
// Map DTOs to entities
List<CustomParam> entities = customParams.stream().map(dto -> mapper.map(dto, CustomParam.class))
.collect(Collectors.toList());
List<CustomParam> entities = customParams.stream().map(dto -> {
CustomParam mappedParam = mapper.map(dto, CustomParam.class);
mappedParam.setReqId(requestId);
mappedParam.setTxnId(txnID);
mappedParam.setUserId(userId);
return mappedParam;
}).collect(Collectors.toList());
// Save all to DB
customParamReposiotory.saveAll(entities);
LOGGER.info("[{}] Saved {} custom param records to DB", apiName, entities.size());
@@ -306,8 +311,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_CATEGORY_MASTER_DATA;
String requestId = contactMasterRequest.getReqId();
String mid = contactMasterRequest.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | category={}", apiName, requestId, contactMasterRequest.getMid(),
contactMasterRequest.getCategory());
String userId = contactMasterRequest.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | category={} | userId={}", apiName, requestId,
contactMasterRequest.getMid(), contactMasterRequest.getCategory(), userId);
String txnID = helper.generateTxnId(15);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
@@ -345,8 +351,8 @@ public class MasterDataServiceImpl implements MasterDataService {
}
ContactMasterResponse responseWrapper = objectMapper.convertValue(dataMap, ContactMasterResponse.class);
String result = mapperHelper.saveContactMasterData(responseWrapper.getContactMasterList(), requestId,
txnID);
String result = mapperHelper.saveContactMasterData(responseWrapper.getContactMasterList(), requestId, txnID,
userId);
LOGGER.info("[{}] DB Save Result | reqId={} | result={}", apiName, requestId, result);
GeneralResp generalResp = responseWrapper.getGeneralResp();
@@ -371,9 +377,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_MASTER_DATA_CATEGORY_WISE;
String requestId = masterRequest.getReqId();
String mid = masterRequest.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerName={} | category={}", apiName, requestId, mid,
masterRequest.getBillerName(), masterRequest.getCategory());
String userId = masterRequest.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerName={} | category={} | userId={}", apiName, requestId, mid,
masterRequest.getBillerName(), masterRequest.getCategory(), userId);
String txnID = helper.generateTxnId(15);
String fullUrl = String.format("%s%s?billerName=%s&category=%s&page=%d&pagesize=%d", masterRegisterUrl,
@@ -414,7 +420,7 @@ public class MasterDataServiceImpl implements MasterDataService {
BillerResponse responseWrapper = objectMapper.convertValue(dataMap, BillerResponse.class);
List<BillerCategoryWise> savedEntities = mapperHelper.mapAndSaveAll(responseWrapper.getBillerResp(),
requestId, txnID);
requestId, txnID, userId);
LOGGER.info("[{}] Saved {} records to DB | reqId={}", apiName, savedEntities.size(), requestId);
GeneralResp generalResp = responseWrapper.getGeneralResp();
@@ -439,7 +445,8 @@ public class MasterDataServiceImpl implements MasterDataService {
String requestId = dispositionDetailRequest.getReqId();
String mid = dispositionDetailRequest.getMid();
String requestJson = helper.convertObjectToJson(dispositionDetailRequest);
LOGGER.info("[{}] START | reqId={} | mid={}", apiName, requestId, mid);
String userId = dispositionDetailRequest.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | userId={}", apiName, requestId, mid, userId);
String txnID = helper.generateTxnId(15);
String fullUrl = masterRegisterUrl + BBPSConstant.DISPOSTION_URL;
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName,
@@ -474,15 +481,23 @@ public class MasterDataServiceImpl implements MasterDataService {
GeneralResp generalResp = responseWrapper.getGeneralResp();
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
List<DispositionDetails> entities = responseWrapper.getDispositionsList().stream()
.map(dto -> mapper.map(dto, DispositionDetails.class)).collect(Collectors.toList());
// Assuming responseWrapper contains the data you need to map to
// DispositionDetails
List<DispositionDetails> entities = responseWrapper.getDispositionsList().stream().map(dto -> {
DispositionDetails disposition = mapper.map(dto, DispositionDetails.class);
disposition.setReqId(requestId);
disposition.setTxnId(txnID);
disposition.setUserId(userId);
return disposition;
}).collect(Collectors.toList());
LOGGER.info("[{}] Dispositions Received: {}", apiName, entities.size());
if (entities != null) {
dispositionRepository.saveAll(entities);
} else {
LOGGER.warn("No disposition found in response to save.");
if (entities != null && !entities.isEmpty()) {
dispositionRepository.saveAll(entities); // Save the list of entities
} else {
LOGGER.warn("No dispositions found in response to save.");
}
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -506,9 +521,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_CUSTOMER_PARAM_GROUP;
String requestId = requestModel.getReqId();
String mid = requestModel.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={}", apiName, requestId, mid,
requestModel.getBillerId());
String userId = requestModel.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={} | userId={}", apiName, requestId, mid,
requestModel.getBillerId(), userId);
helper.validateMerchant(mid);
String txnID = helper.generateTxnId(15);
String fullUrl = masterRegisterUrl + BBPSConstant.CUSTOMER_PARAM_GROUP + requestModel.getBillerId();
@@ -543,7 +558,7 @@ public class MasterDataServiceImpl implements MasterDataService {
GeneralResp generalResp = responseWrapper.getGeneralResp();
CustomerParamGroupsDTO responseDTO = mapperHelper
.saveCustomerParamGroups(responseWrapper.getCustomerParamGroupResp(), requestId, txnID);
.saveCustomerParamGroups(responseWrapper.getCustomerParamGroupResp(), requestId, txnID, userId);
LOGGER.info("[{}] Saved {} Customer Param Group records | reqId={}", apiName, responseDTO.toString(),
requestId);
@@ -569,9 +584,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_ALL_MASTER_AMOUNT_OPTION;
String requestId = requestModel.getReqId();
String mid = requestModel.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={}", apiName, requestId, mid,
requestModel.getBillerId());
String userId = requestModel.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={} | userId={}", apiName, requestId, mid,
requestModel.getBillerId(), userId);
String txnID = helper.generateTxnId(15);
String fullUrl = masterRegisterUrl + BBPSConstant.AMOUNT_OPTIONS + requestModel.getBillerId();
@@ -607,8 +622,8 @@ public class MasterDataServiceImpl implements MasterDataService {
AmountOptionsResponse responseWrapper = objectMapper.convertValue(dataMap, AmountOptionsResponse.class);
String saveAmountOptionsResponse = mapperHelper.saveAmountOptionsResponse(responseWrapper, requestId,
txnID);
String saveAmountOptionsResponse = mapperHelper.saveAmountOptionsResponse(responseWrapper, requestId, txnID,
userId);
LOGGER.info("[{}] Save Result | reqId={} | result={}", apiName, requestId, saveAmountOptionsResponse);
GeneralResp generalResp = responseWrapper.getGeneralResp();
@@ -635,8 +650,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_PLAN_CATEGORIES;
String requestId = requestModel.getReqId();
String mid = requestModel.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={}", apiName, requestId, mid,
requestModel.getBillerId());
String userId = requestModel.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={} | userId={}", apiName, requestId, mid,
requestModel.getBillerId(), userId);
helper.validateMerchant(requestModel.getMid());
String txnID = helper.generateTxnId(15);
String fullUrl = masterRegisterUrl + BBPSConstant.PLAN_CATEGORIES + requestModel.getBillerId();
@@ -672,7 +688,7 @@ public class MasterDataServiceImpl implements MasterDataService {
PlaneCategoriesResponse responseWrapper = objectMapper.convertValue(dataMap, PlaneCategoriesResponse.class);
String saveCategoryItems = mapperHelper.saveCategoryItems(responseWrapper.getCategoryRespList(), requestId,
txnID);
txnID, userId);
LOGGER.info("[{}] Saved category items | reqId={} | count={}", apiName, requestId, saveCategoryItems);
GeneralResp generalResp = responseWrapper.getGeneralResp();
@@ -754,8 +770,9 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_FETCH_PLAN_BY_CATEGORIES;
String requestId = requestModel.getReqId();
String mid = requestModel.getMid();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={}", apiName, requestId, mid,
requestModel.getBillerId());
String userId = requestModel.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | billerId={} | userId={}", apiName, requestId, mid,
requestModel.getBillerId(), userId);
String txnID = helper.generateTxnId(15);
String url = String.format("%s%s?billerId=%s%s%s%s&page=%d&pagesize=%d", masterRegisterUrl,
BBPSConstant.PLANS_URL, requestModel.getBillerId(),
@@ -802,7 +819,7 @@ public class MasterDataServiceImpl implements MasterDataService {
PlanResponse responseWrapper = objectMapper.convertValue(dataMap, PlanResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
PlanResponses savePlanResponse = mapperHelper.savePlanResponse(responseWrapper, requestId, txnID);
PlanResponses savePlanResponse = mapperHelper.savePlanResponse(responseWrapper, requestId, txnID, userId);
LOGGER.info("[{}] Saved Plans | reqId={} | count={}", apiName, requestId, savePlanResponse);
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
@@ -824,8 +841,8 @@ public class MasterDataServiceImpl implements MasterDataService {
String apiName = BBPSConstant.API_GET_TICKET_DISPOSITIONS;
String requestId = dispositionDetailRequest.getReqId();
String mid = dispositionDetailRequest.getMid();
LOGGER.info("[{}] START | reqId={} | mid={}", apiName, requestId, mid);
String userId = dispositionDetailRequest.getClientUserId();
LOGGER.info("[{}] START | reqId={} | mid={} | userId={}", apiName, requestId, mid, userId);
String txnID = helper.generateTxnId(15);
String fullUrl = masterRegisterUrl + BBPSConstant.TICKET_DISPOSTION_URL;
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName,
@@ -862,7 +879,7 @@ public class MasterDataServiceImpl implements MasterDataService {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
mapperHelper.saveTicketDisoptionDetails(responseWrapper.getDispositionsList(), requestId, txnID);
mapperHelper.saveTicketDisoptionDetails(responseWrapper.getDispositionsList(), requestId, txnID, userId);
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
@@ -45,355 +45,361 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class PaymentServiceImpl implements PaymentService {
@Value("${payment.data.url}")
private String paymentUrl;
private final BharatConnectMasterRepository beneficiaryDetailsRepository;
private final HttpService httpService;
private final Helper helper;
private final PaymentRepository paymentRepository;
private final InboundTraceLogRepository inboundTraceLogRepository;
private final OutboundTraceLogRepository outboundTraceLogRepository;
private final PaymentIntiateRepository paymentIntiateRepository;
private final TransactionMasterRepository transactionMasterRepository;
private final AgentFundTransferRepository agentFundTransferRepository;
private final BillerMapperHelper mapperHelper;
// Shared reusable instances
private final ObjectMapper objectMapper;
private final ModelMapper modelMapper;
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);
public PaymentServiceImpl(BharatConnectMasterRepository beneficiaryDetailsRepository, HttpService httpService,
Helper helper, PaymentRepository paymentRepository, InboundTraceLogRepository inboundTraceLogRepository,
OutboundTraceLogRepository outboundTraceLogRepository, PaymentIntiateRepository paymentIntiateRepository,
TransactionMasterRepository transactionMasterRepository,
AgentFundTransferRepository agentFundTransferRepository,
BillerMapperHelper mapperHelper) {
this.beneficiaryDetailsRepository = beneficiaryDetailsRepository;
this.httpService = httpService;
this.helper = helper;
this.paymentRepository = paymentRepository;
this.inboundTraceLogRepository = inboundTraceLogRepository;
this.outboundTraceLogRepository = outboundTraceLogRepository;
this.paymentIntiateRepository = paymentIntiateRepository;
this.transactionMasterRepository = transactionMasterRepository;
this.agentFundTransferRepository = agentFundTransferRepository;
this.mapperHelper = mapperHelper;
this.objectMapper = new ObjectMapper();
this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.modelMapper = new ModelMapper();
this.modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
@Override
public ResponseModel initiatePayment(BillPaymentRequest billPaymentRequest) {
String apiName = BBPSConstant.API_INITIATE_PAYMENT;
String txnId = helper.generateTxnId(15);
String requestId = billPaymentRequest.getReqId();
String url = paymentUrl + BBPSConstant.PAYMENT_URL;
billPaymentRequest.setClientReqId(txnId);
LOGGER.info("Initiating payment for reqId={} and txnId={}", requestId, txnId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
BillPaymentForwardRequest forwardReq = mapperHelper.billPaymentForwardRequest(billPaymentRequest);
String forwardjson = helper.convertObjectToJson(forwardReq);
String requestJson = helper.convertObjectToJson(billPaymentRequest);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnId, apiName, billPaymentRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, BBPSConstant.HTTP_POST, forwardjson);
LOGGER.debug("Outbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
try {
LOGGER.info("Calling BBPS payment URL: {}", url);
Map<String, String> responseMap = httpService.postRequest(url, forwardjson, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Payment API Response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for txnId={}", txnId);
if (responseData == null || responseData.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.EMPTY_RESPONSE_FROM_BBPS, BBPSConstant.FAILED_STR);
LOGGER.warn("Empty response received from BBPS for txnId={}", txnId);
throw new CustomException(BBPSConstant.EMPTY_RESPONSE_FROM_BBPS);
}
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERIC_KEY)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_STRUCTURE);
LOGGER.warn("Invalid response structure received for txnId={}", txnId);
throw new CustomException(BBPSConstant.INVALID_STRUCTURE);
}
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
BillPayment entity = modelMapper.map(billPaymentResponse, BillPayment.class);
paymentRepository.save(entity);
LOGGER.info("BillPayment entity saved successfully for txnId={}", txnId);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
PaymentInitiate paymentInitiate = new PaymentInitiate();
paymentInitiate.setTxnId(txnId);
paymentInitiate.setReqId(requestId);
paymentInitiate.setMid(billPaymentRequest.getMid());
paymentInitiate.setClientUserId(billPaymentRequest.getClientUserId());
paymentInitiate.setBankTxnId(billPaymentResponse.getTxnId());
paymentInitiate.setStatus(billPaymentResponse.getStatus());
paymentIntiateRepository.save(paymentInitiate);
LOGGER.info("PaymentInitiate entry saved successfully for txnId={}", txnId);
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
transactionStatusRequest.setTxnId(billPaymentResponse.getTxnId());
transactionStatusRequest.setReqId(requestId);
transactionStatusRequest.setMid(billPaymentRequest.getMid());
transactionStatusRequest.setClientUserId(billPaymentRequest.getClientUserId());
try {
Thread.sleep((long) BBPSConstant.PAYMENT_STATUS_DELAY_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.warn("Thread interrupted during payment delay: {}", e.getMessage());
}
LOGGER.info("Checking transaction status for txnId={}", billPaymentResponse.getTxnId());
LOGGER.info("[{}] END | reqId={} | txnId={}", apiName, requestId, txnId);
return checkTrasactionStatus(transactionStatusRequest, inboundLog);
} catch (JsonProcessingException e) {
LOGGER.error("JSON Parsing Error in initiatePayment: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest, InboundTraceLog inboundLog) {
String apiName = BBPSConstant.API_CHECK_TRANSACTION_STATUS;
String txnId = helper.generateTxnId(15);
String requestId = transactionStatusRequest.getReqId();
// START log for internal transaction status check
LOGGER.info("[{}] START (internal) | checkTxnId={} | reqId={} | bankTxnId={}", apiName, txnId, requestId, transactionStatusRequest.getTxnId());
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
LOGGER.info("Checking transaction status (internal) for txnId={} and reqId={}", transactionStatusRequest.getTxnId(), requestId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, BBPSConstant.HTTP_GET, null);
LOGGER.debug("Outbound log created for internal status check | txnId={} | reqId={}", txnId, requestId);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction status response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for internal status check | txnId={}", txnId);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for txnId={}", transactionStatusRequest.getTxnId());
throw new CustomException(
String.valueOf(dataMap.get("message")),
String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks"))
);
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap, TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction status received: {}", generalResp.getStatus());
TransactionMaster transactionMaster = modelMapper.map(responseWrapper.getTransactionDAO(), TransactionMaster.class);
transactionMaster.setTxnId(txnId);
transactionMaster.setReqId(transactionStatusRequest.getReqId());
transactionMaster.setMid(transactionStatusRequest.getMid());
transactionMaster.setClientUserId(transactionStatusRequest.getClientUserId());
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
transactionMasterRepository.save(transactionMaster);
LOGGER.info("TransactionMaster saved successfully for txnId={}", txnId);
AgentFundTransfer agentFundTransfer = modelMapper.map(responseWrapper.getAgentFundTransfer(), AgentFundTransfer.class);
agentFundTransfer.setTxnId(txnId);
agentFundTransfer.setReqId(transactionStatusRequest.getReqId());
agentFundTransfer.setTransactionMasterId(transactionMaster.getBankTxnId());
agentFundTransferRepository.save(agentFundTransfer);
LOGGER.info("AgentFundTransfer entry saved successfully for txnId={}", txnId);
ResponseModel responseModel = new ResponseModel(
generalResp.getMessage(),
generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()),
responseWrapper
);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (internal) | checkTxnId={} | reqId={} | status={}", apiName, txnId, requestId, generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing transaction status JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
@Override
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest) {
helper.validateMerchant(transactionStatusRequest.getMid());
String txnID = helper.generateTxnId(15);
String apiName = BBPSConstant.API_CHECK_TRANSACTION_PUBLIC;
String requestId = transactionStatusRequest.getReqId();
LOGGER.info("[{}] START (public) | reqId={} | mid={} | checkBankTxnId={}", apiName, requestId, transactionStatusRequest.getMid(), transactionStatusRequest.getTxnId());
String requestJson = helper.convertObjectToJson(transactionStatusRequest);
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
LOGGER.info("Checking transaction status (public) for txnId={} and reqId={}", transactionStatusRequest.getTxnId(), requestId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName, transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for public status check | reqId={} | txnId={}", requestId, txnID);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, url, BBPSConstant.HTTP_GET, null);
LOGGER.debug("Outbound log created for public status check | reqId={} | txnId={}", requestId, txnID);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction status response data: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for public status check | reqId={} | txnId={}", requestId, txnID);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData, new TypeReference<Map<String, Object>>() {});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
LOGGER.warn("Invalid transaction status response for txnId={} from BBPS", transactionStatusRequest.getTxnId());
throw new CustomException(
String.valueOf(dataMap.get("message")),
String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks"))
);
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap, TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
String status = generalResp.getStatus();
LOGGER.info("Current transaction status: {}", status);
ResponseModel responseModel = new ResponseModel(
generalResp.getMessage(),
generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()),
responseWrapper
);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (public) | reqId={} | txnId={} | status={}", apiName, requestId, txnID, generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing responseData JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
@Override
public ResponseModel checkTrasactionStatusByClientReqId(TrasactionStatusByClientReqIdRequest transactionStatusRequest) {
helper.validateMerchant(transactionStatusRequest.getMid());
String txnID = helper.generateTxnId(15);
String apiName = BBPSConstant.API_CHECK_BY_CLIENT_REQ_ID;
String requestId = transactionStatusRequest.getReqId();
String clientReqId = transactionStatusRequest.getClientReqId();
String requestJson = helper.convertObjectToJson(transactionStatusRequest);
LOGGER.info("[{}] START | reqId={} | mid={} | clientReqId={}", apiName, requestId, transactionStatusRequest.getMid(), clientReqId);
Optional<PaymentInitiate> paymentInitiate = paymentIntiateRepository.findByReqId(clientReqId);
if (paymentInitiate.isEmpty()) {
throw new CustomException(BBPSConstant.NO_BILL_FOUND);
}
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_BY_CLIENT_REQ_ID_URL + paymentInitiate.get().getTxnId();
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
InboundTraceLog inboundLog = helper.createInboundLog(
requestId, txnID, apiName, transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
OutboundTraceLog outboundLog = helper.createOutboundLog(
txnID, requestId, apiName, url, BBPSConstant.HTTP_GET, null);
LOGGER.debug("Outbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
try {
LOGGER.info("Calling BBPS Transaction Status API URL={}", url);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction Status Response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for clientReqId check | reqId={} | txnId={}", requestId, txnID);
Map<String, Object> dataMap = objectMapper.readValue(
responseData, new TypeReference<Map<String, Object>>() {});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for clientReqId={} | Response={}",
clientReqId, responseData);
throw new CustomException(
String.valueOf(dataMap.get("message")),
String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks"))
);
}
TransactionStatusResponse responseWrapper =
objectMapper.convertValue(dataMap, TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction Status for clientReqId={} => {}", clientReqId, generalResp.getStatus());
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END | reqId={} | clientReqId={} | status={}", apiName, requestId, clientReqId, generalResp.getStatus());
return new ResponseModel(
generalResp.getMessage(),
generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()),
responseWrapper
);
@Value("${payment.data.url}")
private String paymentUrl;
private final BharatConnectMasterRepository beneficiaryDetailsRepository;
private final HttpService httpService;
private final Helper helper;
private final PaymentRepository paymentRepository;
private final InboundTraceLogRepository inboundTraceLogRepository;
private final OutboundTraceLogRepository outboundTraceLogRepository;
private final PaymentIntiateRepository paymentIntiateRepository;
private final TransactionMasterRepository transactionMasterRepository;
private final AgentFundTransferRepository agentFundTransferRepository;
private final BillerMapperHelper mapperHelper;
// Shared reusable instances
private final ObjectMapper objectMapper;
private final ModelMapper modelMapper;
private static final Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);
public PaymentServiceImpl(BharatConnectMasterRepository beneficiaryDetailsRepository, HttpService httpService,
Helper helper, PaymentRepository paymentRepository, InboundTraceLogRepository inboundTraceLogRepository,
OutboundTraceLogRepository outboundTraceLogRepository, PaymentIntiateRepository paymentIntiateRepository,
TransactionMasterRepository transactionMasterRepository,
AgentFundTransferRepository agentFundTransferRepository, BillerMapperHelper mapperHelper) {
this.beneficiaryDetailsRepository = beneficiaryDetailsRepository;
this.httpService = httpService;
this.helper = helper;
this.paymentRepository = paymentRepository;
this.inboundTraceLogRepository = inboundTraceLogRepository;
this.outboundTraceLogRepository = outboundTraceLogRepository;
this.paymentIntiateRepository = paymentIntiateRepository;
this.transactionMasterRepository = transactionMasterRepository;
this.agentFundTransferRepository = agentFundTransferRepository;
this.mapperHelper = mapperHelper;
this.objectMapper = new ObjectMapper();
this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.modelMapper = new ModelMapper();
this.modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
}
@Override
public ResponseModel initiatePayment(BillPaymentRequest billPaymentRequest) {
String apiName = BBPSConstant.API_INITIATE_PAYMENT;
String txnId = helper.generateTxnId(15);
String requestId = billPaymentRequest.getReqId();
String userId = billPaymentRequest.getClientReqId();
String url = paymentUrl + BBPSConstant.PAYMENT_URL;
billPaymentRequest.setClientReqId(txnId);
LOGGER.info("Initiating payment for reqId={} and txnId={} and userId={}", requestId, txnId, userId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
BillPaymentForwardRequest forwardReq = mapperHelper.billPaymentForwardRequest(billPaymentRequest);
String forwardjson = helper.convertObjectToJson(forwardReq);
String requestJson = helper.convertObjectToJson(billPaymentRequest);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnId, apiName, billPaymentRequest.getMid(),
BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, BBPSConstant.HTTP_POST,
forwardjson);
LOGGER.debug("Outbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
try {
LOGGER.info("Calling BBPS payment URL: {}", url);
Map<String, String> responseMap = httpService.postRequest(url, forwardjson, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Payment API Response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for txnId={}", txnId);
if (responseData == null || responseData.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.EMPTY_RESPONSE_FROM_BBPS,
BBPSConstant.FAILED_STR);
LOGGER.warn("Empty response received from BBPS for txnId={}", txnId);
throw new CustomException(BBPSConstant.EMPTY_RESPONSE_FROM_BBPS);
}
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERIC_KEY)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_STRUCTURE);
LOGGER.warn("Invalid response structure received for txnId={}", txnId);
throw new CustomException(BBPSConstant.INVALID_STRUCTURE);
}
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
BillPayment entity = modelMapper.map(billPaymentResponse, BillPayment.class);
paymentRepository.save(entity);
LOGGER.info("BillPayment entity saved successfully for txnId={}", txnId);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
PaymentInitiate paymentInitiate = new PaymentInitiate();
paymentInitiate.setTxnId(txnId);
paymentInitiate.setUserId(userId);
paymentInitiate.setReqId(requestId);
paymentInitiate.setMid(billPaymentRequest.getMid());
paymentInitiate.setClientUserId(billPaymentRequest.getClientUserId());
paymentInitiate.setBankTxnId(billPaymentResponse.getTxnId());
paymentInitiate.setStatus(billPaymentResponse.getStatus());
paymentIntiateRepository.save(paymentInitiate);
LOGGER.info("PaymentInitiate entry saved successfully for txnId={}", txnId);
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
transactionStatusRequest.setTxnId(billPaymentResponse.getTxnId());
transactionStatusRequest.setReqId(requestId);
transactionStatusRequest.setMid(billPaymentRequest.getMid());
transactionStatusRequest.setClientUserId(billPaymentRequest.getClientUserId());
try {
Thread.sleep((long) BBPSConstant.PAYMENT_STATUS_DELAY_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
LOGGER.warn("Thread interrupted during payment delay: {}", e.getMessage());
}
LOGGER.info("Checking transaction status for txnId={}", billPaymentResponse.getTxnId());
LOGGER.info("[{}] END | reqId={} | txnId={}", apiName, requestId, txnId);
return checkTrasactionStatus(transactionStatusRequest, inboundLog);
} catch (JsonProcessingException e) {
LOGGER.error("JSON Parsing Error in initiatePayment: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest,
InboundTraceLog inboundLog) {
String apiName = BBPSConstant.API_CHECK_TRANSACTION_STATUS;
String txnId = helper.generateTxnId(15);
String requestId = transactionStatusRequest.getReqId();
// START log for internal transaction status check
LOGGER.info("[{}] START (internal) | checkTxnId={} | reqId={} | bankTxnId={}", apiName, txnId, requestId,
transactionStatusRequest.getTxnId());
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
LOGGER.info("Checking transaction status (internal) for txnId={} and reqId={}",
transactionStatusRequest.getTxnId(), requestId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnId, requestId, apiName, url, BBPSConstant.HTTP_GET,
null);
LOGGER.debug("Outbound log created for internal status check | txnId={} | reqId={}", txnId, requestId);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction status response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for internal status check | txnId={}", txnId);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for txnId={}", transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction status received: {}", generalResp.getStatus());
TransactionMaster transactionMaster = modelMapper.map(responseWrapper.getTransactionDAO(),
TransactionMaster.class);
transactionMaster.setTxnId(txnId);
transactionMaster.setReqId(transactionStatusRequest.getReqId());
transactionMaster.setMid(transactionStatusRequest.getMid());
transactionMaster.setClientUserId(transactionStatusRequest.getClientUserId());
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
transactionMasterRepository.save(transactionMaster);
LOGGER.info("TransactionMaster saved successfully for txnId={}", txnId);
AgentFundTransfer agentFundTransfer = modelMapper.map(responseWrapper.getAgentFundTransfer(),
AgentFundTransfer.class);
agentFundTransfer.setTxnId(txnId);
agentFundTransfer.setReqId(transactionStatusRequest.getReqId());
agentFundTransfer.setTransactionMasterId(transactionMaster.getBankTxnId());
agentFundTransferRepository.save(agentFundTransfer);
LOGGER.info("AgentFundTransfer entry saved successfully for txnId={}", txnId);
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (internal) | checkTxnId={} | reqId={} | status={}", apiName, txnId, requestId,
generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing transaction status JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
@Override
public ResponseModel checkTrasactionStatus(TransactionStatusRequest transactionStatusRequest) {
helper.validateMerchant(transactionStatusRequest.getMid());
String txnID = helper.generateTxnId(15);
String apiName = BBPSConstant.API_CHECK_TRANSACTION_PUBLIC;
String requestId = transactionStatusRequest.getReqId();
LOGGER.info("[{}] START (public) | reqId={} | mid={} | checkBankTxnId={}", apiName, requestId,
transactionStatusRequest.getMid(), transactionStatusRequest.getTxnId());
String requestJson = helper.convertObjectToJson(transactionStatusRequest);
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_URL + transactionStatusRequest.getTxnId();
LOGGER.info("Checking transaction status (public) for txnId={} and reqId={}",
transactionStatusRequest.getTxnId(), requestId);
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName,
transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for public status check | reqId={} | txnId={}", requestId, txnID);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, url, BBPSConstant.HTTP_GET,
null);
LOGGER.debug("Outbound log created for public status check | reqId={} | txnId={}", requestId, txnID);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction status response data: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for public status check | reqId={} | txnId={}", requestId, txnID);
try {
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData,
String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
LOGGER.warn("Invalid transaction status response for txnId={} from BBPS",
transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
String status = generalResp.getStatus();
LOGGER.info("Current transaction status: {}", status);
ResponseModel responseModel = new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END (public) | reqId={} | txnId={} | status={}", apiName, requestId, txnID,
generalResp.getStatus());
return responseModel;
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing responseData JSON: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
@Override
public ResponseModel checkTrasactionStatusByClientReqId(
TrasactionStatusByClientReqIdRequest transactionStatusRequest) {
helper.validateMerchant(transactionStatusRequest.getMid());
String txnID = helper.generateTxnId(15);
String apiName = BBPSConstant.API_CHECK_BY_CLIENT_REQ_ID;
String requestId = transactionStatusRequest.getReqId();
String clientReqId = transactionStatusRequest.getClientReqId();
String requestJson = helper.convertObjectToJson(transactionStatusRequest);
LOGGER.info("[{}] START | reqId={} | mid={} | clientReqId={}", apiName, requestId,
transactionStatusRequest.getMid(), clientReqId);
Optional<PaymentInitiate> paymentInitiate = paymentIntiateRepository.findByReqId(clientReqId);
if (paymentInitiate.isEmpty()) {
throw new CustomException(BBPSConstant.NO_BILL_FOUND);
}
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_BY_CLIENT_REQ_ID_URL
+ paymentInitiate.get().getTxnId();
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
InboundTraceLog inboundLog = helper.createInboundLog(requestId, txnID, apiName,
transactionStatusRequest.getMid(), BBPSConstant.HTTP_POST, requestJson);
LOGGER.debug("Inbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
OutboundTraceLog outboundLog = helper.createOutboundLog(txnID, requestId, apiName, url, BBPSConstant.HTTP_GET,
null);
LOGGER.debug("Outbound log created for clientReqId check | reqId={} | txnId={}", requestId, txnID);
try {
LOGGER.info("Calling BBPS Transaction Status API URL={}", url);
Map<String, String> responseMap = httpService.getRequest(url, headers);
String responseData = responseMap.get(BBPSConstant.RESPONSE_DATA_KEY);
LOGGER.info("Transaction Status Response: {}", responseData);
helper.updateOutboundLogResponse(outboundLog, responseData);
LOGGER.debug("Outbound log response updated for clientReqId check | reqId={} | txnId={}", requestId, txnID);
Map<String, Object> dataMap = objectMapper.readValue(responseData,
new TypeReference<Map<String, Object>>() {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_RESPONSE);
LOGGER.warn("Invalid transaction status response for clientReqId={} | Response={}", clientReqId,
responseData);
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
Integer.parseInt(String.valueOf(dataMap.get("statusCode"))),
String.valueOf(dataMap.get("remarks")));
}
TransactionStatusResponse responseWrapper = objectMapper.convertValue(dataMap,
TransactionStatusResponse.class);
GeneralResp generalResp = responseWrapper.getGeneralResp();
LOGGER.info("Transaction Status for clientReqId={} => {}", clientReqId, generalResp.getStatus());
helper.updateInboundLogSuccess(inboundLog, responseData, generalResp.getStatus());
LOGGER.info("[{}] END | reqId={} | clientReqId={} | status={}", apiName, requestId, clientReqId,
generalResp.getStatus());
return new ResponseModel(generalResp.getMessage(), generalResp.getStatus(),
Integer.parseInt(generalResp.getStatusCode()), responseWrapper);
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing JSON in transaction status API: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
} catch (JsonProcessingException e) {
LOGGER.error("Error parsing JSON in transaction status API: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
throw new CustomException("Invalid JSON received from API");
}
}
throw new CustomException("Invalid JSON received from API");
}
}
}
@@ -286,11 +286,36 @@ public class PaymentStartServiceImpl implements PaymentStartService {
// Save record with HTML (persist original request and HTML response)
String responseTypeWeb = BBPSConstant.RESPONSE_TYPE_HTML;
String rawResponseWeb = respBody == null ? "" : respBody;
// bbpsMapperHelper.savePaymentStartRecord(request, null, txnId, orderNo, requestJson, rawResponseWeb, responseTypeWeb);
LOGGER.info("[startWebPayment] saved payment start record txnId={} orderNo={} responseType={}", txnId, orderNo, responseTypeWeb);
// Try to extract useful fields from returned HTML (txnId, amount, mid)
Map<String, String> parsed = parseHtmlResponse(rawResponseWeb);
// Build a minimal PaymentStartApiResponse so savePaymentStartRecord() can safely read fields
com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse apiResp = new com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse();
com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse.ResponseData rd = new com.billpaymentservice.bbps.dto.response.PaymentStartApiResponse.ResponseData();
String parsedTxn = parsed.getOrDefault("txnId", "");
String parsedAmount = parsed.getOrDefault("amount", "0.00");
String parsedMid = parsed.getOrDefault("mid", paymentMid == null ? "DUMMY_MID" : paymentMid);
// prefer HTML-provided txnId if present, otherwise reuse generated txnId
rd.setTxnId(parsedTxn != null && !parsedTxn.isEmpty() ? parsedTxn : txnId);
rd.setAmount(parsedAmount != null && !parsedAmount.isEmpty() ? parsedAmount : "0.00");
rd.setMid(parsedMid);
rd.setOrderNo(orderNo);
rd.setQrString("NO_QR");
rd.setCreatedOn(LocalDateTime.now().toString());
apiResp.setResponseData(rd);
apiResp.setMessage("HTML_RESPONSE");
apiResp.setStatusCode(String.valueOf(BBPSConstant.HTTP_OK_INT));
bbpsMapperHelper.savePaymentStartRecord(request, apiResp, txnId, orderNo, requestJson, rawResponseWeb, responseTypeWeb);
LOGGER.info("[startWebPayment] saved payment start record txnId={} orderNo={} responseType={}", txnId, orderNo, responseTypeWeb);
// Return HTML directly in API response
Map<String, String> result = new HashMap<>();
result.put("OrderId", orderNo);
result.put("html", respBody);
LOGGER.info("[startWebPayment] complete txnId={} orderNo={} returning HTML", txnId, orderNo);
@@ -437,4 +462,4 @@ public class PaymentStartServiceImpl implements PaymentStartService {
}
}
@@ -4,7 +4,9 @@ import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.billpaymentservice.bbps.dto.ResponseModel;
import com.billpaymentservice.bbps.dto.TransactionHistoryMasterDTO;
import com.billpaymentservice.bbps.dto.TransactionHistoryParticularDetailsDTO;
@@ -57,22 +59,34 @@ public class TxnHistoryServiceImpl implements TxnHistoryService {
BBPSConstant.HTTP_GET, null);
try {
List<TransactionMaster> dataResult = transactionMasterRepository.findByMidOrClientUserId(mid, clientUserId);
Page<TransactionMaster> dataResult;
if (clientUserId.isEmpty() || clientUserId == null) {
Pageable pageable = PageRequest.of(paymentHistoryRequest.getPageNo(),
paymentHistoryRequest.getPageSize());
dataResult = transactionMasterRepository.findByMid(mid, pageable);
} else {
Pageable pageable = PageRequest.of(paymentHistoryRequest.getPageNo(),
paymentHistoryRequest.getPageSize());
dataResult = transactionMasterRepository.findByMidOrClientUserId(mid, clientUserId, pageable);
}
// List<TransactionMaster> dataResult =
// transactionMasterRepository.findByMidOrClientUserId(mid, clientUserId);
if (dataResult == null || dataResult.isEmpty()) {
log.info("[{}] Response Fetch From DB | reqId={} | data={}", apiName, requestId, dataResult);
throw new CustomException("No Transcation Found This Mid", "FAILED", BBPSConstant.BADREQUEST, null);
}
Integer responseData = dataResult.size();
log.info("[{}] Response Fetch From DB | reqId={} | data={}", apiName, requestId, responseData);
log.info("[{}] Response Fetch From DB | reqId={} | data={}", apiName, requestId,
dataResult.getTotalElements());
List<TransactionHistoryParticularDetailsDTO> responseDatas = dataResult.stream()
.map(mapperHelper::billerRemainingDetails).collect(Collectors.toList());
helper.updateOutboundLogResponse(outboundLog, String.valueOf(responseData));
helper.updateOutboundLogResponse(outboundLog, String.valueOf(dataResult.getTotalElements()));
return new ResponseModel(BBPSConstant.ALL_MASTER_FIELDS_FETCH, BBPSConstant.SUCCESS_RESPONSE,
return new ResponseModel(BBPSConstant.ALL_HISTORY_FIELDS_FETCH, BBPSConstant.SUCCESS_RESPONSE,
BBPSConstant.HTTP_OK_INT, responseDatas, responseDatas.size());
} catch (CustomException e) {
@@ -123,7 +137,7 @@ public class TxnHistoryServiceImpl implements TxnHistoryService {
helper.updateOutboundLogResponse(outboundLog, String.valueOf(responseData));
return new ResponseModel(BBPSConstant.ALL_MASTER_FIELDS_FETCH, BBPSConstant.SUCCESS_RESPONSE,
BBPSConstant.HTTP_OK_INT, transactionDTO,null,responseData);
BBPSConstant.HTTP_OK_INT, transactionDTO, null, responseData);
} catch (CustomException e) {
// Log and rethrow the custom exception
@@ -141,7 +141,8 @@ public class BBPSConstant {
public static final String RESPONSE_GENERAL_RESP = "generalResp";
public static final String SUCCESS_RESPONSE = "SUCCESS";
// Newly added constants for Payment integration (avoid magic strings in service code)
// Newly added constants for Payment integration (avoid magic strings in service
// code)
public static final String UAT_PAYMENT_URL_WEB = "https://uat.godemo.in/api/UATIntegration/uat/payin/paymentrequest";
public static final String UAT_PAYMENT_URL_INTENT = "https://uat.godemo.in/api/UATIntegration/paymentrequest/seamless";
public static final String RESP_CODE_KEY = "respCode"; // key used by HttpService responses
@@ -182,9 +183,11 @@ public class BBPSConstant {
public static final String NULL_DATA_FROM_DB = "NULL_DATA_FROM_DB";
public static final String NO_MASTER_FIELDS_FOUND = "No master fields found";
public static final String ALL_MASTER_FIELDS_FETCH = "All master fields fetched successfully";
public static final String ALL_HISTORY_FIELDS_FETCH = "All history fields fetched successfully";
public static final String ALL_COMPLAINT_FIELDS_FETCH = "All complaint fields fetched successfully";
public static final String SOMETHING_WENT_WRONG = "Something went wrong";
public static final String USER_ID_IS_EMPTY = "User id is empty";
public static final String USER_Txn_IS_NOT_FOUND = "Not Txn Found This Txn Id";
// Common user-facing and internal message constants used by payment flow
public static final String MSG_UPSTREAM_HTTP_ERROR = "Upstream HTTP error";
@@ -205,4 +208,9 @@ public class BBPSConstant {
public static final long BILL_VALIDATE_DELAY_MS = 12000L; // used after initiate bill validate
public static final long PAYMENT_STATUS_DELAY_MS = 9000L; // used after initiate payment
public static final String enckey = "g5c4lr0tgjjqhu0bfgmhjf26ab0z8ktk";
public static final String mid = "MIDBBPS001THA";
public static final String callbackurl = "https://11.godemo.in/BBPS/payment/callback/startPayment";
public static final String companyName = "testing.com";
}
@@ -1,5 +1,6 @@
package com.billpaymentservice.bbps.util;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
@@ -192,7 +193,7 @@ public class BillerMapperHelper {
* returns the saved list
*/
public List<BillerCategoryWise> mapAndSaveAll(List<MasterCategoryBillerResponse> dtos, String requestId,
String txnId) {
String txnId, String userId) {
if (dtos == null || dtos.isEmpty()) {
return Collections.emptyList();
}
@@ -216,6 +217,7 @@ public class BillerMapperHelper {
biller.setCreateDateTime(new Date());
biller.setRequestId(requestId);
biller.setTxnId(txnId);
biller.setUserId(userId);
// Handle icon
BillerIconDTO iconDTO = dto.getBiller_icon();
@@ -239,7 +241,8 @@ public class BillerMapperHelper {
return billerRepo.saveAll(entities);
}
public CustomerParamGroupsDTO saveCustomerParamGroups(CustomerParamGroupsDTO dtos, String requestId, String txnId) {
public CustomerParamGroupsDTO saveCustomerParamGroups(CustomerParamGroupsDTO dtos, String requestId, String txnId,
String userId) {
if (dtos == null || dtos.getGroups() == null || dtos.getGroups().isEmpty()) {
return new CustomerParamGroupsDTO(); // Return empty DTO if no groups exist
}
@@ -248,8 +251,10 @@ public class BillerMapperHelper {
// Loop through the top-level groups and save them (including nested groups)
for (GroupDTO groupDTO : dtos.getGroups()) {
CustomerParamGroupById entity = saveGroupWithChildren(groupDTO, null, requestId, txnId); // null is for root
// (no
CustomerParamGroupById entity = saveGroupWithChildren(groupDTO, null, requestId, txnId, userId); // null is
// for
// root
// (no
// parent group)
entities.add(entity); // Add the saved entity to the list
@@ -263,7 +268,7 @@ public class BillerMapperHelper {
}
private CustomerParamGroupById saveGroupWithChildren(GroupDTO groupDTO, CustomerParamGroupById parentGroup,
String requestId, String txnId) {
String requestId, String txnId, String userId) {
// Create a new entity for the group
CustomerParamGroupById groupEntity = new CustomerParamGroupById();
@@ -273,6 +278,7 @@ public class BillerMapperHelper {
groupEntity.setParentGroup(parentGroup); // Link to the parent group (if exists)
groupEntity.setRequestId(requestId);
groupEntity.setTxnId(txnId);
groupEntity.setUserId(userId);
groupEntity.setCreateDateTime(new Date());
// Save group parameters (if any)
if (groupDTO.getParams() != null && !groupDTO.getParams().isEmpty()) {
@@ -290,8 +296,8 @@ public class BillerMapperHelper {
if (groupDTO.getGroups() != null && !groupDTO.getGroups().isEmpty()) {
List<CustomerParamGroupById> childEntities = new ArrayList<>();
for (GroupDTO childGroupDTO : groupDTO.getGroups()) {
CustomerParamGroupById childEntity = saveGroupWithChildren(childGroupDTO, groupEntity, requestId,
txnId); // Pass
CustomerParamGroupById childEntity = saveGroupWithChildren(childGroupDTO, groupEntity, requestId, txnId,
userId); // Pass
// current
// group
// as
@@ -346,7 +352,8 @@ public class BillerMapperHelper {
}
// Method to save AmountOptionsResponse and AmountOption entities
public String saveAmountOptionsResponse(AmountOptionsResponse responseWrapper, String requestId, String txnId) {
public String saveAmountOptionsResponse(AmountOptionsResponse responseWrapper, String requestId, String txnId,
String userId) {
// Convert AmountOptionsResponseDTO to AmountOptionsResponse entity
if (responseWrapper == null) {
@@ -358,14 +365,10 @@ public class BillerMapperHelper {
// Map AmountOptionDTO list to AmountOptionDetails entities
List<AmountOptionDetails> amountOptionDetailsList = mapAmountOptionDTOToEntity(
responseWrapper.getAmountOptionDAOS(), requestId, txnId);
// Set the mapped AmountOptionDetails list to AmountOptionByBillerId entity
responseWrapper.getAmountOptionDAOS(), requestId, txnId, userId);
entity.setAmountOptionDetails(amountOptionDetailsList);
entity.setCreateDateTime(new Date());
// Save AmountOptionByBillerId entity (this will also save related
// AmountOptionDetails entities)
amountOptionByBillerIdRepository.save(entity); // Saves the entity and cascades to AmountOptionDetails
// Return success message
@@ -373,7 +376,7 @@ public class BillerMapperHelper {
}
private List<AmountOptionDetails> mapAmountOptionDTOToEntity(List<AmountOptionDTO> amountOptionDTOs,
String requestId, String txnId) {
String requestId, String txnId, String userId) {
// If the list is null or empty, return an empty list of entities
if (amountOptionDTOs == null || amountOptionDTOs.isEmpty()) {
@@ -397,13 +400,14 @@ public class BillerMapperHelper {
amountOptionDetails.setAmountOptionId(dto.getAmountOptionId());
amountOptionDetails.setRequestId(requestId);
amountOptionDetails.setTxnId(txnId);
amountOptionDetails.setUserId(userId);
// Return the mapped AmountOptionDetails entity
return amountOptionDetails;
})).collect(Collectors.toList()); // Collect them into a list and return
}
public PlanResponses savePlanResponse(PlanResponse planResponse, String reqId, String txnId) {
public PlanResponses savePlanResponse(PlanResponse planResponse, String reqId, String txnId, String userId) {
PlanResponses response = new PlanResponses();
response.setRequestId(reqId);
response.setPageNo(planResponse.getPageNo());
@@ -411,6 +415,7 @@ public class BillerMapperHelper {
response.setTotalElements(planResponse.getTotalElements());
response.setTotalPages(planResponse.getTotalPages());
response.setTxnId(txnId);
response.setUserId(userId);
response.setCreateDateTime(new Date());
PlansList plansList = new PlansList();
@@ -472,7 +477,7 @@ public class BillerMapperHelper {
return planResponseRepository.save(response);
}
public String saveCategoryItems(List<String> categoryRespList, String requestId, String txnId) {
public String saveCategoryItems(List<String> categoryRespList, String requestId, String txnId, String userId) {
int savedCount = 0; // To track how many items were saved
if (categoryRespList == null || categoryRespList.isEmpty()) {
@@ -485,13 +490,14 @@ public class BillerMapperHelper {
category.setRequestId(txnId);
category.setRequestId(requestId);
category.setCreateDateTime(new Date());
category.setUserId(userId);
categoryResponseListRepository.save(category);
savedCount++;
}
return savedCount + " items were successfully saved.";
}
public String saveComplaintStatus(TicketCheckStatusResponse response, String reqId, String txnId) {
public String saveComplaintStatus(TicketCheckStatusResponse response, String reqId, String txnId, String userId) {
if (response == null || response.getTicketDetails() == null) {
throw new CustomException("Invalid response received!", "FAILURE", 500, "Response Null");
@@ -531,6 +537,7 @@ public class BillerMapperHelper {
entity.setNpciTicketStatus(dto.getNpciTicketStatus());
entity.setCreatedTime(dto.getCreatedTime());
entity.setCreateDateTime(new Date());
entity.setUserId(userId);
try {
ComplainStatus saved = complaintStatusRepository.save(entity);
@@ -541,7 +548,8 @@ public class BillerMapperHelper {
}
}
public String saveComplaintHistory(ComplaintHistoryStatusResponse responseWrapper, String reqId, String txnId) {
public String saveComplaintHistory(ComplaintHistoryStatusResponse responseWrapper, String reqId, String txnId,
String userId) {
if (responseWrapper == null || responseWrapper.getTicketHistories() == null
|| responseWrapper.getTicketHistories().isEmpty()) {
return "No complaint history data found to save.";
@@ -560,6 +568,7 @@ public class BillerMapperHelper {
entity.setReqId(reqId);
entity.setTxnId(txnId);
entity.setCreateDateTime(new Date());
entity.setUserId(userId);
complaintHistoryRepository.save(entity);
savedCount++;
@@ -656,7 +665,8 @@ public class BillerMapperHelper {
return finalJson;
}
public String saveComplainStatusDetail(ViewComplainByIdResponse responseWrapper, String reqId, String txnId) {
public String saveComplainStatusDetail(ViewComplainByIdResponse responseWrapper, String reqId, String txnId,
String userId) {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
@@ -674,6 +684,7 @@ public class BillerMapperHelper {
entity.setPage(String.valueOf(responseWrapper.getPage()));
entity.setPageSize(String.valueOf(responseWrapper.getPageSize()));
entity.setCreateDateTime(new Date());
entity.setUserId(userId);
}
@@ -794,7 +805,7 @@ public class BillerMapperHelper {
}
public String saveTicketDisoptionDetails(List<TicketDispositionsDTO> dispositionsList, String requestId,
String txnId) {
String txnId, String userId) {
if (dispositionsList == null || dispositionsList.isEmpty()) {
return "No disposition data received.";
@@ -820,7 +831,7 @@ public class BillerMapperHelper {
entity.setCreateDateTime(new Date());
entity.setTxnId(txnId);
entity.setReqId(requestId);
entity.setUserId(userId);
ticketDispositionRepository.save(entity);
savedCount++;
}
@@ -833,7 +844,8 @@ public class BillerMapperHelper {
}
}
public String saveAllComplaints(ViewAllComplaintsTicketsResponse responseWrapper, String reqId, String txnId) {
public String saveAllComplaints(ViewAllComplaintsTicketsResponse responseWrapper, String reqId, String txnId,
String userId) {
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
@@ -851,6 +863,7 @@ public class BillerMapperHelper {
entity.setTotalPages(String.valueOf(responseWrapper.getTotalPages()));
entity.setTotalElements(String.valueOf(responseWrapper.getTotalElements()));
entity.setCreateDateTime(new Date());
entity.setUserId(userId);
}
@@ -860,7 +873,8 @@ public class BillerMapperHelper {
return "SUCCESS";
}
public String saveContactMasterData(List<ContactMaster> contactMasterList, String requestId, String txnID) {
public String saveContactMasterData(List<ContactMaster> contactMasterList, String requestId, String txnID,
String userId) {
if (contactMasterList == null || contactMasterList.isEmpty()) {
return "No contact master data found";
@@ -872,6 +886,7 @@ public class BillerMapperHelper {
entity.setMobNo(dto.getMobNo());
entity.setReqId(requestId);
entity.setTxnId(txnID);
entity.setUserId(userId);
entity.setCreateDateTime(new Date());
return entity;
}).collect(Collectors.toList());
@@ -895,7 +910,7 @@ public class BillerMapperHelper {
}
public void saveOrUpdateBillData(BillDataResponse responseWrapper,
BillFetchByBillIdRequest billFetchByBillIdRequest, String txnId) {
BillFetchByBillIdRequest billFetchByBillIdRequest, String txnId, String reqId, String userId) {
BillMaster billMaster = new BillMaster();
@@ -907,6 +922,9 @@ public class BillerMapperHelper {
billMaster.setUserId(responseWrapper.getUserId());
billMaster.setReqId(billFetchByBillIdRequest.getReqId());
billMaster.setTxnId(txnId);
billMaster.setReqId(reqId);
billMaster.setUserId(userId);
billMaster.setClientUserId(billFetchByBillIdRequest.getClientUserId());
// BILLER RESPONSE
BillerResponse billerResponse = new BillerResponse();
@@ -961,7 +979,8 @@ public class BillerMapperHelper {
billMasterRepository.save(billMaster);
}
public void saveBillValidation(FetchBillValidateResponse responseWrapper, BillFetchByBillIdRequest billRequest) {
public void saveBillValidation(FetchBillValidateResponse responseWrapper, BillFetchByBillIdRequest billRequest,
String txnId) {
System.out.println("responseWrapper");
ModelMapper modelMapper = new ModelMapper();
@@ -988,6 +1007,9 @@ public class BillerMapperHelper {
return ai;
}).collect(Collectors.toList());
billEntity.setAdditionalInfo(additionalInfos);
billEntity.setClientUserId(billRequest.getClientUserId());
billEntity.setTxnId(txnId);
billEntity.setRefId(billRequest.getReqId());
}
// ✅ Save everything (cascade handles child)
@@ -1040,7 +1062,7 @@ public class BillerMapperHelper {
BillPaymentForwardRequest forward = new BillPaymentForwardRequest();
forward.setTenantId(req.getTenantId());
// forward.setTenantId(req.getTenantId());
forward.setRefId(req.getRefId());
forward.setBillId(req.getBillId());
forward.setAmountOptions(req.isAmountOptions());
@@ -1088,14 +1110,15 @@ public class BillerMapperHelper {
record.setClientMid(request.getMid());
record.setClientUserId(request.getClientUserId());
record.setInternalTxnId(txnId);
if (apiResponse != null && apiResponse.getResponseData() != null) {
record.setAmount(apiResponse.getResponseData().getAmount());
record.setMid(apiResponse.getResponseData().getMid());
record.setTxnId(apiResponse.getResponseData().getTxnId());
record.setQrString(apiResponse.getResponseData().getQrString());
record.setCreatedOn(apiResponse.getResponseData().getCreatedOn());
record.setTxnStatus("PENDING");
}
record.setAmount(Optional.ofNullable(apiResponse.getResponseData().getAmount()).orElse("0.00"));
record.setMid(Optional.ofNullable(apiResponse.getResponseData().getMid()).orElse("DUMMY_MID"));
record.setTxnId(Optional.ofNullable(apiResponse.getResponseData().getTxnId()).orElse("DUMMY_TXN"));
record.setQrString(Optional.ofNullable(apiResponse.getResponseData().getQrString()).orElse("NO_QR"));
record.setCreatedOn(Optional.ofNullable(apiResponse.getResponseData().getCreatedOn()).orElse(LocalDateTime.now().toString()));
record.setTxnStatus("PENDING");
// store the original request body and raw response
record.setRequestBody(requestJson);
@@ -1199,7 +1222,8 @@ public class BillerMapperHelper {
}
}
public String saveComplaintResponseEntity(ComplaintResponse responseWrapper, String requestId, String txnId,String userId) {
public String saveComplaintResponseEntity(ComplaintResponse responseWrapper, String requestId, String txnId,
String userId) {
// 1. Convert ComplaintResponse DTO to ComplaintResponseEntity
ComplaintResponseEntity complaintResponseEntity = new ComplaintResponseEntity();
@@ -3,7 +3,7 @@ package com.billpaymentservice.bbps.util;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -210,15 +210,20 @@ public class Helper {
}
private String generateUniqueUserId() {
String userId = UUID.randomUUID().toString(); // Generate UUID
Random random = new Random();
// Generate a random 6-digit number (between 100000 and 999999)
String userId = String.format("USER%06d", random.nextInt(900000) + 100000); // Format as USER-XXXXXX
// Check if the userId already exists in the database (theoretically rare but
// can happen)
while (userRepository.existsByUserId(userId)) {
// If it exists, generate a new one
userId = UUID.randomUUID().toString();
userId = String.format("USER-%06d", random.nextInt(900000) + 100000); // Generate new 6-digit number with
// prefix
}
return userId;
}
}