half commited

This commit is contained in:
Lincpay Tech
2025-12-17 15:30:33 +05:30
parent 4b5f81d0d5
commit c8bc6e7f12
12 changed files with 409 additions and 132 deletions
@@ -1,5 +1,6 @@
package com.billpaymentservice.bbps.serviceImpl;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -23,14 +24,12 @@ import com.billpaymentservice.bbps.entites.BharatConnectMaster;
import com.billpaymentservice.bbps.entites.BillPayment;
import com.billpaymentservice.bbps.entites.InboundTraceLog;
import com.billpaymentservice.bbps.entites.OutboundTraceLog;
import com.billpaymentservice.bbps.entites.PaymentInitiate;
import com.billpaymentservice.bbps.entites.TransactionMaster;
import com.billpaymentservice.bbps.exception.CustomException;
import com.billpaymentservice.bbps.repository.AgentFundTransferRepository;
import com.billpaymentservice.bbps.repository.BharatConnectMasterRepository;
import com.billpaymentservice.bbps.repository.InboundTraceLogRepository;
import com.billpaymentservice.bbps.repository.OutboundTraceLogRepository;
import com.billpaymentservice.bbps.repository.PaymentIntiateRepository;
import com.billpaymentservice.bbps.repository.PaymentRepository;
import com.billpaymentservice.bbps.repository.TransactionMasterRepository;
import com.billpaymentservice.bbps.service.PaymentService;
@@ -54,7 +53,6 @@ public class PaymentServiceImpl implements PaymentService {
private final PaymentRepository paymentRepository;
private final InboundTraceLogRepository inboundTraceLogRepository;
private final OutboundTraceLogRepository outboundTraceLogRepository;
private final PaymentIntiateRepository paymentIntiateRepository;
private final TransactionMasterRepository transactionMasterRepository;
private final AgentFundTransferRepository agentFundTransferRepository;
private final BillerMapperHelper mapperHelper;
@@ -66,8 +64,7 @@ public class PaymentServiceImpl implements PaymentService {
public PaymentServiceImpl(BharatConnectMasterRepository beneficiaryDetailsRepository, HttpService httpService,
Helper helper, PaymentRepository paymentRepository, InboundTraceLogRepository inboundTraceLogRepository,
OutboundTraceLogRepository outboundTraceLogRepository, PaymentIntiateRepository paymentIntiateRepository,
TransactionMasterRepository transactionMasterRepository,
OutboundTraceLogRepository outboundTraceLogRepository, TransactionMasterRepository transactionMasterRepository,
AgentFundTransferRepository agentFundTransferRepository, BillerMapperHelper mapperHelper) {
this.beneficiaryDetailsRepository = beneficiaryDetailsRepository;
this.httpService = httpService;
@@ -75,7 +72,6 @@ public class PaymentServiceImpl implements PaymentService {
this.paymentRepository = paymentRepository;
this.inboundTraceLogRepository = inboundTraceLogRepository;
this.outboundTraceLogRepository = outboundTraceLogRepository;
this.paymentIntiateRepository = paymentIntiateRepository;
this.transactionMasterRepository = transactionMasterRepository;
this.agentFundTransferRepository = agentFundTransferRepository;
this.mapperHelper = mapperHelper;
@@ -114,6 +110,26 @@ public class PaymentServiceImpl implements PaymentService {
forwardjson);
LOGGER.debug("Outbound log created for api={} | reqId={} | txnId={}", apiName, requestId, txnId);
// Persist a TransactionMaster BEFORE making the external call so we have a DB record
// even if the HTTP call fails later. This is intentionally tolerant: failure to
// save here should not prevent the outgoing request, so we catch and log errors.
try {
TransactionMaster preTransaction = new TransactionMaster();
preTransaction.setBankTxnId("INITIATED_" + txnId);
preTransaction.setTxnId(txnId);
preTransaction.setReqId(requestId);
preTransaction.setMid(billPaymentRequest.getMid());
preTransaction.setClientUserId(billPaymentRequest.getClientUserId());
preTransaction.setClientReqId(billPaymentRequest.getClientReqId());
preTransaction.setUserId(userId);
preTransaction.setStatus("INITIATED");
EntityRelationshipUtil.linkTransactionMasterRelationships(preTransaction);
saveTransactionMasterWithRetry(preTransaction);
LOGGER.info("Pre-request TransactionMaster saved with status=INITIATED for txnId={}", txnId);
} catch (Exception e) {
LOGGER.warn("Failed to persist pre-request TransactionMaster for txnId={}: {}", txnId, e.getMessage());
}
try {
LOGGER.info("Calling BBPS payment URL: {}", url);
Map<String, String> responseMap = httpService.postRequest(url, forwardjson, headers);
@@ -125,14 +141,21 @@ public class PaymentServiceImpl implements PaymentService {
if (responseData == null || responseData.isEmpty()) {
helper.updateInboundLogFailure(inboundLog, BBPSConstant.EMPTY_RESPONSE_FROM_BBPS,
BBPSConstant.FAILED_STR);
BBPSConstant.FAILED_STR);
LOGGER.warn("Empty response received from BBPS for txnId={}", txnId);
throw new CustomException(
BBPSConstant.EMPTY_RESPONSE_FROM_BBPS, // message
BBPSConstant.FAILED_STATUS, // status
502, // statusCode
"BBPS upstream returned empty response"
);
// Persist a TransactionMaster placeholder so scheduler can pick it up later
TransactionMaster tm = new TransactionMaster();
tm.setBankTxnId("PENDING_" + txnId);
tm.setTxnId(txnId);
tm.setReqId(requestId);
tm.setMid(billPaymentRequest.getMid());
tm.setClientUserId(billPaymentRequest.getClientUserId());
tm.setClientReqId(billPaymentRequest.getClientReqId());
tm.setUserId(userId);
tm.setStatus("PENDING_UPSTREAM");
transactionMasterRepository.save(tm);
LOGGER.info("TransactionMaster placeholder saved with status=PENDING_UPSTREAM for txnId={}", txnId);
return new ResponseModel(BBPSConstant.EMPTY_RESPONSE_FROM_BBPS, "PENDING_UPSTREAM", 502, null);
}
Map<String, Object> dataMap = objectMapper.readValue(responseData,
@@ -141,16 +164,42 @@ public class PaymentServiceImpl implements PaymentService {
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERIC_KEY)) {
helper.updateInboundLogFailure(inboundLog, responseData, BBPSConstant.INVALID_STRUCTURE);
LOGGER.warn("Invalid response structure received for txnId={}", txnId);
throw new CustomException(BBPSConstant.INVALID_STRUCTURE);
// Save a TransactionMaster placeholder so scheduler/admin can reconcile later
TransactionMaster tm = new TransactionMaster();
tm.setBankTxnId("INVALID_" + txnId);
tm.setTxnId(txnId);
tm.setReqId(requestId);
tm.setMid(billPaymentRequest.getMid());
tm.setClientUserId(billPaymentRequest.getClientUserId());
tm.setClientReqId(billPaymentRequest.getClientReqId());
tm.setUserId(userId);
tm.setStatus("INVALID_RESPONSE_FROM_BBPS");
transactionMasterRepository.save(tm);
LOGGER.info("TransactionMaster placeholder saved with status=INVALID_RESPONSE_FROM_BBPS for txnId={}", txnId);
return new ResponseModel(BBPSConstant.INVALID_STRUCTURE, "INVALID_RESPONSE_FROM_BBPS", 502, null);
}
BillPaymentResponse billPaymentResponse = objectMapper.convertValue(dataMap, BillPaymentResponse.class);
GeneralResp generalResponse = billPaymentResponse.getGenericResponse();
LOGGER.info("genric Response" + generalResponse);
if(generalResponse.getStatus().equalsIgnoreCase("Failed")) {
throw new CustomException(generalResponse.getMessage(), generalResponse.getStatus(),
Integer.parseInt(generalResponse.getStatusCode()), generalResponse.getRemarks());
}
// Save TransactionMaster with failed status so it can be reconciled later
TransactionMaster tm = new TransactionMaster();
tm.setBankTxnId(billPaymentResponse.getTxnId());
tm.setTxnId(txnId);
tm.setReqId(requestId);
tm.setMid(billPaymentRequest.getMid());
tm.setClientUserId(billPaymentRequest.getClientUserId());
tm.setClientReqId(billPaymentRequest.getClientReqId());
tm.setUserId(userId);
tm.setStatus(generalResponse.getStatus());
// ensure internal txnId uniqueness and save
tm.setTxnId(makeUniqueTxnId(tm.getTxnId()));
saveTransactionMasterWithRetry(tm);
LOGGER.info("TransactionMaster saved with failed status={} for txnId={}", generalResponse.getStatus(), txnId);
return new ResponseModel(generalResponse.getMessage(), generalResponse.getStatus(),
Integer.parseInt(generalResponse.getStatusCode()), billPaymentResponse);
}
BillPayment entity = modelMapper.map(billPaymentResponse, BillPayment.class);
@@ -158,17 +207,29 @@ public class PaymentServiceImpl implements PaymentService {
LOGGER.info("BillPayment entity saved successfully for txnId={}", txnId);
helper.updateInboundLogSuccess(inboundLog, responseData, generalResponse.getStatus());
PaymentInitiate paymentInitiate = new PaymentInitiate();
paymentInitiate.setTxnId(txnId);
paymentInitiate.setUserId(userId);
paymentInitiate.setReqId(requestId);
paymentInitiate.setMid(billPaymentRequest.getMid());
paymentInitiate.setClientUserId(billPaymentRequest.getClientUserId());
paymentInitiate.setBankTxnId(billPaymentResponse.getTxnId());
paymentInitiate.setStatus(billPaymentResponse.getStatus());
paymentIntiateRepository.save(paymentInitiate);
LOGGER.info("PaymentInitiate entry saved successfully for txnId={}", txnId);
// Create and save TransactionMaster for this initiate flow so everything is stored in the same table
try {
TransactionMaster transactionMaster = new TransactionMaster();
// bankTxnId is BBPS txn id (primary key)
transactionMaster.setBankTxnId(billPaymentResponse.getTxnId());
// use internal txnId generated earlier for tracing
transactionMaster.setTxnId(txnId);
transactionMaster.setReqId(requestId);
transactionMaster.setMid(billPaymentRequest.getMid());
transactionMaster.setClientUserId(billPaymentRequest.getClientUserId());
transactionMaster.setClientReqId(billPaymentRequest.getClientReqId());
transactionMaster.setUserId(userId);
transactionMaster.setBillerId(billPaymentResponse.getBillerId());
transactionMaster.setTxnAmount(billPaymentResponse.getTxnAmount());
transactionMaster.setStatus(billPaymentResponse.getStatus());
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
// ensure internal txnId uniqueness and save (handles collisions)
transactionMaster.setTxnId(makeUniqueTxnId(transactionMaster.getTxnId()));
saveTransactionMasterWithRetry(transactionMaster);
LOGGER.info("TransactionMaster created during initiatePayment for internalTxnId={} bankTxnId={}", transactionMaster.getTxnId(), transactionMaster.getBankTxnId());
} catch (Exception e) {
LOGGER.warn("Failed to persist TransactionMaster during initiatePayment for txnId={}: {}", txnId, e.getMessage());
}
TransactionStatusRequest transactionStatusRequest = new TransactionStatusRequest();
transactionStatusRequest.setTxnId(billPaymentResponse.getTxnId());
transactionStatusRequest.setReqId(requestId);
@@ -188,6 +249,18 @@ public class PaymentServiceImpl implements PaymentService {
} catch (JsonProcessingException e) {
LOGGER.error("JSON Parsing Error in initiatePayment: {}", e.getMessage(), e);
helper.updateInboundLogFailure(inboundLog, e.getMessage(), BBPSConstant.JSON_ERROR);
// Persist TransactionMaster placeholder so admin/scheduler can reconcile later
TransactionMaster tm = new TransactionMaster();
tm.setBankTxnId("INVALID_JSON_" + txnId);
tm.setTxnId(txnId);
tm.setUserId(billPaymentRequest.getClientReqId());
tm.setReqId(billPaymentRequest.getReqId());
tm.setMid(billPaymentRequest.getMid());
tm.setClientUserId(billPaymentRequest.getClientUserId());
tm.setClientReqId(billPaymentRequest.getClientReqId());
tm.setStatus("INVALID_JSON_FROM_UPSTREAM");
transactionMasterRepository.save(tm);
LOGGER.info("TransactionMaster saved with status=INVALID_JSON_FROM_UPSTREAM for txnId={}", txnId);
throw new CustomException(BBPSConstant.MSG_INVALID_JSON_FROM_UPSTREAM, BBPSConstant.FAILED_STATUS, BBPSConstant.INVALID_JSON_STATUS_CODE, e.getMessage());
}
}
@@ -244,7 +317,9 @@ public class PaymentServiceImpl implements PaymentService {
transactionMaster.setMid(transactionStatusRequest.getMid());
transactionMaster.setClientUserId(transactionStatusRequest.getClientUserId());
EntityRelationshipUtil.linkTransactionMasterRelationships(transactionMaster);
transactionMasterRepository.save(transactionMaster);
// Ensure internal txnId is unique; if collisions occur append suffix (_1, _2...)
transactionMaster.setTxnId(makeUniqueTxnId(transactionMaster.getTxnId()));
saveTransactionMasterWithRetry(transactionMaster);
LOGGER.info("TransactionMaster saved successfully for txnId={}", txnId);
AgentFundTransfer agentFundTransfer = modelMapper.map(responseWrapper.getAgentFundTransfer(),
@@ -306,7 +381,7 @@ public class PaymentServiceImpl implements PaymentService {
});
if (!dataMap.containsKey(BBPSConstant.RESPONSE_GENERAL_RESP)) {
helper.updateInboundLogFailure(inboundLog, responseData,
String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
String.valueOf(dataMap.get(BBPSConstant.RESPONSE_STATUS_KEY)));
LOGGER.warn("Invalid transaction status response for txnId={} from BBPS",
transactionStatusRequest.getTxnId());
throw new CustomException(String.valueOf(dataMap.get("message")), String.valueOf(dataMap.get("status")),
@@ -350,18 +425,29 @@ public class PaymentServiceImpl implements PaymentService {
LOGGER.info("[{}] START | reqId={} | mid={} | clientReqId={}", apiName, requestId,
transactionStatusRequest.getMid(), clientReqId);
Optional<PaymentInitiate> paymentInitiate = paymentIntiateRepository.findByReqId(clientReqId);
if (paymentInitiate.isEmpty()) {
// look up TransactionMaster(s) by clientReqId instead of PaymentInitiate
List<TransactionMaster> transactionMasters = transactionMasterRepository.findByClientReqId(clientReqId);
if (transactionMasters == null || transactionMasters.isEmpty()) {
throw new CustomException(
BBPSConstant.NO_BILL_FOUND, // message // status
BBPSConstant.FAILED_STATUS,
BBPSConstant.HTTP_NOT_FOUND, // statusCode
"Bill not found in database for given clientReqId"
BBPSConstant.NO_BILL_FOUND, // message // status
BBPSConstant.FAILED_STATUS,
BBPSConstant.HTTP_NOT_FOUND, // statusCode
"Bill not found in database for given clientReqId"
);
}
// prefer a TransactionMaster with a real bankTxnId (not a placeholder)
TransactionMaster chosen = null;
for (TransactionMaster t : transactionMasters) {
if (t.getBankTxnId() != null && !t.getBankTxnId().startsWith("PENDING_") && !t.getBankTxnId().startsWith("INVALID_") && !t.getBankTxnId().startsWith("INVALID_JSON_")) {
chosen = t;
break;
}
}
if (chosen == null) chosen = transactionMasters.get(0);
String url = paymentUrl + BBPSConstant.CHECK_TRANSACTION_BY_CLIENT_REQ_ID_URL
+ paymentInitiate.get().getTxnId();
+ chosen.getTxnId();
BharatConnectMaster headersData = beneficiaryDetailsRepository.findByOrgId(BBPSConstant.ORG_ID);
HttpHeaders headers = helper.buildHeaders(headersData);
@@ -419,4 +505,52 @@ public class PaymentServiceImpl implements PaymentService {
}
}
/**
* Ensure the provided internal txnId is unique in bbps_transaction_master.txn_id.
* If a record already exists with the same txnId, append _1, _2, ... until unique.
*/
private String makeUniqueTxnId(String baseTxnId) {
if (baseTxnId == null || baseTxnId.isBlank()) return baseTxnId;
List<TransactionMaster> existing = transactionMasterRepository.findByTxnId(baseTxnId);
if (existing == null || existing.isEmpty()) {
return baseTxnId;
}
int suffix = 1;
String candidate;
while (true) {
candidate = baseTxnId + "_" + suffix;
List<TransactionMaster> coll = transactionMasterRepository.findByTxnId(candidate);
if (coll == null || coll.isEmpty()) {
return candidate;
}
suffix++;
}
}
/**
* Try to save TransactionMaster and handle unique txnId collisions that may occur under concurrency.
* This method will attempt to save up to maxAttempts; on duplicate collision it will append a numeric suffix.
*/
private void saveTransactionMasterWithRetry(TransactionMaster transactionMaster) {
final int maxAttempts = 5;
String baseTxnId = transactionMaster.getTxnId();
for (int attempt = 0; attempt < maxAttempts; attempt++) {
try {
if (attempt == 0) {
transactionMaster.setTxnId(makeUniqueTxnId(baseTxnId));
} else {
transactionMaster.setTxnId(baseTxnId + "_" + attempt);
}
transactionMasterRepository.save(transactionMaster);
return; // success
} catch (org.springframework.dao.DataIntegrityViolationException dex) {
LOGGER.warn("Duplicate txnId detected when saving TransactionMaster (attempt {}) for baseTxnId={}: {}", attempt, baseTxnId, dex.getMessage());
// retry with next suffix
}
}
// if we reach here, all attempts failed
LOGGER.error("Failed to save TransactionMaster after {} attempts for baseTxnId={}", maxAttempts, transactionMaster.getTxnId());
throw new CustomException("Unable to save TransactionMaster due to txnId collisions", BBPSConstant.FAILED_STATUS, 500, "Duplicate txnId");
}
}
@@ -87,7 +87,6 @@ public class PaymentStartServiceImpl implements PaymentStartService {
String txnId = helper.generateTxnId(15);
LOGGER.info("MID IS:{}",paymentMid);
LOGGER.info("[startIntentPayment] enter requestId={} txnId={} mid={}", requestId, txnId, request.getMid());
helper.validateMerchant(request.getMid());
// inbound log
@@ -102,7 +101,7 @@ public class PaymentStartServiceImpl implements PaymentStartService {
sent.setEnckey(paymentEncryKey);
String plaintext = helper.convertObjectToJson(sent);
String encrypted = encryptionUtil.encryptMData(plaintext, paymentEncryKey);
PaymentRequestPayload finalPayload = new PaymentRequestPayload();
finalPayload.setMid(paymentMid);
finalPayload.setPayload(encrypted);
@@ -217,7 +216,6 @@ public class PaymentStartServiceImpl implements PaymentStartService {
String requestId = request.getReqId();
String apiName = BBPSConstant.API_START_PAYMENT;
String txnId = helper.generateTxnId(15);
LOGGER.info("[startWebPayment] enter requestId={} txnId={} mid={}", requestId, txnId, request.getMid());
helper.validateMerchant(request.getMid());