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