// Close the modal after submission
this.closePaymentModal();
}
closePaymentModal() {
this.closePopupEvent.emit();
}
redirectToPayment() {
// Create a new form element
const form = document.createElement('form');
form.method = 'POST';
form.action = 'https://dipuat.sbigen.in/CD/CDAmount';
// form.action = 'https://dip.sbigeneral.in/CD/CDAmount';
//form.action='https://dippreprod.sbigeneral.in/CD/CDAmount';
form.target='_blank';
// Create hidden inputs
const imdCodeInput = document.createElement('input');
imdCodeInput.type = 'hidden';
imdCodeInput.name = 'imdcode';
imdCodeInput.value = this.responseData?.imd_code || '';
console.log("imdcode"+imdCodeInput.value);
code
const accNoInput = document.createElement('input');
accNoInput.type = 'hidden';
accNoInput.name = 'accno';
accNoInput.value = this.responseData?.aCDAccount || '';
console.log("accNoInput"+accNoInput.value);
const amountInput = document.createElement('input');
amountInput.type = 'hidden';
amountInput.name = 'amount';
amountInput.value = (this.responseData?.totalPremiumAmount ??0).toString();
console.log("amountInput.value"+amountInput.value);
const oldestTranDateInput = document.createElement('input');
oldestTranDateInput.type = 'hidden';
oldestTranDateInput.name = 'oldestIRDate';
oldestTranDateInput.value = (this.oldestTranDate ??'').toString();
console.log("oldestTranDateInput.value"+oldestTranDateInput.value);
const transactionIdInput = document.createElement('input');
transactionIdInput.type = 'hidden';
transactionIdInput.name = 'transactionid';
transactionIdInput.value = (this.responseData?.transactionId ??0).toString();
console.log("transactionIdInput.value"+transactionIdInput.value);
const oldestInsuranceDateInput = document.createElement('input');
oldestInsuranceDateInput.type = 'hidden';
oldestInsuranceDateInput.name = 'oldestInsuranceDate';
oldestInsuranceDateInput.value = (this.oldestInsuranceDate ??'').toString();
console.log("oldestInsuranceDateInput.value"+oldestInsuranceDateInput.value);
const cdCodeInput = document.createElement('input');
cdCodeInput.type = 'hidden';
cdCodeInput.name = 'cdCode';
cdCodeInput.value = (this.cd_code ??'').toString();
console.log("cdCodeInput.value"+cdCodeInput.value);
// Append inputs to the form
form.appendChild(imdCodeInput);
form.appendChild(accNoInput);
form.appendChild(amountInput);
form.appendChild(transactionIdInput);
form.appendChild(oldestTranDateInput);
form.appendChild(oldestInsuranceDateInput);
form.appendChild(cdCodeInput);
// Append the form to the body
document.body.appendChild(form);
// Show a loading message
const loadingMessage = document.createElement('h1');
loadingMessage.innerText = 'Please wait while we redirect you...';
document.body.appendChild(loadingMessage);
// Submit the form after a short delay
setTimeout(() => {
form.submit();
}, 2000); // Wait for 2 seconds before submitting
// Add beforeunload event listener for a confirmation message
window.addEventListener('beforeunload', (e) => {
e.preventDefault();
e.returnValue = ''; // Show confirmation dialog
});
}
}
just tell me the update credit limit how it is updating tell me that
Assistant
Based on the provided Angular component code, there is no explicit logic or method that directly updates a "credit limit" anywhere in the given HTML or TypeScript files.
What the code is doing instead:
Collecting payment-related data (account numbers, total amount, policy numbers, etc.) via @Input() bindings.
On form submission (onSubmitPayment()):
It populates a PaymentModel object (reportCard) with these inputs and some data fetched from localStorage.
It calls a service method UpdatePaymentCardDetails() passing this reportCard object:
When the response is received, it stores it in this.responseData and then calls redirectToPayment(), which dynamically creates and submits a POST form to an external payment URL.
The modal popup is also closed right after submitting.
About the "update credit limit":
The only data mutation happening in your code is with the service call:
This call hits your backend or API service, which presumably processes the payment and may update the credit limit or any other relevant database records on the backend side.
Since your Angular code only sends data (reportCard) and receives a response (responseData), the actual updating/upsert of the credit limit likely happens on the server or API method that UpdatePaymentCardDetails() calls.
Your front-end code does not show or handle any update logic for the credit limit directly.
Summary:
The credit limit is not updated in this Angular code itself.
The update presumably happens on the backend inside the API that handles UpdatePaymentCardDetails() which receives the reportCard.
Your front-end's responsibility is to prepare the data, send it to the backend service, and then redirect the user to the payment gateway after successful response.
If you want to confirm how the credit limit updates, you should check the implementation of:
The backend method or API behind TransactionByacdNoService.UpdatePaymentCardDetails()
This is where you will likely find the business logic of updating the credit limit in your database or payment provider system.
exportCreditData1(filters: any): Observable<any[]> {
return this.http.post<any[]>(${this.baseUrl}/ChildExport, filters);
}
}and this is java springboot backend code @Autowired
private CustomTransactionService customTransactionService;
code
Assistant
Thanks for sharing the backend code! Here’s an explanation of how the credit limit update (or more precisely the payment transaction logging) is working based on your Spring Boot backend:
This sends the paymentMethodRequest (an instance of PaymentModel) as JSON payload to the backend endpoint:
code
POST /ReplenishLimitPaymentInsert
2. Spring Boot Controller receives the request
java
@PostMapping("/ReplenishLimitPaymentInsert")
public ResponseEntity<?> processCustomTransaction(@RequestBody Map<String, Object> requestMap) {
try {
PaymentResponseModel model = customTransactionService.processCustomTransaction(requestMap);
return ResponseEntity.status(HttpStatus.OK).body(model);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to process transactions");
}
}
The request JSON is deserialized into a Map<String, Object> named requestMap.
The controller calls the service method processCustomTransaction(requestMap).
The service processes the transaction and returns a PaymentResponseModel.
3. Service method processes the transaction and updates data:
java
User
code
<!-- Row for Agreement Code -->
<div class="col-md-6 mb-3">
<label for="agreementCode" class="form-label">Child Code</label>
<input
type="text"
id="agreementCode"
class="form-control"
[(ngModel)]="creditCardPopupmodel.childcode"
name="childcode"
required
readonly
/>
<!-- <div *ngIf="creditCardForm.submitted && !creditCardForm.controls.agreementCode.valid" class="text-danger">
Agreement Code is required.
</div> -->
</div>
</div>
<!-- Existing fields for Parent Code, Child Code, Credit Limit, etc. -->
<!-- Row for Parent Code -->
<!-- Row for Child Code -->
<!-- Row for Credit Limit -->
<div class="row">
<div class="col-md-6 mb-3">
<label for="creditLimit" class="form-label">Credit Limit</label>
<input
type="text"
id="creditLimit"
class="form-control"
[(ngModel)]="creditCardPopupmodel.creditLimit"
name="creditLimit"
required
/>
</div>
<!-- Row for Credit Period -->
<div class="col-md-6 mb-3">
<label for="creditPeriod" class="form-label">ACD Number</label>
<input
type="text"
id="creditPeriod"
class="form-control"
[(ngModel)]="creditCardPopupmodel.acdNumber"
name="creditPeriod"
required
readonly
/>
</div>
</div>
<!-- Row for Limit Start Date -->
<!-- Row for Limit End Date -->
<!-- Submit Button -->
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary" >Update</button>
</div>
Assistant
Yes, the credit limit update logic is primarily handled in this Angular component (CreditUpdatePopupComponent) within the onSubmit() method, which sends the updated credit limit data to the backend via a service call.
What happens in onSubmit() (the core update logic here):
typescript
onSubmit() {
// 1. Validation checks
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert('Entered Credit Limit exceeds the available amount: ' + this.availableamount);
return;
}
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available amount: ' + this.balanceLimit);
return;
}
// 2. Calculate new available limit for child code (seems to subtract updated credit limit from current credit limit)
this.ChildcodeavailableLimit = this.CreditLimit - this.creditCardPopupmodel.creditLimit;
// Note: This line *overwrites* creditLimit in the model to the reduced available limit
this.creditCardPopupmodel.creditLimit = this.ChildcodeavailableLimit;
// 3. Send updated credit card details to backend for saving
this.creditCardlimit.UpdateCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
console.log('Data updated successfully:', response);
alert('Data saved successfully');
// 4. Optionally fetch updated credit card details to refresh UI and reload page
// (with encryption on ImdCode for security)
const customKey = new Uint8Array([...]);
const customIV = new Uint8Array([...]);
encryptText({ imdCode: this.parentCode1.trim() }, customKey, customIV).then((encryptedResult) => {
if (encryptedResult) {
this.creditCardlimit.FetchCreditCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv).subscribe(
(data) => {
this.report1 = data;
window.location.reload(); // Refresh page after update
this.closePopup();
},
(error) => {
console.error('Error fetching credit card details:', error);
}
);
}
}).catch((error) => {
console.error('Error encrypting data:', error);
});
},
(error) => {
console.error('Error saving data:', error);
alert('An error occurred while saving data. Please try again.');
}
);
}
User
so what is logic here and what is that we are doing minus from and when we cant update tell me exact
Assistant
Certainly! Let's break down the exact logic happening in your Angular component onSubmit() method, specially focusing on the credit limit update and validation.
What is the logic happening here?
1. Validation of entered Credit Limit:
ts
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert('Entered Credit Limit exceeds the available amount: ' + this.availableamount);
return;
}
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available amount: ' + this.balanceLimit);
return;
}
The user enters a new credit limit (creditCardPopupmodel.creditLimit).
The code checks 2 things:
Is the entered credit limit greater than the parent's available amount (availableamount)?
If yes, the update is stopped and an alert is shown.
Is the entered credit limit greater than the child's current balance limit (balanceLimit)?
If yes, the update is stopped and an alert is shown.
=> You cannot update if the new credit limit exceeds either the parent’s available credit or the child’s balance limit.
2. Calculation of the new credit limit value sent to API:
CreditLimit is the current credit limit of the child (input from parent component).
creditCardPopupmodel.creditLimit is the new credit limit entered by the user.
The logic subtracts the new credit limit entered by user from the current credit limit:
User
so now just have to change a small change where parent can update limit to give to child if it has balance availablle that means if parent available limit is 10lakhs then if in child we are updating or allocating to child it should check parent limit then only give and then parent available limit should be minus whatever is given to child as parent was having it
Assistant
Got it! You want to implement this logic:
The parent has an available credit limit (say 10 lakhs).
When updating the child's credit limit (i.e., allocating credit to child),
The parent’s available limit should be checked and decreased by the allocated amount to the child.
The child can only be allocated credit if the parent has enough available balance.
After allocation, the parent’s available limit should reduce accordingly.
How to implement this in your existing Angular component?
Currently, you check for available limits but you do NOT update or subtract the parent’s available limit anywhere in your component or backend call.
Step-by-step changes at Angular side:
1. Modify onSubmit() to:
Take the difference between old child limit and new child limit, which is the change amount that affects the parent’s available limit.
Check if parent has enough balance for the difference.
Send this difference info to backend so the parent’s available limit gets adjusted.
Adjusted Angular logic example:
typescript
User
give me full with existing and where i need change with comments above it
Assistant
Certainly! Below is your existing Angular onSubmit() method with full changes and comments inline to implement the logic where:
Parent's available limit is checked before allocating to child.
Parent's available limit is decreased by the allocated amount.
Child's credit limit is updated accordingly.
Updated Angular onSubmit() method with detailed comments
typescript
User
also the exisitng functionality of limits should be intact it is just a addon on this
Assistant
Certainly! I'll integrate the new delta-based parent-child credit limit logicas an addition within your existing Angular onSubmit() method, keeping all current validations and functionality intact, and adding only the necessary parts to handle the parent available limit adjustment.
Complete updated onSubmit() with proper comments and preserved original logic plus delta logic as addon
typescript
onSubmit() {
// === Existing validation - 1 ===
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert('Entered Credit Limit exceeds the available amount: ' + this.availableamount);
return;
}
// === Existing validation - 2 ===
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available amount: ' + this.balanceLimit);
return;
}
// -----------------------------------
// ADDITIONAL LOGIC: calculate delta and check parent available limit
// -----------------------------------
// Calculate delta between new and old credit limit
const oldChildLimit = this.CreditLimit; // from @Input() - existing limit before update
const newChildLimit = this.creditCardPopupmodel.creditLimit;
const deltaLimit = newChildLimit - oldChildLimit;
// Allow only if parent has sufficient available credit for increased allocation
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return; // reject if not enough parent credit available
}
// -----------------------------------
// Prepare updated model including delta (addon)
// -----------------------------------
this.creditCardPopupmodel.creditLimit = newChildLimit;
this.creditCardPopupmodel.creditLimitDelta = deltaLimit; // Use this new property in your model
// -----------------------------------
// Call backend to update child credit limit & adjust parent available limit accordingly
// -----------------------------------
this.creditCardlimit.UpdateCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
console.log('Data updated successfully:', response);
alert('Data saved successfully');
// Refresh UI with new data, keep original behavior
this.closePopup();
window.location.reload();
},
(error) => {
console.error('Error saving data:', error);
alert('An error occurred while saving data. Please try again.');
}
);
}
User
onSubmit() {
if (
!this.creditCardPopupmodel.childcode ||
this.creditCardPopupmodel.childcode === ''
) {
alert('Please select a Child Code.');
return;
}
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert('Entered Credit Limit exceeds the available amount. :: ' + this.availableamount);
return;
}
if(this.creditCardPopupmodel.creditPeriod>this.creditPeriod)
{
alert('Entered Credit Period is gether then Perent Credit Card Period. :: ' + this.creditPeriod);
return;
}
// Handle the form submission
this.CreditCardServicepopup.SaveCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
console.log('Data saved successfully:', response);
alert(response.message);
);
} this is my code add the new here and give will directly copy paste with addon changes
Assistant
Certainly! Below is your provided onSubmit() method with the new delta-based parent-child credit limit logic added as an addon, keeping your existing validations and flow intact.
Here, you are overwriting the creditLimit field with the delta, which is a difference value (could be positive or negative). This is likely the cause why the child is getting the limit changed incorrectly. The child credit limit should receive the new absolute value (the actual limit), not the delta.
Your existing check:
ts
if (this.creditCardPopupmodel.creditLimit > this.availableamount) { ... }
still compares the new limit against the parent's available amount, but this is only if availableamount is the parent available limit.
However, you mentioned it's "checking with child balance limit". This check is due to where and how the availableamount is set and used.
How to fix them:
1. Separate delta from creditLimit properly
Your model’s creditLimit should always hold the child's actual credit limit (absolute value).
Use a new field like creditLimitDelta to hold the difference (new - old).
Trainsaction_id = creditLimitService.UpdateTransactiondateCreditLimit(creditTransactionLimit);
if (Trainsaction_id != null) {
logger.info("fetch CardLimit details found for CardLimitController: {}", creditTransactionLimit);
return ResponseEntity.status(HttpStatus.ACCEPTED)
.body(new ResponseMessage("Data has been Updated successfully"));
} else {
return ResponseEntity.status(HttpStatus.ACCEPTED).body(new ResponseMessage(""));
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Internal server error occurred while fetching CardLimit details for CardLimitController: {}",
creditTransactionLimit, e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new ResponseMessage("INTERNAL SERVER ERROR"));
}
} this is backend call @Override
public String UpdateTransactiondateCreditLimit(
CreditCardLimitPopup creditTransactionLimit) {
logger.info(
"Fetching CardLimit report details for UpdateTransactiondateCreditLimit: {}",
creditTransactionLimit);
List<CreditCardLimit> transactionDetails = creditLimitRepo
.fetchCreditParentAndChildCredirDetails(
creditTransactionLimit.getParentCode(),
creditTransactionLimit.getChildcode());
if (!transactionDetails.isEmpty()) {
CreditCardLimit transaction = transactionDetails.get(0);
transaction.setImd_paraent_code(
creditTransactionLimit.getParentCode());
transaction
.setImd_child_code(creditTransactionLimit.getChildcode());
transaction.setACD_number(creditTransactionLimit.getAcdNumber());
transaction
.setCredit_Limit(creditTransactionLimit.getCreditLimit());
String tran_id = creditLimitRepo.save(transaction).getACD_number();
return tran_id;
} else {
return null;
}
}
Assistant
Thanks for sharing your backend code! Here's an explanation how it currently works and what you need to change to support the parent credit limit adjustment based on the delta.
Current backend flow
Your controller endpoint /updateCreditLimitTransaction calls:
You only update the child's credit limit with the passed new absolute credit limit.
You do NOT update the parent's available credit limit anywhere.
You do NOT use the creditLimitDelta at all.
How to modify to support your requirements?
You want to:
Update the child's credit limit to the new limit.
Adjust the parent's available limit by subtracting or adding the creditLimitDelta.
Make sure the parent's limit cannot go negative.
Suggested backend code changes
Modify your UpdateTransactiondateCreditLimit method to:
Fetch parent's available credit limit record.
Calculate parent's new available limit = old available - delta (delta can be positive or negative).
Validate parent's available limit new value ≥ 0, else reject or throw exception.
Update parent's available limit in DB.
Update child's credit limit in DB.
User
i only track parentlimit assign but it is shown only in frontend and all calulation is done there only so without updating backend api how to do it ? also available parent limit is shown in frontend also so how to show this things
Assistant
Got it! Since you track the parent’s available limit only on the frontend (not updated or stored on the backend), all the logic for checking and updating limits should happen on the frontend only.
You want to:
Check if the parent has enough available limit before assigning more credit to the child.
Adjust the parent’s available limit shown on the frontend after the assignment.
Keep the backend API as-is (only updates child's credit limit).
How to handle this fully in the frontend?
Step 1: Keep track of parent's available limit as a frontend variable (availableamount).
Step 2: On update:
Compute how much credit you are assigning deltaLimit = newChildLimit - oldChildLimit.
Check if deltaLimit is positive and less than or equal to parent's available limit (availableamount).
If valid, update child's credit limit on backend.
Reduce parent's available limit locally on frontend by deltaLimit after successful update, so UI stays consistent.
Modified frontend onSubmit() outline example:
typescript
onSubmit() {
if (!this.creditCardPopupmodel.childcode || this.creditCardPopupmodel.childcode === '') {
alert('Please select a Child Code.');
return;
}
const oldChildLimit = this.CreditLimit; // previous credit limit of child
const newChildLimit = this.creditCardPopupmodel.creditLimit; // new credit limit entered
const deltaLimit = newChildLimit - oldChildLimit; // how much credit is being changed/added
// Check child's balance limit (existing check)
if (newChildLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available amount: ' + this.balanceLimit);
return;
}
// Check parent available limit if deltaLimit > 0 (increment allocation)
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return;
}
// Proceed with backend update (only child credit limit updated on server)
this.CreditCardServicepopup.SaveCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
response => {
alert(response.message);
// Manually reduce parent available amount locally
if (deltaLimit > 0) { // only reduce if increased allocation
this.availableamount -= deltaLimit;
}
// Optionally, update UI by emitting event, refreshing list, etc.
this.closePopup();
window.location.reload(); // or update data without full reload as needed
},
error => {
alert('Error saving data.');
}
);
}
@Override
public PaymentResponseModel processCustomTransaction(Map<String, Object> requestMap) {
String txnId = null;
// Extract data from request map
String acdNumber = (String) requestMap.get("aCDAccount");
String imdcodes = (String) requestMap.get("imd_code");
String agrementCode = (String) requestMap.get("agrementCode");
List<String> policyNumbers = (List<String>) requestMap.get("policyNumber");
List<String> amounts = (List<String>) requestMap.get("amount");
String totalAmount = String.valueOf(requestMap.get("totalPremiumAmount"));
String userIds = String.valueOf(requestMap.get("userIds"));
String usertypeIds = String.valueOf(requestMap.get("UserTypeId"));
// Generate new transaction ID:
String transactionId = generateNextTransactionId();
// For each policy number and amount, create a new transaction log record:
for (int i = 0; i < Math.max(policyNumbers.size(), amounts.size()); i++) {
String policyNumber = i < policyNumbers.size() ? policyNumbers.get(i) : "";
String amount = i < amounts.size() ? amounts.get(i) : "";
Tble_Transaction_Credit_Limit_log log = new Tble_Transaction_Credit_Limit_log();
log.setACD_NUMBER(acdNumber);
log.setAMOUNT(amount);
log.setPOLICY_NUMBER(policyNumber);
log.setTRANSACTIONID(transactionId);
log.setIMD_CODE(imdcodes);
log.setTOTALPREMIUMAMOUNT(totalAmount);
log.setAGREMENTCODE(agrementCode);
log.setCREATION_DATE(new Date());
log.setPAYMENTSTATUS("N");
log.setUSERID(userIds);
log.setUSERTYPEID(usertypeIds);
// Save the log entry to the database:
txnId = repository.save(log).getTRANSACTIONID();
}
PaymentResponseModel paymentmodel = new PaymentResponseModel();
paymentmodel.setTransactionId(txnId);
paymentmodel.setaCDAccount(acdNumber);
paymentmodel.setImd_code(imdcodes);
paymentmodel.setTotalPremiumAmount(totalAmount);
return paymentmodel;
}
Key points:
The method extracts multiple input values such as ACD account, IMD code, agreement code, lists of policy numbers and their respective amounts, total premium amount, user IDs, etc.
It generates a new unique transaction ID using a synchronized method generateNextTransactionId() which finds the latest transaction ID in the database and increments it.
It loops through the policy number & amount lists, creates a new Tble_Transaction_Credit_Limit_log record for each pair, sets all details including PAYMENTSTATUS = "N" (probably meaning "Not Paid" or "Pending").
It then saves each log record in the database via the repository.save() call. This is the actual data persistence/update step.
Finally it creates a PaymentResponseModel object with the transaction details and returns it to the controller.
This method generates the next transaction ID by finding the max existing ID and adding 1.
The numeric part of the transaction ID is incremented.
5. Summary: How "update credit limit" is done
There is no direct credit limit field updated here; instead, a transaction log record (Tble_Transaction_Credit_Limit_log) is inserted for each policy & amount.
This log tracks the replenishment/payment details (amount, policy number, agreement, user info).
The payment status is marked "N" (probably meaning not complete).
This transaction log and the generated transaction ID can be used subsequently by other parts of your system to adjust the credit limits or confirm payment completion.
The insert operation performed by repository.save(log) is the main DB update step.
Additional notes:
Your application's logic may have another process or batch job that consumes these logs to adjust actual credit limits once payment status changes or confirmation arrives.
Or the credit limit may be implicitly tracked by summing these logs.
The service method proccessingPaymentMethod(...) also hints that another call to an external payment gateway may be involved after logging.
In short:
The backend does not directly update a “credit limit” value in this code.
Instead, it creates transaction log entries for payment requests associated with credit limit replenishment.
The Angular frontend sends payment data → backend logs transactions → then frontend redirects user to payment provider.
The actual credit limit update may occur later as part of payment fulfillment or reconciliation workflow not shown here.
If you want to track exactly where the credit limit number gets updated, you would look for code that modifies the credit limit field in a customer or account table based on these transactions — presumably in another service or triggered by status changes.
If you want, I can also help you design/trace that next step!
// Encrypting the IMD code
encryptText({ imdCode: imdCode.trim() }, customKey, customIV).then((encryptedResult) => {
if (encryptedResult) {
this.creditCardlimit.FetchParentCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv).subscribe({
next: (data: any[]) => { // Assuming the response is an array of objects
console.log('API Response:', data);
code
// Check if data array has at least one element
if (data.length > 0) {
// Access the 'availableAmount' from the first object in the array
this.availableamount = parseFloat(data[0].availabaleAmount || '0'); // Corrected spelling from 'availabaleAmount'
console.log('Available update Amount:', this.availableamount);
// Use the available amount in the template
// Example: availableamount1 = {{this.availableamount | currency:'INR':'symbol':'1.2-2'}}
} else {
console.error("No data available in the response");
}
},
error: (error) => {
console.error("Error fetching available amount:", error);
}
});
} else {
console.error("Encryption failed, no encrypted result returned.");
}
// Encrypting the IMD code
encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
.then((encryptedResult) => {
if (encryptedResult) {
this.creditCardlimit.FetchChildCardDetails(encryptedResult.encryptedText, encryptedResult.key, encryptedResult.base64iv)
.subscribe({
next: (data:any[]) => {
// Data is not empty
if (data.length > 0) {
// Access the 'availableAmount' from the first object in the array
this.childavailableamount = parseFloat(data[0].balanceLimit || '0'); // Corrected spelling from 'availabaleAmount'
console.log('childavailableamount Available update Amount:', this.availableamount);
// Use the available amount in the template
// Example: availableamount1 = {{this.availableamount | currency:'INR':'symbol':'1.2-2'}}
} else {
console.error("No data available in the response");
}
},
error: (error) => {
console.error('Error fetching parent card details:', error);
//this.isLoading = false;
// You can display a user-friendly error message here
}
});
} else {
alert('Maximum number of requests sent within 1 hour exceeded. Please try again later.');
}
})
.catch((error) => {
console.error("Encryption error:", error);
// Handle encryption error
});
}
onSubmit() {
// Check if the entered credit limit exceeds the available amount
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert('Entered Credit Limit exceeds the available amount: ' + this.availableamount);
return;
}
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available amount: ' + this.balanceLimit);
return;
}
this.ChildcodeavailableLimit=this.CreditLimit-this.creditCardPopupmodel.creditLimit;
this.creditCardPopupmodel.creditLimit=this.ChildcodeavailableLimit;
// Update credit card details
this.creditCardlimit.UpdateCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
console.log('Data updated successfully:', response);
alert('Data saved successfully');
// Uncomment the following block if you want to fetch updated credit card details
// Encryption logic
const customKey = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
const customIV = new Uint8Array([16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
The adjusted credit limit model (creditCardPopupmodel) with updated (subtracted) limit is sent to backend API.
Summary:
Step
Explanation
Check if new limit > parent's available
Don’t update if new limit exceeds parent’s available credit.
Check if new limit > child’s balance limit
Don’t update if new limit exceeds child’s current balance limit.
Calculate ChildcodeavailableLimit
Subtract new entered limit from child's current limit to find available remaining credit.
Assign this difference to model’s creditLimit
The value sent to backend represents remaining or adjusted credit limit, not raw value.
Call backend API with the updated credit limit
Backend persists update based on this new adjusted credit limit.
When does the update get rejected / prevented?
If user tries to enter a credit limit higher than the parent’s available credit → blocked.
If user tries to enter a credit limit higher than the child’s current balance limit → blocked.
In either case, an alert is shown and no backend API call happens.
Why subtract Current - New limit?
This indicates the component and backend expect the update as a delta or available limit remaining, not just a raw new limit.
In other words:
New Available Limit to assign = Current Credit Limit - Credit Limit Entered by User
This could also mean:
The user is adjusting how much of the credit is assigned/used/blocked for the child.
The difference (remaining limit) is stored or updated accordingly.
If you want the complete picture, it helps to look at the backend's handling of this updated data to understand exactly how that debit or credit is applied in the database.
Does this clarify the logic and update conditions?
If you want, I can also help analyze your backend update method to confirm how exactly the update happens there!
onSubmit() {
// Calculate how much more credit parent needs to allocate or deallocate
const oldChildLimit = this.CreditLimit; // current child limit before update
const newChildLimit = this.creditCardPopupmodel.creditLimit; // new entered limit
const deltaLimit = newChildLimit - oldChildLimit; // positive means allocation increase, negative means decrease
// Check if parent has enough available limit to allocate the increase (deltaLimit > 0)
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return; // prevent update
}
// Check if new child limit exceeds child's balance limit (optional, your existing check)
if (newChildLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available limit: ' + this.balanceLimit);
return;
}
// Prepare data for backend - send updated creditlimit and maybe delta for parent's update
// You can add a new property in model to send delta if you want
this.creditCardPopupmodel.creditLimit = newChildLimit;
this.creditCardPopupmodel.creditLimitDelta = deltaLimit; // add this property in your model
// Call backend to update child credit and decrease parent available by deltaLimit (backend must implement this)
this.creditCardlimit.UpdateCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
alert('Data updated successfully');
// Reload or update UI as needed
this.closePopup();
window.location.reload();
},
(error) => {
alert('Error updating credit limit');
}
);
}
Changes you need in your CreditCardLimitPopup model:
Add a field:
typescript
creditLimitDelta?: number;
Backend logic needed (springboot):
When API receives updated child credit limit and delta:
Decrease the parent’s available limit by deltaLimit if positive (allocating more credit to child).
Increase parent’s available limit by absolute delta if negative (child's credit reduces, so parent regains limit).
Update child's credit limit in DB.
Return success/failure.
Why is this approach better?
You use difference (delta) to adjust parent available limit incrementally.
Ensures parent's available limit never goes negative.
Child can only get credit within what parent can provide.
Parent’s available limit is always consistent with all allocations made.
Summary:
Step
What happens
User inputs new child credit
Calculate difference from old limit
Validate parent has enough
If difference positive and exceeds parent's available limit, reject the update
Update both child and parent
Send new values + delta to backend
Backend adjusts limits
Backend applies delta to parent available and child credit
UI confirms success
Show success alert, refresh UI
If you want, I can also help you write or review the backend method logic for this! Would you like that?
onSubmit() {
// -----------------------------
// Step 1: Calculate how much change in credit limit (delta) is requested
// Positive delta = increase in child's credit limit (parent has to provide more)
// Negative delta = decrease in child's credit limit (parent regains some credit)
// -----------------------------
const oldChildLimit = this.CreditLimit; // current child's credit limit before update
const newChildLimit = this.creditCardPopupmodel.creditLimit; // new credit limit entered by user
const deltaLimit = newChildLimit - oldChildLimit;
// -----------------------------
// Step 2: Validate if the parent has enough available limit to cover an increase
// If deltaLimit > 0, parent must have at least deltaLimit available
// If not enough parent available credit, show alert and reject
// -----------------------------
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return; // Do not proceed
}
// -----------------------------
// Step 3: Validate child’s new credit limit against child's own balance limit
// -----------------------------
if (newChildLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available limit: ' + this.balanceLimit);
return; // Do not proceed
}
// -----------------------------
// Step 4: Prepare the model to send to backend
// Send the NEW credit limit for the child as-is
// Also send the delta limit, so backend knows how to adjust parent's available limit
// Add the delta value to the model (make sure model has this new field declared)
// -----------------------------
this.creditCardPopupmodel.creditLimit = newChildLimit;
this.creditCardPopupmodel.creditLimitDelta = deltaLimit; // <-- Add this (create field in model)
// -----------------------------
// Step 5: Call service to update credit limits (child + adjust parent limit)
// Backend will receive new credit limit and delta (how much parent's limit changes)
// -----------------------------
this.creditCardlimit.UpdateCreditCardpopupDetails(this.creditCardPopupmodel).subscribe(
(response) => {
console.log('Data updated successfully:', response);
alert('Data saved successfully');
// Refresh or close popup as needed
this.closePopup();
window.location.reload(); // Refresh the whole page to load updated data
},
(error) => {
console.error('Error saving data:', error);
alert('An error occurred while saving data. Please try again.');
}
);
}
What you need to do elsewhere:
Add creditLimitDelta to your model class CreditCardLimitPopup:
typescript
export class CreditCardLimitPopup {
parentCode!: string;
childcode!: string;
acdNumber!: string;
creditLimit!: number;
// Add this new optional property for delta support
creditLimitDelta?: number;
// ... existing properties
}
Backend must be updated to:
Receive the creditLimit (new child credit limit) and creditLimitDelta.
Update the child's credit limit to the new value.
Adjust the parent's available credit limit by decreasing it by creditLimitDelta if positive, or increasing if creditLimitDelta negative.
Enforce that parent's available limit never becomes negative (reject or handle errors accordingly).
UI refresh, alerting, and closing popup remain unchanged.
What’s the new add-on?
Calculation of delta (difference between new and old credit limit values).
Additional check that when allocating more credit (deltaLimit > 0), parent has enough available credit (availableamount).
Passing creditLimitDelta to backend for proper parent available limit update.
Don’t forget:
Add the property creditLimitDelta into the model class if not yet done:
typescript
export class CreditCardLimitPopup {
parentCode!: string;
childcode!: string;
acdNumber!: string;
creditLimit!: number;
creditLimitDelta?: number; // new property for delta handling
// other existing fields...
}
Update the backend API to handle this creditLimitDelta property:
Adjust parent’s available credit limit accordingly.
Keep existing child credit limit update logic.
If you want, I can help you craft the backend logic modifications too!
Summary: The code above adds the delta limit logic as an extra validation and data sent to backend, without breaking or removing your current validation and update flows. You retain original behavior plus the new parent-child credit check/update.
onSubmit() {
// === Existing validation: check Child Code selected ===
if (
!this.creditCardPopupmodel.childcode ||
this.creditCardPopupmodel.childcode === ''
) {
alert('Please select a Child Code.');
return;
}
// === Existing validation: New Credit Limit <= available amount ===
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert(
'Entered Credit Limit exceeds the available amount. :: ' +
this.availableamount
);
return;
}
// === Existing validation: Credit Period check ===
if (this.creditCardPopupmodel.creditPeriod > this.creditPeriod) {
alert(
'Entered Credit Period is greater than Parent Credit Card Period. :: ' +
this.creditPeriod
);
return;
}
// -------------------------
// ADDON: Calculate delta and validate parent limit for delta allocation
// -------------------------
const oldChildLimit = this.CreditLimit; // current credit limit before update
const newChildLimit = this.creditCardPopupmodel.creditLimit; // newly entered limit
const deltaLimit = newChildLimit - oldChildLimit;
// Only if we are increasing child credit (delta > 0), check parent availability
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert(
'Allocation exceeds parent available limit: ' + this.availableamount
);
return; // block update, parent limit not enough
}
// Add deltaLimit to your model to send it to backend (make sure your model has this field)
this.creditCardPopupmodel.creditLimitDelta = deltaLimit;
// -------------------------
// Existing submission: call service with updated model (which now includes deltaLimit)
// -------------------------
this.CreditCardServicepopup.SaveCreditCardpopupDetails(
this.creditCardPopupmodel
).subscribe(
(response) => {
console.log('Data saved successfully:', response);
alert(response.message);
// Encryption logic for refresh
const customKey = new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
]);
const customIV = new Uint8Array([
16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
]);
encryptText({ imdCode: this.parentCode1.trim() }, customKey, customIV)
.then((encryptedResult) => {
if (encryptedResult) {
this.credit.FetchCreditCardDetails(
encryptedResult.encryptedText,
encryptedResult.key,
encryptedResult.base64iv
).subscribe(
(data) => {
const newRecordCount = data.length;
if (newRecordCount > this.intialrecordcount) {
console.log('New record found, refreshing the page');
window.location.reload(); // Refreshing the page
this.closePopup();
}
},
(error) => {
console.error('Error fetching credit card details:', error);
}
);
}
})
.catch((error) => {
console.error('Error encrypting data:', error);
});
},
(error) => {
console.error('Error saving data:', error);
}
);
}
Additional notes:
Make sure you add creditLimitDelta to your CreditCardLimitPopup model class, like this:
typescript
export class CreditCardLimitPopup {
// ... your existing fields
creditLimitDelta?: number; // Add this property
}
On backend, parse and use this creditLimitDelta to update the parent's available limit correctly.
This preserves all your previous validations and flow, just adds the delta calculation + validation + sending delta info to backend.
Let me know if you want help updating the backend accordingly!
// === Existing validation: New Credit Limit <= available amount ===
if (this.creditCardPopupmodel.creditLimit > this.availableamount) {
alert(
'Entered Credit Limit exceeds the available amount. :: ' +
this.availableamount
);
return;
}
// === Existing validation: Credit Period check ===
if (this.creditCardPopupmodel.creditPeriod > this.creditPeriod) {
alert(
'Entered Credit Period is greater than Parent Credit Card Period. :: ' +
this.creditPeriod
);
return;
}
// -------------------------
// ADDON: Calculate delta and validate parent limit for delta allocation
// -------------------------
const oldChildLimit = this.CreditLimit; // current credit limit before update
const newChildLimit = this.creditCardPopupmodel.creditLimit; // newly entered limit
const deltaLimit = newChildLimit - oldChildLimit;
// Only if we are increasing child credit (delta > 0), check parent availability
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert(
'Allocation exceeds parent available limit: ' + this.availableamount
);
return; // block update, parent limit not enough
}
// Add deltaLimit to your model to send it to backend (make sure your model has this field)
this.creditCardPopupmodel.creditLimit = deltaLimit;
// -------------------------
// Existing submission: call service with updated model (which now includes deltaLimit)
// -------------------------
this.CreditCardServicepopup.SaveCreditCardpopupDetails(
this.creditCardPopupmodel
).subscribe(
(response) => {
console.log('Data saved successfully:', response);
alert(response.message);
// Encryption logic for refresh
const customKey = new Uint8Array([
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
]);
const customIV = new Uint8Array([
16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
]);
encryptText({ imdCode: this.parentCode1.trim() }, customKey, customIV)
.then((encryptedResult) => {
if (encryptedResult) {
this.credit
.FetchCreditCardDetails(
encryptedResult.encryptedText,
encryptedResult.key,
encryptedResult.base64iv
)
.subscribe(
(data) => {
const newRecordCount = data.length;
if (newRecordCount > this.intialrecordcount) {
console.log('New record found, refreshing the page');
window.location.reload(); // Refreshing the page
this.closePopup();
}
},
(error) => {
console.error('Error fetching credit card details:', error);
}
);
}
})
.catch((error) => {
console.error('Error encrypting data:', error);
});
},
(error) => {
console.error('Error saving data:', error);
}
);
} i have added this but it is still checking with child balance limit and not with parent available limit and if then we have assigned the new limit it is reducing from child but we are adding the limit here
ts
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return;
}
The check:
ts
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) { ... }
should be the child balance limit check, separate from parent available.
Final fixed onSubmit() code snippet:
ts
onSubmit() {
// === Existing validation: check Child Code selected ===
if (!this.creditCardPopupmodel.childcode || this.creditCardPopupmodel.childcode === '') {
alert('Please select a Child Code.');
return;
}
// === Optional: check child's new credit limit <= child's balance limit (if applicable) ===
if (this.creditCardPopupmodel.creditLimit > this.balanceLimit) {
alert('Entered child Credit Limit exceeds the available balance limit: ' + this.balanceLimit);
return;
}
// === Calculate delta ===
const oldChildLimit = this.CreditLimit; // existing child limit before update, input property
const newChildLimit = this.creditCardPopupmodel.creditLimit; // the new limit entered by user
const deltaLimit = newChildLimit - oldChildLimit; // how much parent's available limit should change
// === Check if parent has enough available credit if deltaLimit > 0 ===
if (deltaLimit > 0 && deltaLimit > this.availableamount) {
alert('Allocation exceeds parent available limit: ' + this.availableamount);
return;
}
// === Assign fields properly ===
this.creditCardPopupmodel.creditLimitDelta = deltaLimit; // send delta separately
this.creditCardPopupmodel.creditLimit = newChildLimit; // send absolute new limit
// === Continue with existing credit period check ===
if (this.creditCardPopupmodel.creditPeriod > this.creditPeriod) {
alert('Entered Credit Period is greater than Parent Credit Card Period. :: ' + this.creditPeriod);
return;
}
// === Call backend with updated data ===
this.CreditCardServicepopup.SaveCreditCardpopupDetails(this.creditCardPopupmodel)
.subscribe(
(response) => {
console.log('Data saved successfully:', response);
alert(response.message);
// Existing encryption and refresh logic...
// ...
},
(error) => {
console.error('Error saving data:', error);
}
);
}
Important Notes:
Make sure availableamount corresponds to parent available credit (set from backend properly).
Make sure balanceLimit corresponds to child’s balance limit separately.
Ensure your HTML form or wherever the data binding happens allows user to enter correct new credit limit for child.
Your backend must receive both fields (creditLimit and creditLimitDelta) and apply the following logic:
Update child’s credit limit with creditLimit.
Adjust parent’s available credit limit by subtracting/adding creditLimitDelta.
Do not replace creditLimit with delta in the front end; delta is just an additional field.
If you want, I can help review your backend code for handling this properly as well!
Save both and return success.
Example code outline
java
@Override
public String UpdateTransactiondateCreditLimit(CreditCardLimitPopup creditTransactionLimit) {
logger.info("UpdateTransactiondateCreditLimit called with: {}", creditTransactionLimit);
// Fetch existing child-parent credit limit record
List<CreditCardLimit> transactionDetails = creditLimitRepo.fetchCreditParentAndChildCredirDetails(
creditTransactionLimit.getParentCode(),
creditTransactionLimit.getChildcode());
if (transactionDetails.isEmpty()) {
return null; // or handle not found
}
CreditCardLimit childTransaction = transactionDetails.get(0);
// Fetch Parent record separately
Optional<CreditCardLimit> parentOptional = creditLimitRepo.findByImdCode(creditTransactionLimit.getParentCode());
if (!parentOptional.isPresent()) {
throw new RuntimeException("Parent credit limit record not found");
}
CreditCardLimit parentTransaction = parentOptional.get();
// Calculate new available parent credit limit after allocation
double delta = creditTransactionLimit.getCreditLimitDelta() != null ? creditTransactionLimit.getCreditLimitDelta() : 0.0;
double parentAvailableBefore = parentTransaction.getAvailableCreditLimit(); // You'll need to add this field or similar
double parentAvailableAfter = parentAvailableBefore - delta;
if (parentAvailableAfter < 0) {
// Reject update - Parent does not have enough available limit
throw new RuntimeException("Parent available credit limit is insufficient");
}
// Update Parent available credit limit
parentTransaction.setAvailableCreditLimit(parentAvailableAfter);
creditLimitRepo.save(parentTransaction);
// Update Child's credit limit
childTransaction.setCredit_Limit(creditTransactionLimit.getCreditLimit());
childTransaction.setImd_paraent_code(creditTransactionLimit.getParentCode());
childTransaction.setImd_child_code(creditTransactionLimit.getChildcode());
childTransaction.setACD_number(creditTransactionLimit.getAcdNumber());
String tran_id = creditLimitRepo.save(childTransaction).getACD_number();
return tran_id;
}
Important notes:
You need to have a field like availableCreditLimit or similar for parent credit record in your DB/entity to track current available credit.
Handle transaction atomically to avoid race conditions.
You might want to add exception handling to return meaningful error messages when parent's available limit is insufficient.
Adjust repository and entity classes accordingly if availableCreditLimit is missing.
If you don't currently track parent's available credit in DB, you will need to add that.
Summary
Frontend sends both new child credit limit and delta.
Backend updates child credit limit and adjusts parent's available credit by subtracting delta.
Backend validates parent has enough available limit; rejects update if not.
Both parent and child records are updated and saved.
If you want help with repository methods or entity classes or any additional backend wiring, just ask!
How to show the updated parent available limit in the UI?
Since availableamount lives only in your frontend component, after reducing it locally (see above), you simply bind this variable into your template wherever you display parent available limit, e.g.:
html
<p>Parent Available Limit: {{ availableamount | currency:'INR':'symbol':'1.2-2' }}</p>
When you decrease it in onSubmit(), Angular binding updates the display automatically.
Summary
Parent available limit check and update happens solely in frontend in your current setup.
On successful child limit update, manually reduce the availableamount variable by the allocated delta.
Parent availability is never sent or updated on backend; only checked and maintained on frontend.
Make sure to initialize availableamount from your API data when loading the component.
If you want, I can help you write a more detailed Angular example with event emitters or state management to keep this consistent!
Let me know if you want that or have any questions!