import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TranslateModule } from '@ngx-translate/core'; import { ExcelExportService } from '../shared/services/excel-export.service'; import { TRANSACTION_LOGS_FILE_NAME } from '../utils/app.constants'; import { pageSizeOptions } from '../utils/app.constants'; import { NgSelectModule } from '@ng-select/ng-select'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { TableFilterPipe } from '../shared/pipes/table-filter.pipe'; import { TransactionLog } from "../models/user"; import { URIKey } from '../utils/uri-enums'; import { HttpParams } from '@angular/common/http'; import { HttpURIService } from '../app.http.uri.service'; import { formatDate } from '@angular/common'; @Component({ selector: 'app-transaction-logs', templateUrl: './transaction-logs.component.html', styleUrls: ['./transaction-logs.component.scss'], imports: [CommonModule, TranslateModule, NgSelectModule, FormsModule, ReactiveFormsModule, TableFilterPipe] }) export class TransactionLogsComponent implements OnInit { currentPage: number = 1; totalCount: number = 0; renewalDataExpanded: boolean = true; pageSizeOptions = pageSizeOptions; itemsPerPage: number = 10; transactionLog: TransactionLog[] = []; isLoading = false; pagedItems: any[] = []; errorMessage: string = ''; searchText: string = ''; allItems: TransactionLog[] = []; transactionDataExpanded: boolean = true; // Date range properties fromDate: string = ''; toDate: string = ''; maxDate: string = ''; showDateFilters: boolean = false; constructor( private excelExportService: ExcelExportService, private httpService: HttpURIService, ) {} ngOnInit(): void { // Set max date to today this.maxDate = formatDate(new Date(), 'yyyy-MM-dd', 'en-US'); // Optionally set default date range (last 30 days) const today = new Date(); const lastMonth = new Date(); lastMonth.setDate(today.getDate() - 30); this.fromDate = formatDate(lastMonth, 'yyyy-MM-dd', 'en-US'); this.toDate = formatDate(today, 'yyyy-MM-dd', 'en-US'); this.loadTransactionLogs(); } loadTransactionLogs(): void { this.isLoading = true; this.errorMessage = ''; // Build query parameters let params = new HttpParams(); // Add pagination parameters params = params.set('page', this.currentPage.toString()); params = params.set('limit', this.itemsPerPage.toString()); // Add date filters if provided if (this.fromDate) { params = params.set('fromDate', this.fromDate); } if (this.toDate) { params = params.set('toDate', this.toDate); } // Add search filter if provided if (this.searchText && this.searchText.trim() !== '') { params = params.set('search', this.searchText.trim()); } this.httpService .requestGET(URIKey.TRANSACTION_LOGS, params) .subscribe({ next: (res) => { const logs = Array.isArray(res) ? res : res?.data; this.transactionLog = logs ?? []; this.allItems = [...this.transactionLog]; // Get total count from response if (res?.total !== undefined) { this.totalCount = res.total; } else if (res?.pagination?.total !== undefined) { this.totalCount = res.pagination.total; } else if (res?.meta?.total !== undefined) { this.totalCount = res.meta.total; } else { this.totalCount = this.transactionLog.length; } this.updatePagedItems(); this.isLoading = false; }, error: (err) => { console.error('Error fetching transaction logs:', err); this.errorMessage = err.message || 'Failed to load transaction logs. Please try again.'; this.transactionLog = []; this.allItems = []; this.totalCount = 0; this.pagedItems = []; this.isLoading = false; }, complete: () => { this.isLoading = false; } }); } // Date filter change handler onDateFilterChange(): void { // Validate date range if (this.fromDate && this.toDate) { const from = new Date(this.fromDate); const to = new Date(this.toDate); if (from > to) { this.errorMessage = 'From date cannot be after To date'; return; } } // Reset to first page and reload this.currentPage = 1; this.loadTransactionLogs(); } // Clear date filters clearDateFilters(): void { this.fromDate = ''; this.toDate = ''; this.currentPage = 1; this.loadTransactionLogs(); } // Toggle date filter visibility toggleDateFilters(): void { this.showDateFilters = !this.showDateFilters; } // Apply default date range (Last 7 days) applyLast7Days(): void { const today = new Date(); const lastWeek = new Date(); lastWeek.setDate(today.getDate() - 7); this.fromDate = formatDate(lastWeek, 'yyyy-MM-dd', 'en-US'); this.toDate = formatDate(today, 'yyyy-MM-dd', 'en-US'); this.onDateFilterChange(); } // Apply default date range (Last 30 days) applyLast30Days(): void { const today = new Date(); const lastMonth = new Date(); lastMonth.setDate(today.getDate() - 30); this.fromDate = formatDate(lastMonth, 'yyyy-MM-dd', 'en-US'); this.toDate = formatDate(today, 'yyyy-MM-dd', 'en-US'); this.onDateFilterChange(); } // Apply default date range (This month) applyThisMonth(): void { const today = new Date(); const firstDay = new Date(today.getFullYear(), today.getMonth(), 1); this.fromDate = formatDate(firstDay, 'yyyy-MM-dd', 'en-US'); this.toDate = formatDate(today, 'yyyy-MM-dd', 'en-US'); this.onDateFilterChange(); } toggleTableCard(): void { this.transactionDataExpanded = !this.transactionDataExpanded; } itemsPerPageChanged(): void { this.currentPage = 1; this.loadTransactionLogs(); } onSearch(value: string): void { this.searchText = value; this.currentPage = 1; // Debounce search to avoid too many API calls clearTimeout((this as any).searchTimeout); (this as any).searchTimeout = setTimeout(() => { this.loadTransactionLogs(); }, 300); } totalPages(): number { return Math.ceil(this.totalCount / this.itemsPerPage); } previousPage(): void { if (this.currentPage > 1) { this.currentPage--; this.loadTransactionLogs(); } } updatePagedItems(): void { // For client-side display with table filter pipe const startIndex = (this.currentPage - 1) * this.itemsPerPage; const endIndex = startIndex + this.itemsPerPage; // If using server-side pagination, use transactionLog directly // If using client-side filtering with tableFilter pipe, this might not be needed this.pagedItems = this.allItems.slice(startIndex, endIndex); } nextPage(): void { if (this.currentPage < this.totalPages()) { this.currentPage++; this.loadTransactionLogs(); } } exportDataInExcel(): void { // Export filtered data const dataToExport = this.allItems.length > 0 ? this.allItems : this.transactionLog; this.excelExportService.exportExcel(dataToExport, TRANSACTION_LOGS_FILE_NAME); } // Get filtered items for display (used in template) get filteredItems(): TransactionLog[] { return this.allItems; } }