i am able to see the filter but data is not coming also another table Child Code Name ACD Number Allocate Limit(INR) Used Limit(INR) Balance Limit(INR) Credit Days Edit Action View Transaction is not able to see
const activeToken = localStorage.getItem(this.tokenKey);
// Step 1: Check if token is provided in URL
if (!token) {
alert('Token is missing or invalid.');
this.redirectToError();
return;
}
// Check if the token is already active in another tab
if (activeToken && activeToken === token) {
alert('This token is already in use in another tab.');
this.redirectToError();
return;
}
// Mark the token as active in localStorage
localStorage.setItem(this.tokenKey, token);
console.log('Token activated in this tab.');
// Step 2: Validate token with backend before proceeding
this.validateTokenWithBackend(token);
// Use decryptText utility function to decrypt the response
decryptText(encryptedData, customKey, customIV)
.then((data) => {
try {
const {
childCode = null,
parentCode = null,
userTypeId = null,
userId = null,
} = data;
// Store necessary data in localStorage and sessionStorage
localStorage.setItem('UserId', userId);
localStorage.setItem('userTypeId', userTypeId);
sessionStorage.setItem('isTokenVerified', 'true'); // Mark token as verified
// Handle redirection based on userTypeId
if (userTypeId == 6) {
localStorage.setItem('childCode', childCode);
this.redirectTo(
'https://secure.sbigeneral.in/PSH/creditchild/'
);
//this.redirectTo('https://ansappsuat.sbigen.in/PSH/creditchild/');
//this.redirectTo('http://localhost:4200/creditchild/');
} else if (userTypeId == 2) {
localStorage.setItem('parentCode', parentCode);
this.loadData(parentCode);
} else {
console.warn(
'Invalid response: Both parentCode and childCode are missing.'
);
this.redirectToError();
}
} catch (error) {
console.error('Error parsing decrypted data:', error);
this.redirectToError();
}
})
.catch((error) => {
console.error('Error decrypting data:', error);
this.redirectToError();
});
} else {
console.error('No valid data received from backend.');
this.redirectToError();
}
},
error: (error) => {
console.error('Error fetching token details from backend:', error);
if (error.status === 403) {
alert('Access denied: This token has already been used.');
} else {
alert('An error occurred while verifying the token.');
}
this.redirectToError(); // Redirect to error on any backend error
},
});
}
// Load data only after token is verified and a valid parent code is received
private loadData(parentCode: string) {
this.parentCode1 = parentCode;
this.FetchParentCardDetails(this.parentCode1);
this.FetchCreditCardPage(this.parentCode1);
this.FetchCreditCardPage1(this.parentCode1);
// this.FetchCreditCardPage2(this.parentCode1);
}
private redirectTo(url: string) {
window.location.href = url; // Redirect to the specified URL
}
// Encrypting the IMD code
encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
.then((encryptedResult) => {
if (encryptedResult) {
this.Credit.FetchCreditCardDetails(
encryptedResult.encryptedText,
encryptedResult.key,
encryptedResult.base64iv
).subscribe({
next: (data) => {
if (!data || data.length === 0) {
// Data is empty or not defined
this.emptyDataMessage =
'Policy Details Not Found for the Given Agreement Code.';
this.isLoading = false;
this.isDataEmptyMessage = true;
} else {
// Data is not empty
this.report = data;
// this.refreshDataTable();
//this.isLoading = false;
this.isDataEmptyMessage = false;
console.log('Credit Card Limit:', this.report);
// Additional logic if needed
}
},
error: (error) => {
console.error('Error fetching child page:', error);
if (error.status === 404) {
alert('Session has been Expired .');
} else {
alert('An error occurred while verifying the token.');
}
this.redirectToError();
// Handle the error as needed
this.isLoading = false;
// Optionally display an error message to the user
},
});
} else {
console.error('Encryption failed, no encrypted result returned.');
this.isLoading = false; // Ensure loading is stopped if encryption fails
}
})
.catch((error) => {
console.error('Encryption error:', error);
this.isLoading = false;
if (error.status === 403) {
alert('Access denied: This token has already been used.');
} else {
alert('An error occurred while verifying the token.');
}
this.redirectToError(); // Ensure loading is stopped if there's an encryption error
});
// Initialize these arrays somewhere in your component to store checked dates
checkedTranDates: Date[] = [];
checkedInsuranceDates: Date[] = [];
onCheckboxClick(transaction: any, event: any) {
const premiumvalue = Number(transaction.premium);
const insurencedate = new Date(transaction.insurenceDate);
const tranDate = new Date(transaction.tran_date);
code
if (event.target.checked) {
// Add the selected transaction's premium to the total sum
this.selectedPremiumSum += premiumvalue;
// Store the acd_number of the current selected transaction
this.lastSelectedAcdNumber = transaction.acd_number;
this.parentcode = transaction.imd_parent_code;
this.agrementcode = transaction.imd_child_code;
// Add tranDate and insurencedate to the checked lists
this.checkedTranDates.push(tranDate);
this.checkedInsuranceDates.push(insurencedate);
// Add policy number to the list (duplicates are allowed)
this.policynumbers.push(transaction.policyNumber);
// Add the premium to the selected amounts list (duplicates are allowed)
this.selectedAmount.push(transaction.premium);
} else {
// Subtract the transaction's premium from the total sum
this.selectedPremiumSum -= premiumvalue;
// Remove tranDate and insurencedate from the checked lists
this.checkedTranDates = this.checkedTranDates.filter(
(date) => date.getTime() !== tranDate.getTime()
);
this.checkedInsuranceDates = this.checkedInsuranceDates.filter(
(date) => date.getTime() !== insurencedate.getTime()
);
// Remove the policy number from the list (only the first match)
const policyIndex = this.policynumbers.indexOf(transaction.policyNumber);
if (policyIndex > -1) {
this.policynumbers.splice(policyIndex, 1);
}
// Remove the premium from the selected amounts list (only the first match)
const premiumIndex = this.selectedAmount.indexOf(transaction.premium);
if (premiumIndex > -1) {
this.selectedAmount.splice(premiumIndex, 1);
}
}
// Determine the oldest tranDate and insurencedate among checked policies
const oldestTranDate =
this.checkedTranDates.length > 0
? new Date(
Math.min(...this.checkedTranDates.map((date) => date.getTime()))
)
: null;
const oldestInsuranceDate =
this.checkedInsuranceDates.length > 0
? new Date(
Math.min(
...this.checkedInsuranceDates.map((date) => date.getTime())
)
)
: null;
const formattedOldestTranDate = oldestTranDate
? this.formatDate(oldestTranDate)
: 'N/A';
const formattedOldestInsuranceDate = oldestInsuranceDate
? this.formatDate(oldestInsuranceDate)
: 'N/A';
console.log('Selected Total Premium:', this.selectedPremiumSum);
console.log('Last Selected ACD Number:', this.lastSelectedAcdNumber);
console.log('Oldest Transaction Date (Checked):', formattedOldestTranDate);
console.log(
'Oldest Insurance Date (Checked):',
formattedOldestInsuranceDate
);
// Save oldest dates in localStorage
localStorage.setItem('oldestTranDate', formattedOldestTranDate);
localStorage.setItem('oldestInsuranceDate', formattedOldestInsuranceDate);
}
formatDate(date: Date): string {
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-indexed
const year = date.getFullYear();
return ${day}-${month}-${year};
}
isReadOnly = false;
openPaymentPopup() {
if (this.selectedPremiumSum > 0) {
this.isReadOnly = true; // Make fields read-only
this.ispaymentPopupOpen = true; // Open the modal
} else {
console.log('No transactions selected for payment');
}
}
navigateToTransaction(item: any): void {
this.sharedService.setCodes(item.imd_paraent_code, item.imd_child_code);
this.routers.navigate(['/transactionAcdNumber']);
}
}
Sure! Below, I've updated your template code to include sorting, filtering, and pagination functionality specifically for the transaction details table (reporttransaction). The code leverages the Angular Material Table with a MatPaginator and MatSort, as well as an input for filtering.
Make sure to also update the corresponding TypeScript code in your component. Here are the key updates you need to make:
typescript
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
@Component({
selector: 'app-credit-card-limit',
templateUrl: './credit-card-limit.component.html',
styleUrls: ['./credit-card-limit.component.css'],
})
export class CreditCardLimitComponent implements OnInit, AfterViewInit {
dataSource = new MatTableDataSource<any>();
displayedColumns: string[] = ['select', 'policyNumber', 'customerName', 'quoteNumber', 'issuanceDate', 'riskStartDate', 'premiumAmount', 'elapsedDays', 'acdNumber', 'replenishStatus', 'replenishDate', 'vehicleNo'];
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
// Your existing code...
ngOnInit(): void {
// Existing initialization...
}
ngAfterViewInit() {
// Existing code after view init...
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
// Populate data source for the transactions table
this.dataSource.data = this.reporttransaction; // Assuming you are fetching this from the service
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
// Your existing methods...
}
Explanation
Table Structure: The code structure of the transaction details table has mat-table from Angular Material, which adds sorting and pagination features.
Filter: A text input is added above the table for filtering transaction data based on the policy number.
Data Source and Column Definitions: The data source for the transactions table is controlled with MatTableDataSource, and the column definitions are set in the component's TypeScript code.
Pagination: A paginator is attached to the table to enable easy navigation between pages.
Styling: Make sure to style the input fields and buttons using Angular Material styles or your own custom styles.
You should ensure that Angular Material modules for MatTable, MatPaginator, MatSort, and MatInput (for the filter input) are imported in your module file. Let me know if you need any further modifications or help!
To ensure that both your transaction details table and the credit limit allocation table are displayed correctly and functionally with data, it's essential to ensure that:
Data Source Initialization: Both tables should have data sources properly initialized in your TypeScript component.
Conditions for Displaying Tables: Ensure the logic that decides whether to show the transaction details table or the credit limit allocation table is functioning as expected.
Correct Table Setup: Verify that you have properly defined the template HTML structure for both tables.
Step 1: Ensure Initialization of Data Source
Here is how you might adjust your TypeScript code to ensure that both data sources (dataSource for transactions and report for the credit limit allocation) are adequately populated from the backend:
TypeScript Component
typescript
import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
@Component({
selector: 'app-credit-card-limit',
templateUrl: './credit-card-limit.component.html',
styleUrls: ['./credit-card-limit.component.css'],
})
export class CreditCardLimitComponent implements OnInit, AfterViewInit {
dataSource = new MatTableDataSource<any>();
report: any[] = []; // For Parent Card Details
reporttransaction: any[] = []; // For Transaction Details
displayedColumns: string[] = ['select', 'policyNumber', 'customerName', 'quoteNumber', 'issuanceDate', 'riskStartDate', 'premiumAmount', 'elapsedDays', 'acdNumber', 'replenishStatus', 'replenishDate', 'vehicleNo'];
displayedColumnsParent: string[] = ['childCode', 'name', 'acdNumber', 'allocateLimit', 'usedLimit', 'balanceLimit', 'creditDays', 'editAction', 'viewTransaction'];
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
// For the filter in transactions table
filterValue: string = '';
ngOnInit(): void {
// Your initialization logic
this.loadInitialData();
}
ngAfterViewInit() {
// Setting up the paginator and sort after view initialization
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
loadInitialData() {
// Load Parent Card Details and Transaction Details
this.FetchParentCardDetails(this.parentCode1); // Assume parentCode1 is already set correctly
this.FetchTransactionDetails(this.imdCode); // Fetch transaction details from the correct source
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
// Other existing methods...
FetchTransactionDetails(imdCode: string) {
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]);
// Encrypt and fetch transaction details...
encryptText({ imdCode: imdCode.trim() }, customKey, customIV)
.then(encryptedResult => {
// Call your service to fetch transaction details
this.Transaction.FetchCreditCardDetailss(
encryptedResult.encryptedText,
encryptedResult.key,
encryptedResult.base64iv
).subscribe(data => {
this.reporttransaction = data;
this.dataSource.data = this.reporttransaction; // Bind data to MatTableDataSource
},
error => {
console.error('Error fetching transaction details:', error);
});
})
.catch(error => {
console.error('Encryption error:', error);
});
}
}
Step 2: Update the HTML Template
Make sure your HTML template is set up correctly to display both tables.
Updated HTML Template
Here's how you might adjust your HTML:
html
Key Adjustments Made
Data Sources: Ensure that the dataSource for the transaction table is initialized from the fetched data in FetchTransactionDetails.
HTML Structure: Ensure both the transaction details and credit limit allocation tables are structured correctly.
Display Conditions: Ensure your logic for toggling showTransactionDetails or showing the credit allocation table is correct.
Fetch Data: Ensure you are correctly invoking the function to fetch the data from your backend service that handles transactions.
Debugging Tips
Use console.log statements to verify that data is being fetched correctly and being assigned to the report and reporttransaction variables.
Check the console for errors during the execution of the component, especially during data fetch operations.
Confirm the backend API being called returns the expected data format.
Ensure you have defined appropriate classes/modules for Angular Material in your application module, especially for MatTableModule, MatPaginatorModule, and MatSortModule. If you're missing the imports, your tables won't function correctly.
Let me know if this helps or if you require further clarification!