station locator: station page

This commit is contained in:
armiejean 2025-05-19 18:03:37 +08:00
parent b350d6ad4a
commit de06c08832
9 changed files with 477 additions and 533 deletions

View File

@ -16,7 +16,7 @@ class ReportsController extends Controller
$this->apiBaseUrl = env('EXTERNAL_API_URL', 'http://localhost:8081/api/'); $this->apiBaseUrl = env('EXTERNAL_API_URL', 'http://localhost:8081/api/');
} }
private function makeApiRequest($endpoint, $params, $isDownload = false) private function makeApiRequest($endpoint, $params, $isDownload = false)
{ {
try { try {
$user = Session::get('user'); $user = Session::get('user');
@ -59,7 +59,7 @@ class ReportsController extends Controller
} }
if ($isDownload) { if ($isDownload) {
return $response; // Return raw response for file download return $response;
} }
return $response->json(); return $response->json();
@ -77,6 +77,7 @@ class ReportsController extends Controller
return null; return null;
} }
} }
public function mobileUsage(Request $request) public function mobileUsage(Request $request)
{ {
$params = [ $params = [
@ -91,7 +92,7 @@ class ReportsController extends Controller
$data = $this->makeApiRequest('cms/reportMobileUsage', $params); $data = $this->makeApiRequest('cms/reportMobileUsage', $params);
if (is_a($data, '\Illuminate\Http\RedirectResponse')) { if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
return $data; // Redirect to login if unauthorized return $data;
} }
$mobileUsageData = []; $mobileUsageData = [];
@ -124,6 +125,33 @@ class ReportsController extends Controller
return view('pages.reports.mobile-usage-report', compact('mobileUsageData', 'currentPage', 'lastPage', 'total', 'errorMessage')); return view('pages.reports.mobile-usage-report', compact('mobileUsageData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
} }
public function exportMobileUsage(Request $request)
{
$params = [
'date_start' => $request->input('date_start'),
'date_end' => $request->input('date_end'),
'_search' => $request->input('_search'),
'sorting' => $request->input('sort', 'date|desc'),
];
$response = $this->makeApiRequest('cms/reportMobileUsageExport', $params, true);
if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
return $response;
}
if (!$response) {
Log::warning("Failed to export mobile usage data", ['params' => $params]);
return redirect()->back()->with('error', 'Failed to export CSV.');
}
$filename = "reports_mobile_usage" . date("mdY") . ".csv";
return response($response->body(), 200)
->header('Content-Type', 'text/csv')
->header('Content-Disposition', "attachment; filename=\"$filename\"");
}
public function registration(Request $request) public function registration(Request $request)
{ {
$params = [ $params = [
@ -170,53 +198,108 @@ class ReportsController extends Controller
return view('pages.reports.registration-report', compact('registrationData', 'currentPage', 'lastPage', 'total', 'errorMessage')); return view('pages.reports.registration-report', compact('registrationData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
} }
public function stationRating(Request $request) public function exportRegistration(Request $request)
{ {
$params = [ $params = [
'page' => $request->input('page', 1), 'date_start' => $request->input('date_start'),
'page_size' => 5, 'date_end' => $request->input('date_end'),
'date_start' => $request->input('date_start'), '_search' => $request->input('_search'),
'date_end' => $request->input('date_end'), 'sorting' => $request->input('sort', 'date|desc'),
'sorting' => $request->input('sort', 'date|desc'), ];
'_search' => $request->input('_search'),
];
$data = $this->makeApiRequest('cms/reportStationRatings', $params); $response = $this->makeApiRequest('cms/reportRegistrationExport', $params, true);
if (is_a($data, '\Illuminate\Http\RedirectResponse')) { if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
return $data; return $response;
}
if (!$response) {
Log::warning("Failed to export registration data", ['params' => $params]);
return redirect()->back()->with('error', 'Failed to export CSV.');
}
$filename = "registration" . date("mdY") . ".csv";
return response($response->body(), 200)
->header('Content-Type', 'text/csv')
->header('Content-Disposition', "attachment; filename=\"$filename\"");
} }
$stationRatingData = []; public function stationRating(Request $request)
$currentPage = $params['page']; {
$lastPage = 1; $params = [
$total = 0; 'page' => $request->input('page', 1),
$errorMessage = null; 'page_size' => 5,
'date_start' => $request->input('date_start'),
'date_end' => $request->input('date_end'),
'sorting' => $request->input('sort', 'date|desc'),
'_search' => $request->input('_search'),
];
if ($data && isset($data['data'])) { $data = $this->makeApiRequest('cms/reportStationRatings', $params);
$stationRatingData = array_map(function ($item) {
return [ if (is_a($data, '\Illuminate\Http\RedirectResponse')) {
'id' => $item['id'] ?? uniqid(), return $data;
'transactionDateTime' => $item['date'], }
'cardNumber' => $item['card_number'],
'salesInvoice' => $item['invoice'], $stationRatingData = [];
'station' => $item['station'], $currentPage = $params['page'];
'ratings' => $item['rate'], $lastPage = 1;
]; $total = 0;
}, $data['data']); $errorMessage = null;
$currentPage = $data['meta']['current_page'] ?? 1;
$lastPage = $data['meta']['last_page'] ?? 1; if ($data && isset($data['data'])) {
$total = $data['meta']['total'] ?? count($stationRatingData); $stationRatingData = array_map(function ($item) {
} elseif ($data && isset($data['message'])) { return [
Log::info("API returned message for stationRating", ['message' => $data['message']]); 'id' => $item['id'] ?? uniqid(),
$errorMessage = $data['message']; 'transactionDateTime' => $item['date'],
} else { 'cardNumber' => $item['card_number'],
Log::warning("No data returned or invalid response structure for stationRating", ['data' => $data]); 'salesInvoice' => $item['invoice'],
$errorMessage = 'Failed to fetch station rating data.'; 'station' => $item['station'],
'ratings' => $item['rate'],
];
}, $data['data']);
$currentPage = $data['meta']['current_page'] ?? 1;
$lastPage = $data['meta']['last_page'] ?? 1;
$total = $data['meta']['total'] ?? count($stationRatingData);
} elseif ($data && isset($data['message'])) {
Log::info("API returned message for stationRating", ['message' => $data['message']]);
$errorMessage = $data['message'];
} else {
Log::warning("No data returned or invalid response structure for stationRating", ['data' => $data]);
$errorMessage = 'Failed to fetch station rating data.';
}
return view('pages.reports.station-rating-report', compact('stationRatingData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
}
public function exportStationRating(Request $request)
{
$params = [
'date_start' => $request->input('date_start'),
'date_end' => $request->input('date_end'),
'_search' => $request->input('_search'),
'sorting' => $request->input('sort', 'date|desc'),
];
$response = $this->makeApiRequest('cms/reportStationRatingsExport', $params, true);
if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
return $response;
}
if (!$response) {
Log::warning("Failed to export station rating data", ['params' => $params]);
return redirect()->back()->with('error', 'Failed to export CSV.');
}
$filename = "reports_station_rating" . date("mdY") . ".csv";
return response($response->body(), 200)
->header('Content-Type', 'text/csv')
->header('Content-Disposition', "attachment; filename=\"$filename\"");
} }
return view('pages.reports.station-rating-report', compact('stationRatingData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
}
public function topUp(Request $request) public function topUp(Request $request)
{ {
$params = [ $params = [
@ -263,27 +346,27 @@ class ReportsController extends Controller
return view('pages.reports.top-up-usage-report', compact('topUpData', 'currentPage', 'lastPage', 'total', 'errorMessage')); return view('pages.reports.top-up-usage-report', compact('topUpData', 'currentPage', 'lastPage', 'total', 'errorMessage'));
} }
public function exportStationRating(Request $request) public function exportTopUp(Request $request)
{ {
$params = [ $params = [
'date_start' => $request->input('date_start'), 'date_start' => $request->input('date_start'),
'date_end' => $request->input('date_end'), 'date_end' => $request->input('date_end'),
'_search' => $request->input('_search'), '_search' => $request->input('_search'),
'sorting' => $request->input('sort', 'date|desc'), 'sorting' => $request->input('sort', 'transaction_date_time|desc'),
]; ];
$response = $this->makeApiRequest('cms/reportStationRatingsExport', $params, true); $response = $this->makeApiRequest('cms/reportTopUpExport', $params, true);
if (is_a($response, '\Illuminate\Http\RedirectResponse')) { if (is_a($response, '\Illuminate\Http\RedirectResponse')) {
return $response; return $response;
} }
if (!$response) { if (!$response) {
Log::warning("Failed to export station rating data", ['params' => $params]); Log::warning("Failed to export top-up data", ['params' => $params]);
return redirect()->back()->with('error', 'Failed to export CSV.'); return redirect()->back()->with('error', 'Failed to export CSV.');
} }
$filename = "reports_station_rating" . date("mdY") . ".csv"; $filename = "reports_top_up" . date("mdY") . ".csv";
return response($response->body(), 200) return response($response->body(), 200)
->header('Content-Type', 'text/csv') ->header('Content-Type', 'text/csv')

View File

@ -4,195 +4,141 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
class StationController extends Controller class StationController extends Controller
{ {
protected $apiBaseUrl = 'http://192.168.100.6:8081/api/'; protected $apiBaseUrl = 'http://192.168.100.6:8081/api/cms';
public function index(Request $request) public function index(Request $request)
{ {
$params = [ try {
'page' => $request->input('page', 1), $user = Session::get('user');
'page_size' => 5, $accessToken = $user['access_token'] ?? null;
'_search' => $request->input('_search'),
'sort' => $request->input('sort', 'code|asc'),
];
$response = Http::get($this->apiBaseUrl . 'cms/getStations', $params); if (!$accessToken) {
$data = $response->json(); Log::info('No access token found, redirecting to login from stations');
return redirect()->route('login')->with('error', 'Please log in to view stations.');
}
\Log::info('Stations API Response:', ['status' => $response->status(), 'data' => $data]); $page = $request->input('page', 1);
$pageSize = 5;
$search = $request->input('_search', null);
$sort = $request->input('sort', 'station_code|asc');
$stations = []; Log::info('Initiating API request to fetch stations', [
$currentPage = $params['page']; 'url' => "{$this->apiBaseUrl}/getStations",
$lastPage = 1; 'params' => [
$total = 0; 'page' => $page,
'page_size' => $pageSize,
'_search' => $search,
'sort' => $sort,
],
]);
if ($response->successful() && isset($data['data'])) { $response = Http::withHeaders([
$stations = array_map(function ($item) { 'Accept' => 'application/json',
return [ 'Authorization' => 'Bearer ' . $accessToken,
'id' => $item['station_uuid'], ])->timeout(30)->get("{$this->apiBaseUrl}/getStations", [
'station_code' => $item['code'], 'page' => $page,
'station_name' => $item['description'], 'page_size' => $pageSize,
'branch_name' => 'N/A', '_search' => $search,
'date_created' => 'N/A', 'sort' => $sort,
'created_by' => 'N/A', ]);
'modified_by' => 'N/A',
'date_modified' => 'N/A',
];
}, $data['data']);
$total = count($data['data']); $json = $response->json();
$lastPage = ceil($total / $params['page_size']); $rawResponse = $response->body();
$currentPage = min($currentPage, $lastPage);
if ($params['_search']) { Log::info('API response received for stations', [
$searchTerm = strtolower($params['_search']); 'status' => $response->status(),
$stations = array_filter($stations, function ($station) use ($searchTerm) { 'headers' => $response->headers(),
return str_contains(strtolower($station['station_code']), $searchTerm) || 'data' => $json,
str_contains(strtolower($station['station_name']), $searchTerm) || 'raw_response' => $rawResponse,
str_contains(strtolower($station['branch_name']), $searchTerm); 'reason' => $response->reason(),
}); ]);
$stations = array_values($stations);
$total = count($stations); if ($response->status() === 401 || $response->status() === 403) {
$lastPage = ceil($total / $params['page_size']); Log::warning('Unauthorized or Forbidden API response for stations', ['response' => $json]);
return redirect()->route('login')->with('error', 'Your session has expired. Please log in again.');
}
if ($response->successful() && isset($json['code']) && $json['code'] == 200 && isset($json['data']) && is_array($json['data'])) {
$stations = array_map(function ($station) {
return [
'id' => $station['station_uuid'] ?? '',
'station_code' => $station['code'] ?? '',
'station_name' => $station['description'] ?? '',
'branch_name' => $station['branch_name'] ?? '',
'date_created' => $station['date_created'] ?? '',
'created_by' => $station['created_by'] ?? '',
'modified_by' => $station['modified_by'] ?? '',
'date_modified' => $station['date_modified'] ?? '',
];
}, $json['data']);
// Use meta for pagination if provided, else calculate locally
$total = $json['meta']['total'] ?? count($stations);
$lastPage = $json['meta']['last_page'] ?? ceil($total / $pageSize);
// Apply search filter locally if needed
if ($search) {
$searchTerm = strtolower($search);
$stations = array_filter($stations, function ($station) use ($searchTerm) {
return str_contains(strtolower($station['station_code'] ?? ''), $searchTerm) ||
str_contains(strtolower($station['station_name'] ?? ''), $searchTerm);
});
$stations = array_values($stations);
$total = count($stations);
$lastPage = ceil($total / $pageSize);
}
// Apply sorting locally
if ($sort) {
[$sortField, $sortDir] = explode('|', $sort);
usort($stations, function ($a, $b) use ($sortField, $sortDir) {
$aValue = $a[$sortField] ?? '';
$bValue = $b[$sortField] ?? '';
return $sortDir === 'asc' ? strcmp($aValue, $bValue) : strcmp($bValue, $aValue);
});
}
// Paginate locally
$start = ($page - 1) * $pageSize;
$stations = array_slice($stations, $start, $pageSize);
} else {
Log::warning('No station data found or invalid API response', ['response' => $json]);
$stations = [];
$total = 0;
$lastPage = 1;
}
Log::info('Processed stations data', [
'stations_count' => count($stations),
'total' => $total,
'currentPage' => $page,
'lastPage' => $lastPage,
'stations' => $stations,
]);
return view('pages.station locator.stations', [
'stations' => $stations,
'currentPage' => $page,
'lastPage' => $lastPage,
'total' => $total,
'search' => $search,
]);
} catch (\Exception $e) {
Log::error('Error fetching stations: ' . $e->getMessage(), [
'trace' => $e->getTraceAsString(),
]);
return view('pages.station locator.stations', [
'stations' => [],
'currentPage' => 1,
'lastPage' => 1,
'total' => 0,
'search' => $search,
])->with('error', 'Failed to fetch stations: ' . $e->getMessage());
} }
if ($params['sort']) {
[$sortField, $sortDir] = explode('|', $params['sort']);
usort($stations, function ($a, $b) use ($sortField, $sortDir) {
$aValue = $a[$sortField] ?? '';
$bValue = $b[$sortField] ?? '';
return $sortDir === 'asc' ? strcmp($aValue, $bValue) : strcmp($bValue, $aValue);
});
}
$start = ($currentPage - 1) * $params['page_size'];
$stations = array_slice($stations, $start, $params['page_size']);
} }
return view('pages.station locator.stations', compact('stations', 'currentPage', 'lastPage', 'total'));
}
// public function create()
// {
// return view('pages.add-station');
// }
// public function store(Request $request)
// {
// $request->validate([
// 'station_code' => 'required|string|max:50|unique:stations,station_code',
// 'station_name' => 'required|string|max:255',
// 'branch_name' => 'required|string|max:255',
// ]);
// // Mock API call to store station
// $response = Http::post($this->apiBaseUrl . 'cms/stations/store', [
// 'code' => $request->station_code,
// 'description' => $request->station_name,
// 'branch_name' => $request->branch_name,
// 'is_viewable' => 1,
// 'is_active' => 1,
// ]);
// if ($response->successful()) {
// return redirect()->route('station-management')->with('success', 'Station added successfully');
// }
// return back()->withErrors(['error' => 'Failed to add station']);
// }
// public function show($id)
// {
// $response = Http::get($this->apiBaseUrl . 'cms/getStations');
// $data = $response->json();
// $station = null;
// if ($response->successful() && isset($data['data'])) {
// $station = collect($data['data'])->firstWhere('station_uuid', $id);
// if ($station) {
// $station = [
// 'id' => $station['station_uuid'],
// 'station_code' => $station['code'],
// 'station_name' => $station['description'],
// 'branch_name' => 'N/A',
// 'date_created' => 'N/A',
// 'created_by' => 'N/A',
// 'modified_by' => 'N/A',
// 'date_modified' => 'N/A',
// ];
// }
// }
// if (!$station) {
// abort(404, 'Station not found');
// }
// return view('pages.view-station', compact('station'));
// }
// public function edit($id)
// {
// $response = Http::get($this->apiBaseUrl . 'cms/getStations');
// $data = $response->json();
// $station = null;
// if ($response->successful() && isset($data['data'])) {
// $station = collect($data['data'])->firstWhere('station_uuid', $id);
// if ($station) {
// $station = [
// 'id' => $station['station_uuid'],
// 'station_code' => $station['code'],
// 'station_name' => $station['description'],
// 'branch_name' => 'N/A',
// 'date_created' => 'N/A',
// 'created_by' => 'N/A',
// 'modified_by' => 'N/A',
// 'date_modified' => 'N/A',
// ];
// }
// }
// if (!$station) {
// abort(404, 'Station not found');
// }
// return view('pages.edit-station', compact('station'));
// }
// public function update(Request $request, $id)
// {
// $request->validate([
// 'station_code' => 'required|string|max:50|unique:stations,station_code,' . $id . ',id',
// 'station_name' => 'required|string|max:255',
// 'branch_name' => 'required|string|max:255',
// ]);
// // Mock API call to update station
// $response = Http::put($this->apiBaseUrl . 'cms/stations/update/' . $id, [
// 'code' => $request->station_code,
// 'description' => $request->station_name,
// 'branch_name' => $request->branch_name,
// ]);
// if ($response->successful()) {
// return redirect()->route('station-management')->with('success', 'Station updated successfully');
// }
// return back()->withErrors(['error' => 'Failed to update station']);
// }
// public function destroy($id)
// {
// // Mock API call to delete station
// $response = Http::delete($this->apiBaseUrl . 'cms/stations/delete/' . $id);
// if ($response->successful()) {
// return redirect()->route('station-management')->with('success', 'Station deleted successfully');
// }
// return back()->withErrors(['error' => 'Failed to delete station']);
// }
} }

View File

@ -12,6 +12,7 @@
'currentPage' => 1, 'currentPage' => 1,
'lastPage' => 1, 'lastPage' => 1,
'total' => 0, 'total' => 0,
'search' => null,
]) ])
<div class="card-header border-0 bg-transparent"> <div class="card-header border-0 bg-transparent">
@ -32,7 +33,7 @@
<span class="input-group-text bg-light border-end-0"> <span class="input-group-text bg-light border-end-0">
<i class="fa-solid fa-magnifying-glass text-muted"></i> <i class="fa-solid fa-magnifying-glass text-muted"></i>
</span> </span>
<input type="text" class="form-control border-start-0" placeholder="Search..." id="searchInput" data-search-param="_search"> <input type="text" class="form-control border-start-0" placeholder="Search..." id="searchInput" value="{{ $search }}" data-search-param="_search">
</div> </div>
</div> </div>
<div class="col-12 col-md-6 d-flex justify-content-end"> <div class="col-12 col-md-6 d-flex justify-content-end">
@ -47,13 +48,8 @@
<table class="table table-hover align-middle"> <table class="table table-hover align-middle">
<thead class="table-light"> <thead class="table-light">
<tr> <tr>
@if ($showCheckboxes)
<th class="text-center" style="width: 40px;">
<input type="checkbox" id="selectAll">
</th>
@endif
@foreach ($columns as $index => $column) @foreach ($columns as $index => $column)
<th class="{{ $column['sortable'] ? 'sortable' : '' }}" data-column="{{ $index + ($showCheckboxes ? 1 : 0) }}"> <th class="{{ $column['sortable'] ? 'sortable' : '' }}" data-column="{{ $index }}">
{{ $column['name'] }} {{ $column['name'] }}
@if ($column['sortable']) @if ($column['sortable'])
<i class="fa-solid fa-sort"></i> <i class="fa-solid fa-sort"></i>
@ -69,15 +65,8 @@
</table> </table>
</div> </div>
<!-- Batch Delete and Pagination --> <!-- Pagination -->
<div class="d-flex justify-content-between align-items-center mt-4"> <div class="d-flex justify-content-end align-items-center mt-4">
@if ($showBatchDelete)
<div>
<button class="btn btn-danger btn-sm" id="deleteSelected" disabled>
<i class="fa-solid fa-trash-can me-1"></i> Delete Selected
</button>
</div>
@endif
<nav aria-label="Page navigation"> <nav aria-label="Page navigation">
<ul class="pagination pagination-sm" id="pagination"></ul> <ul class="pagination pagination-sm" id="pagination"></ul>
</nav> </nav>
@ -175,8 +164,6 @@
data: @json($data), data: @json($data),
columns: @json($columns), columns: @json($columns),
actions: @json($actions), actions: @json($actions),
showCheckboxes: {{ json_encode($showCheckboxes) }},
showBatchDelete: {{ json_encode($showBatchDelete) }},
showEditModal: {{ json_encode($showEditModal) }}, showEditModal: {{ json_encode($showEditModal) }},
showViewModal: {{ json_encode($showViewModal) }}, showViewModal: {{ json_encode($showViewModal) }},
pageTitle: @json($pageTitle), pageTitle: @json($pageTitle),
@ -184,75 +171,98 @@
currentPage: {{ $currentPage }}, currentPage: {{ $currentPage }},
lastPage: {{ $lastPage }}, lastPage: {{ $lastPage }},
total: {{ $total }}, total: {{ $total }},
search: @json($search),
}; };
console.log('Table Config:', {
data: tableConfig.data,
total: tableConfig.total,
currentPage: tableConfig.currentPage,
lastPage: tableConfig.lastPage,
search: tableConfig.search
});
const rowsPerPage = 5; const rowsPerPage = 5;
let currentPage = tableConfig.currentPage; let currentPage = tableConfig.currentPage;
let filteredRows = [...tableConfig.data]; let filteredRows = [...tableConfig.data];
let originalRows = [...tableConfig.data].map(row => ({ ...row }));
let sortDirection = {}; let sortDirection = {};
function renderTable() { function renderTable() {
const tableBody = document.getElementById('tableBody'); const tableBody = document.getElementById('tableBody');
if (!tableBody) return; if (!tableBody) {
console.error('Table body element not found');
return;
}
tableBody.innerHTML = ''; tableBody.innerHTML = '';
const startIndex = (currentPage - 1) * rowsPerPage; const startIndex = (currentPage - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage; const endIndex = startIndex + rowsPerPage;
const paginatedRows = filteredRows.slice(startIndex, endIndex); const paginatedRows = filteredRows.slice(startIndex, endIndex);
paginatedRows.forEach(row => { console.log('Rendering table:', {
const tr = document.createElement('tr'); filteredRowsCount: filteredRows.length,
tr.setAttribute('data-id', row.id); paginatedRows: paginatedRows,
tr.classList.add('clickable-row'); paginatedRowsCount: paginatedRows.length,
let rowHtml = ''; startIndex: startIndex,
endIndex: endIndex
if (tableConfig.showCheckboxes) {
rowHtml += `<td class="text-center"><input type="checkbox" class="rowCheckbox" value="${row.id}"></td>`;
}
tableConfig.columns.forEach(col => {
let value = row[col.key] || '';
if (col.key.includes('date')) {
value = value && value !== 'N/A' ? new Date(value).toLocaleDateString() : 'N/A';
}
rowHtml += `<td>${value}</td>`;
});
if (tableConfig.actions.length > 0) {
rowHtml += `<td class="text-center">`;
tableConfig.actions.forEach(action => {
const routeBase = 'stations';
if (action === 'view') {
rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm view-btn me-1" title="View"><i class="fa-solid fa-eye"></i></a>`;
} else if (action === 'edit') {
rowHtml += `<button class="btn btn-sm edit-btn me-1" title="Edit" onclick="openEditModal('${row.id}')"><i class="fa-solid fa-pen"></i></button>`;
} else if (action === 'delete') {
rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this station?')) { document.getElementById('delete-form-${row.id}').submit(); }"><i class="fa-solid fa-trash"></i></a>
<form id="delete-form-${row.id}" action="/${routeBase}/${row.id}" method="POST" style="display: none;">
@csrf
@method('DELETE')
</form>`;
}
});
rowHtml += `</td>`;
}
tr.innerHTML = rowHtml;
tableBody.appendChild(tr);
}); });
attachEventListeners(); if (paginatedRows.length === 0) {
tableBody.innerHTML = '<tr><td colspan="' + (tableConfig.columns.length + (tableConfig.actions.length > 0 ? 1 : 0)) + '" class="text-center">No stations found</td></tr>';
} else {
paginatedRows.forEach(row => {
if (!row.id || !row.station_code || !row.station_name) {
console.warn('Invalid row data:', row);
return;
}
const tr = document.createElement('tr');
tr.setAttribute('data-id', row.id);
tr.classList.add('clickable-row');
let rowHtml = '';
tableConfig.columns.forEach(col => {
let value = row[col.key] || 'N/A';
rowHtml += `<td>${value}</td>`;
});
if (tableConfig.actions.length > 0) {
rowHtml += `<td class="text-center">`;
tableConfig.actions.forEach(action => {
const routeBase = 'stations';
if (action === 'view') {
rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm view-btn me-1" title="View"><i class="fa-solid fa-eye"></i></a>`;
} else if (action === 'edit') {
rowHtml += `<button class="btn btn-sm edit-btn me-1" title="Edit" onclick="openEditModal('${row.id}')"><i class="fa-solid fa-pen"></i></button>`;
} else if (action === 'delete') {
rowHtml += `<a href="/${routeBase}/${row.id}" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this station?')) { document.getElementById('delete-form-${row.id}').submit(); }"><i class="fa-solid fa-trash"></i></a>
<form id="delete-form-${row.id}" action="/${routeBase}/${row.id}" method="POST" style="display: none;">
@csrf
@method('DELETE')
</form>`;
}
});
rowHtml += `</td>`;
}
tr.innerHTML = rowHtml;
tableBody.appendChild(tr);
});
}
updateNoDataMessage(); updateNoDataMessage();
attachEventListeners();
} }
function renderPagination() { function renderPagination() {
const pagination = document.getElementById('pagination'); const pagination = document.getElementById('pagination');
if (!pagination) return; if (!pagination) {
console.error('Pagination element not found');
return;
}
pagination.innerHTML = ''; pagination.innerHTML = '';
const totalPages = Math.max(tableConfig.lastPage, 1); const totalPages = Math.max(tableConfig.lastPage, 1);
const routeName = tableConfig.pageTitle.toLowerCase().replace(/\s+/g, '-') + '.index'; console.log('Rendering pagination:', { totalPages, currentPage });
const prevLi = document.createElement('li'); const prevLi = document.createElement('li');
prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`; prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
@ -292,6 +302,7 @@
} }
function updateUrl(page, search = '') { function updateUrl(page, search = '') {
console.log('Updating URL:', { page, search });
const url = new URL(window.location); const url = new URL(window.location);
url.searchParams.set('page', page); url.searchParams.set('page', page);
if (search) { if (search) {
@ -310,12 +321,16 @@
const noDataMessage = document.getElementById('no-data-message'); const noDataMessage = document.getElementById('no-data-message');
if (noDataMessage) { if (noDataMessage) {
noDataMessage.style.display = filteredRows.length === 0 ? 'block' : 'none'; noDataMessage.style.display = filteredRows.length === 0 ? 'block' : 'none';
console.log('No data message:', { display: noDataMessage.style.display, filteredRowsCount: filteredRows.length });
} }
} }
function openEditModal(id) { function openEditModal(id) {
const row = tableConfig.data.find(row => row.id === id); const row = tableConfig.data.find(row => row.id === id);
if (!row) return; if (!row) {
console.error('Row not found for edit:', id);
return;
}
const editForm = document.getElementById('editForm'); const editForm = document.getElementById('editForm');
if (editForm) { if (editForm) {
@ -334,16 +349,16 @@
function openViewModal(id) { function openViewModal(id) {
const row = tableConfig.data.find(row => row.id === id); const row = tableConfig.data.find(row => row.id === id);
if (!row) return; if (!row) {
console.error('Row not found for view:', id);
return;
}
const modalBody = document.getElementById('viewModalBody'); const modalBody = document.getElementById('viewModalBody');
if (modalBody) { if (modalBody) {
let html = ''; let html = '';
tableConfig.columns.forEach(col => { tableConfig.columns.forEach(col => {
let value = row[col.key] || 'N/A'; let value = row[col.key] || 'N/A';
if (col.key.includes('date')) {
value = value && value !== 'N/A' ? new Date(value).toLocaleDateString() : 'N/A';
}
html += `<p><strong>${col.name}:</strong> ${value}</p>`; html += `<p><strong>${col.name}:</strong> ${value}</p>`;
}); });
modalBody.innerHTML = html; modalBody.innerHTML = html;
@ -356,16 +371,18 @@
const searchInput = document.getElementById('searchInput'); const searchInput = document.getElementById('searchInput');
if (searchInput) { if (searchInput) {
searchInput.addEventListener('input', function() { searchInput.addEventListener('input', function() {
console.log('Search input:', this.value);
updateUrl(1, this.value); updateUrl(1, this.value);
}); });
} }
document.querySelectorAll('.sortable').forEach(header => { document.querySelectorAll('.sortable').forEach(header => {
header.addEventListener('click', function() { header.addEventListener('click', function() {
const columnIndex = parseInt(this.getAttribute('data-column')) - (tableConfig.showCheckboxes ? 1 : 0); const columnIndex = parseInt(this.getAttribute('data-column'));
const key = tableConfig.columns[columnIndex].key; const key = tableConfig.columns[columnIndex].key;
sortDirection[columnIndex] = !sortDirection[columnIndex] ? 'asc' : sortDirection[columnIndex] === 'asc' ? 'desc' : 'asc'; sortDirection[columnIndex] = !sortDirection[columnIndex] ? 'asc' : sortDirection[columnIndex] === 'asc' ? 'desc' : 'asc';
console.log('Sorting:', { key, direction: sortDirection[columnIndex] });
document.querySelectorAll('.sortable i').forEach(icon => { document.querySelectorAll('.sortable i').forEach(icon => {
icon.classList.remove('fa-sort-up', 'fa-sort-down'); icon.classList.remove('fa-sort-up', 'fa-sort-down');
@ -384,6 +401,7 @@
const clearFilters = document.getElementById('clearFilters'); const clearFilters = document.getElementById('clearFilters');
if (clearFilters) { if (clearFilters) {
clearFilters.addEventListener('click', function() { clearFilters.addEventListener('click', function() {
console.log('Clearing filters');
if (searchInput) searchInput.value = ''; if (searchInput) searchInput.value = '';
sortDirection = {}; sortDirection = {};
document.querySelectorAll('.sortable i').forEach(icon => { document.querySelectorAll('.sortable i').forEach(icon => {
@ -394,57 +412,13 @@
}); });
} }
const checkboxes = document.querySelectorAll('.rowCheckbox');
const selectAll = document.getElementById('selectAll');
const deleteSelected = document.getElementById('deleteSelected');
if (selectAll) {
selectAll.addEventListener('change', function() {
checkboxes.forEach(checkbox => checkbox.checked = this.checked);
updateDeleteButton();
});
}
if (checkboxes.length > 0) {
checkboxes.forEach(checkbox => {
checkbox.addEventListener('change', updateDeleteButton);
});
}
if (deleteSelected) {
deleteSelected.addEventListener('click', function() {
const selectedIds = Array.from(document.querySelectorAll('.rowCheckbox:checked')).map(cb => cb.value);
if (selectedIds.length > 0 && confirm('Are you sure you want to delete the selected stations?')) {
fetch('/stations/batch-delete', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': tableConfig.csrfToken,
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ station_ids: selectedIds })
}).then(response => response.json())
.then(data => {
if (data.success) {
location.reload();
} else {
alert(data.message || 'Error deleting stations');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while deleting the stations.');
});
}
});
}
document.querySelectorAll('.clickable-row').forEach(row => { document.querySelectorAll('.clickable-row').forEach(row => {
row.addEventListener('click', function(e) { row.addEventListener('click', function(e) {
if (e.target.closest('.rowCheckbox, .edit-btn, .view-btn, .delete-btn')) { if (e.target.closest('.edit-btn, .view-btn, .delete-btn')) {
return; return;
} }
const id = this.getAttribute('data-id'); const id = this.getAttribute('data-id');
console.log('Row clicked:', id);
if (tableConfig.showViewModal) { if (tableConfig.showViewModal) {
openViewModal(id); openViewModal(id);
} else { } else {
@ -454,14 +428,12 @@
}); });
} }
function updateDeleteButton() { try {
const deleteSelected = document.getElementById('deleteSelected'); renderTable();
const checkedBoxes = document.querySelectorAll('.rowCheckbox:checked'); renderPagination();
deleteSelected.disabled = checkedBoxes.length === 0; } catch (error) {
console.error('Error rendering table:', error);
} }
renderTable();
renderPagination();
</script> </script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">

View File

@ -8,20 +8,23 @@
</div> </div>
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="card-body p-3"> <div class="card-body p-3">
<!-- Filters --> @if ($errorMessage)
<div class="alert alert-danger">{{ $errorMessage }}</div>
@endif
<div class="d-flex justify-content-between mb-3 flex-wrap gap-2"> <div class="d-flex justify-content-between mb-3 flex-wrap gap-2">
<div class="d-flex align-items-center gap-2"> <div class="d-flex align-items-center gap-2">
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="startDate" class="form-label mb-1">Start Date</label> <label for="startDate" class="form-label mb-1">Start Date</label>
<div class="input-group"> <div class="input-group">
<span class="input-group-text"><i class="fas fa-calendar-alt"></i></span> <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
<input type="date" class="form-control" id="startDate"> <input type="date" class="form-control" id="startDate" value="{{ request('date_start') }}">
</div> </div>
</div> </div>
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="endDate" class="form-label mb-1">End Date</label> <label for="endDate" class="form-label mb-1">End Date</label>
<div class="input-group"> <div class="input-group">
<input type="date" class="form-control" id="endDate"> <input type="date" class="form-control" id="endDate" value="{{ request('date_end') }}">
</div> </div>
</div> </div>
</div> </div>
@ -30,7 +33,6 @@
</div> </div>
</div> </div>
<!-- Table -->
@include('components.reports-component', [ @include('components.reports-component', [
'pageTitle' => 'Mobile Usage Report', 'pageTitle' => 'Mobile Usage Report',
'data' => $mobileUsageData ?? [], 'data' => $mobileUsageData ?? [],
@ -45,7 +47,7 @@
'showAddButton' => false, 'showAddButton' => false,
'showCheckboxes' => false, 'showCheckboxes' => false,
'showBatchDelete' => false, 'showBatchDelete' => false,
'showSearch' => false, 'showSearch' => true,
'currentPage' => $currentPage ?? 1, 'currentPage' => $currentPage ?? 1,
'lastPage' => $lastPage ?? 1, 'lastPage' => $lastPage ?? 1,
'total' => $total ?? 0, 'total' => $total ?? 0,
@ -54,20 +56,6 @@
</div> </div>
<style> <style>
.card {
border-radius: 5px;
border: 1px solid #dee2e6;
}
.form-control {
font-size: 0.9rem;
}
.btn-outline-secondary {
border-color: #6c757d;
color: #6c757d;
}
.btn-outline-secondary:hover {
background-color: #f8f9fa;
}
.btn-export-csv { .btn-export-csv {
background-color: #ff6200; background-color: #ff6200;
color: white; color: white;
@ -76,63 +64,43 @@
.btn-export-csv:hover { .btn-export-csv:hover {
background-color: #e65a00; background-color: #e65a00;
} }
.input-group-text {
background-color: #f8f9fa;
}
</style> </style>
<script> <script>
let originalData = [...tableConfig.data];
const startDateInput = document.getElementById('startDate'); const startDateInput = document.getElementById('startDate');
const endDateInput = document.getElementById('endDate'); const endDateInput = document.getElementById('endDate');
const searchInput = document.getElementById('searchInput');
const exportCsvBtn = document.getElementById('exportCsv'); const exportCsvBtn = document.getElementById('exportCsv');
function filterData() { function updateQueryParams() {
const startDate = startDateInput.value ? new Date(startDateInput.value) : null; const url = new URL(window.location);
const endDate = endDateInput.value ? new Date(endDateInput.value) : null; url.searchParams.set('page', '1');
if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
tableConfig.data = originalData.filter(item => { else url.searchParams.delete('date_start');
const itemDate = new Date(item.date); if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (startDate && itemDate < startDate) return false; else url.searchParams.delete('date_end');
if (endDate) { if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
const endDateAdjusted = new Date(endDate); else url.searchParams.delete('_search');
endDateAdjusted.setHours(23, 59, 59, 999); window.location = url;
if (itemDate > endDateAdjusted) return false;
}
return true;
});
currentPage = 1;
renderTable();
renderPagination();
} }
startDateInput.addEventListener('change', filterData); startDateInput.addEventListener('change', updateQueryParams);
endDateInput.addEventListener('change', filterData); endDateInput.addEventListener('change', updateQueryParams);
searchInput?.addEventListener('input', () => {
exportCsvBtn.addEventListener('click', () => { clearTimeout(window.searchTimeout);
const headers = tableConfig.columns.map(col => col.name).join(','); window.searchTimeout = setTimeout(updateQueryParams, 500);
const rows = tableConfig.data.map(item => {
return [
item.date,
item.activeUsers,
item.inactiveUsers,
item.lockedUsers
].join(',');
});
const csvContent = [headers, ...rows].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', 'mobile-usage-report.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}); });
// Initial render exportCsvBtn.addEventListener('click', () => {
renderTable(); const url = new URL(tableConfig.exportEndpoint, window.location.origin);
renderPagination(); if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
if (sortColumn && sortDirection) {
url.searchParams.set('sort', `${sortColumn}|${sortDirection}`);
}
console.log('Exporting CSV to:', url.toString());
window.location.href = url.toString();
});
</script> </script>
@endsection @endsection

View File

@ -8,20 +8,23 @@
</div> </div>
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="card-body p-3"> <div class="card-body p-3">
<!-- Filters --> @if ($errorMessage)
<div class="alert alert-danger">{{ $errorMessage }}</div>
@endif
<div class="d-flex justify-content-between mb-3 flex-wrap gap-2"> <div class="d-flex justify-content-between mb-3 flex-wrap gap-2">
<div class="d-flex align-items-center gap-2"> <div class="d-flex align-items-center gap-2">
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="startDate" class="form-label mb-1">Start Date</label> <label for="startDate" class="form-label mb-1">Start Date</label>
<div class="input-group"> <div class="input-group">
<span class="input-group-text"><i class="fas fa-calendar-alt"></i></span> <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
<input type="date" class="form-control" id="startDate"> <input type="date" class="form-control" id="startDate" value="{{ request('date_start') }}">
</div> </div>
</div> </div>
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="endDate" class="form-label mb-1">End Date</label> <label for="endDate" class="form-label mb-1">End Date</label>
<div class="input-group"> <div class="input-group">
<input type="date" class="form-control" id="endDate"> <input type="date" class="form-control" id="endDate" value="{{ request('date_end') }}">
</div> </div>
</div> </div>
</div> </div>
@ -30,7 +33,6 @@
</div> </div>
</div> </div>
<!-- Table -->
@include('components.reports-component', [ @include('components.reports-component', [
'pageTitle' => 'Registration Report', 'pageTitle' => 'Registration Report',
'data' => $registrationData ?? [], 'data' => $registrationData ?? [],
@ -44,7 +46,7 @@
'showAddButton' => false, 'showAddButton' => false,
'showCheckboxes' => false, 'showCheckboxes' => false,
'showBatchDelete' => false, 'showBatchDelete' => false,
'showSearch' => false, 'showSearch' => true,
'currentPage' => $currentPage ?? 1, 'currentPage' => $currentPage ?? 1,
'lastPage' => $lastPage ?? 1, 'lastPage' => $lastPage ?? 1,
'total' => $total ?? 0, 'total' => $total ?? 0,
@ -53,20 +55,6 @@
</div> </div>
<style> <style>
.card {
border-radius: 5px;
border: 1px solid #dee2e6;
}
.form-control {
font-size: 0.9rem;
}
.btn-outline-secondary {
border-color: #6c757d;
color: #6c757d;
}
.btn-outline-secondary:hover {
background-color: #f8f9fa;
}
.btn-export-csv { .btn-export-csv {
background-color: #ff6200; background-color: #ff6200;
color: white; color: white;
@ -75,62 +63,43 @@
.btn-export-csv:hover { .btn-export-csv:hover {
background-color: #e65a00; background-color: #e65a00;
} }
.input-group-text {
background-color: #f8f9fa;
}
</style> </style>
<script> <script>
let originalData = [...tableConfig.data];
const startDateInput = document.getElementById('startDate'); const startDateInput = document.getElementById('startDate');
const endDateInput = document.getElementById('endDate'); const endDateInput = document.getElementById('endDate');
const searchInput = document.getElementById('searchInput');
const exportCsvBtn = document.getElementById('exportCsv'); const exportCsvBtn = document.getElementById('exportCsv');
function filterData() { function updateQueryParams() {
const startDate = startDateInput.value ? new Date(startDateInput.value) : null; const url = new URL(window.location);
const endDate = endDateInput.value ? new Date(endDateInput.value) : null; url.searchParams.set('page', '1');
if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
tableConfig.data = originalData.filter(item => { else url.searchParams.delete('date_start');
const itemDate = new Date(item.date); if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (startDate && itemDate < startDate) return false; else url.searchParams.delete('date_end');
if (endDate) { if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
const endDateAdjusted = new Date(endDate); else url.searchParams.delete('_search');
endDateAdjusted.setHours(23, 59, 59, 999); window.location = url;
if (itemDate > endDateAdjusted) return false;
}
return true;
});
currentPage = 1;
renderTable();
renderPagination();
} }
startDateInput.addEventListener('change', filterData); startDateInput.addEventListener('change', updateQueryParams);
endDateInput.addEventListener('change', filterData); endDateInput.addEventListener('change', updateQueryParams);
searchInput?.addEventListener('input', () => {
exportCsvBtn.addEventListener('click', () => { clearTimeout(window.searchTimeout);
const headers = tableConfig.columns.map(col => col.name).join(','); window.searchTimeout = setTimeout(updateQueryParams, 500);
const rows = tableConfig.data.map(item => {
return [
item.date,
item.activatedCards,
item.registeredMembers
].join(',');
});
const csvContent = [headers, ...rows].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', 'registration-report.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}); });
// Initial render exportCsvBtn.addEventListener('click', () => {
renderTable(); const url = new URL(tableConfig.exportEndpoint, window.location.origin);
renderPagination(); if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
if (sortColumn && sortDirection) {
url.searchParams.set('sort', `${sortColumn}|${sortDirection}`);
}
console.log('Exporting CSV to:', url.toString());
window.location.href = url.toString();
});
</script> </script>
@endsection @endsection

View File

@ -8,20 +8,23 @@
</div> </div>
<div class="row justify-content-center"> <div class="row justify-content-center">
<div class="card-body p-3"> <div class="card-body p-3">
<!-- Filters --> @if ($errorMessage)
<div class="alert alert-danger">{{ $errorMessage }}</div>
@endif
<div class="d-flex justify-content-between mb-3 flex-wrap gap-2"> <div class="d-flex justify-content-between mb-3 flex-wrap gap-2">
<div class="d-flex align-items-center gap-2"> <div class="d-flex align-items-center gap-2">
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="startDate" class="form-label mb-1">Start Date</label> <label for="startDate" class="form-label mb-1">Start Date</label>
<div class="input-group"> <div class="input-group">
<span class="input-group-text"><i class="fas fa-calendar-alt"></i></span> <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
<input type="date" class="form-control" id="startDate"> <input type="date" class="form-control" id="startDate" value="{{ request('date_start') }}">
</div> </div>
</div> </div>
<div class="d-flex flex-column"> <div class="d-flex flex-column">
<label for="endDate" class="form-label mb-1">End Date</label> <label for="endDate" class="form-label mb-1">End Date</label>
<div class="input-group"> <div class="input-group">
<input type="date" class="form-control" id="endDate"> <input type="date" class="form-control" id="endDate" value="{{ request('date_end') }}">
</div> </div>
</div> </div>
</div> </div>
@ -30,7 +33,6 @@
</div> </div>
</div> </div>
<!-- Table -->
@include('components.reports-component', [ @include('components.reports-component', [
'pageTitle' => 'Top-Up Usage Report', 'pageTitle' => 'Top-Up Usage Report',
'data' => $topUpData ?? [], 'data' => $topUpData ?? [],
@ -44,7 +46,7 @@
'showAddButton' => false, 'showAddButton' => false,
'showCheckboxes' => false, 'showCheckboxes' => false,
'showBatchDelete' => false, 'showBatchDelete' => false,
'showSearch' => false, 'showSearch' => true,
'currentPage' => $currentPage ?? 1, 'currentPage' => $currentPage ?? 1,
'lastPage' => $lastPage ?? 1, 'lastPage' => $lastPage ?? 1,
'total' => $total ?? 0, 'total' => $total ?? 0,
@ -81,56 +83,40 @@
</style> </style>
<script> <script>
let originalData = [...tableConfig.data];
const startDateInput = document.getElementById('startDate'); const startDateInput = document.getElementById('startDate');
const endDateInput = document.getElementById('endDate'); const endDateInput = document.getElementById('endDate');
const searchInput = document.getElementById('searchInput');
const exportCsvBtn = document.getElementById('exportCsv'); const exportCsvBtn = document.getElementById('exportCsv');
function filterData() { function updateQueryParams() {
const startDate = startDateInput.value ? new Date(startDateInput.value) : null; const url = new URL(window.location);
const endDate = endDateInput.value ? new Date(endDateInput.value) : null; url.searchParams.set('page', '1');
if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
tableConfig.data = originalData.filter(item => { else url.searchParams.delete('date_start');
const itemDate = new Date(item.transactionDateTime); if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (startDate && itemDate < startDate) return false; else url.searchParams.delete('date_end');
if (endDate) { if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
const endDateAdjusted = new Date(endDate); else url.searchParams.delete('_search');
endDateAdjusted.setHours(23, 59, 59, 999); window.location = url;
if (itemDate > endDateAdjusted) return false;
}
return true;
});
currentPage = 1;
renderTable();
renderPagination();
} }
startDateInput.addEventListener('change', filterData); startDateInput.addEventListener('change', updateQueryParams);
endDateInput.addEventListener('change', filterData); endDateInput.addEventListener('change', updateQueryParams);
searchInput?.addEventListener('input', () => {
exportCsvBtn.addEventListener('click', () => { clearTimeout(window.searchTimeout);
const headers = tableConfig.columns.map(col => col.name).join(','); window.searchTimeout = setTimeout(updateQueryParams, 500);
const rows = tableConfig.data.map(item => {
return [
item.transactionDateTime,
item.cardNumber,
item.topUpAmount
].join(',');
});
const csvContent = [headers, ...rows].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', 'top-up-usage-report.csv');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}); });
// Initial render exportCsvBtn.addEventListener('click', () => {
renderTable(); const url = new URL(tableConfig.exportEndpoint, window.location.origin);
renderPagination(); if (startDateInput.value) url.searchParams.set('date_start', startDateInput.value);
if (endDateInput.value) url.searchParams.set('date_end', endDateInput.value);
if (searchInput?.value) url.searchParams.set('_search', searchInput.value);
if (sortColumn && sortDirection) {
url.searchParams.set('sort', `${sortColumn}|${sortDirection}`);
}
console.log('Exporting CSV to:', url.toString());
window.location.href = url.toString();
});
</script> </script>
@endsection @endsection

View File

@ -3,7 +3,19 @@
@section('page_title', 'Station Management') @section('page_title', 'Station Management')
@section('content') @section('content')
@include('components.table-component', [ @if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
<!-- Debug: Display raw stations data -->
<div style="display: none;">
<h6>Debug: Raw Stations Data</h6>
<pre>{{ json_encode($stations, JSON_PRETTY_PRINT) }}</pre>
</div>
@include('components.station-component', [
'pageTitle' => 'Station Management', 'pageTitle' => 'Station Management',
'data' => $stations ?? [], 'data' => $stations ?? [],
'columns' => [ 'columns' => [
@ -25,8 +37,9 @@
'currentPage' => $currentPage ?? 1, 'currentPage' => $currentPage ?? 1,
'lastPage' => $lastPage ?? 1, 'lastPage' => $lastPage ?? 1,
'total' => $total ?? 0, 'total' => $total ?? 0,
'search' => $search ?? null,
]) ])
<div id="no-data-message" style="display: {{ empty($stations ?? []) ? 'block' : 'none' }}; text-align: center; margin-top: 20px;"> <div id="no-data-message" style="display: none; text-align: center; margin-top: 20px;">
<p>No stations found.</p> <p>No stations found.</p>
</div> </div>
@endsection @endsection

View File

@ -42,6 +42,8 @@
@endif @endif
<div class="text-end"> <div class="text-end">
<a href="{{ route('user.management') }}" class="btn btn-primary">Back to Users</a> <a href="{{ route('user.management') }}" class="btn btn-primary">Back to Users</a>
<a href="{{ route('user-management.edit', $user['username']) }}" class="btn btn-primary">Edit</a>
</div> </div>
</div> </div>
</div> </div>

View File

@ -202,7 +202,12 @@ Route::get('/mobile-usage-report', [ReportsController::class, 'mobileUsage'])->n
Route::get('/registration-report', [ReportsController::class, 'registration'])->name('registration-report'); Route::get('/registration-report', [ReportsController::class, 'registration'])->name('registration-report');
Route::get('/station-rating-report', [ReportsController::class, 'stationRating'])->name('station-rating-report'); Route::get('/station-rating-report', [ReportsController::class, 'stationRating'])->name('station-rating-report');
Route::get('/top-up-usage-report', [ReportsController::class, 'topUp'])->name('top-up-usage-report'); Route::get('/top-up-usage-report', [ReportsController::class, 'topUp'])->name('top-up-usage-report');
Route::get('/station-rating-reportExport', [ReportsController::class, 'exportStationRating'])->name('station-rating-reportExport'); Route::get('/station-rating-reportExport', [ReportsController::class, 'exportStationRating'])->name('station-rating-reportExport');
Route::get('/mobile-usage-reportExport', [ReportsController::class, 'exportMobileUsage'])->name('mobile-usage-reportExport');
Route::get('/registration-reportExport', [ReportsController::class, 'exportRegistration'])->name('registration-reportExport');
Route::get('/top-up-usage-reportExport', [ReportsController::class, 'exportTopUp'])->name('top-up-usage-reportExport');
//Station //Station
Route::get('/station-management', [StationController::class, 'index'])->name('stations'); Route::get('/station-management', [StationController::class, 'index'])->name('stations');
Route::get('/stations/create', [StationController::class, 'create'])->name('stations.create'); Route::get('/stations/create', [StationController::class, 'create'])->name('stations.create');