terms batch delete works

This commit is contained in:
armiejean 2025-05-22 00:20:30 +08:00
parent 905ceb0ba5
commit 5a70321121
3 changed files with 263 additions and 152 deletions

View File

@ -206,7 +206,7 @@ class TermsAndPrivacyController extends Controller
];
return view('pages.terms-and-privacy.edit', ['item' => $item, 'types' => ['1' => 'Terms', '2' => 'Privacy']]);
} else {
Log::warning('No terms or privacy found or invalid API response: ', $json);
Log::warning('No terms and privacy found or invalid API response: ', $json);
return redirect()->back()->with('error', 'Terms or privacy not found.');
}
} catch (\Exception $e) {
@ -298,32 +298,49 @@ class TermsAndPrivacyController extends Controller
$accessToken = $user['access_token'] ?? null;
if (!$accessToken) {
Log::info('No access token found, redirecting to login from terms-and-privacy batch delete');
return redirect()->route('login')->with('error', 'Please log in to delete terms or privacy.');
}
$uuids = $request->input('tp_uuid', []);
if (is_string($uuids)) {
$uuids = json_decode($uuids, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::warning('Invalid JSON format for tp_uuid', ['input' => $uuids]);
return redirect()->back()->with('error', 'Invalid terms or privacy UUID format.');
}
}
if (empty($uuids)) {
if (empty($uuids) || !is_array($uuids)) {
Log::warning('No valid tp_uuids provided for batch delete', ['uuids' => $uuids]);
return redirect()->back()->with('error', 'No terms or privacy selected for deletion.');
}
Log::info('Attempting batch delete for UUIDs: ', ['uuids' => $uuids]);
$response = Http::withHeaders([
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $accessToken,
'Content-Type' => 'application/json',
])->delete("{$this->apiBaseUrl}/TermsAndPrivacyBatchDelete", [
'tp_uuid' => $uuids,
]);
if ($response->successful()) {
Log::info('Terms or privacy batch deleted successfully: ', $uuids);
return redirect()->route('terms-and-privacy')->with('success', 'Selected terms or privacy deleted successfully.');
$json = $response->json();
Log::info('Batch delete response: ', ['response' => $json, 'status' => $response->status(), 'headers' => $response->headers()]);
if ($response->successful() && isset($json['status']) && $json['status'] === 'success') {
Log::info('Batch delete successful for UUIDs: ', ['uuids' => $uuids, 'response' => $json]);
return redirect()->route('terms-and-privacy')
->with('success', $json['message'] ?? 'Selected terms or privacy deleted successfully.');
} else {
Log::warning('Failed to batch delete terms or privacy: ', $response->json());
return redirect()->back()->with('error', $response->json()['message'] ?? 'Failed to delete terms or privacy. Please try again.');
Log::error('Batch delete failed: ', ['response' => $json, 'status' => $response->status(), 'headers' => $response->headers()]);
return redirect()->back()->with('error', $json['message'] ?? 'Failed to delete terms or privacy. Status: ' . $response->status());
}
} catch (\Exception $e) {
Log::error('Error batch deleting terms or privacy: ' . $e->getMessage());
return redirect()->back()->with('error', 'An error occurred while deleting the terms or privacy.');
Log::error('Error in batch delete: ', ['error' => $e->getMessage(), 'uuids' => $uuids ?? [], 'trace' => $e->getTraceAsString()]);
return redirect()->back()->with('error', 'An error occurred while deleting terms or privacy: ' . $e->getMessage());
}
}
}

View File

@ -65,43 +65,7 @@
@endif
</tr>
</thead>
<tbody id="tableBody">
@foreach ($data as $row)
<tr class="clickable-row" data-id="{{ $row['id'] }}">
@if ($showCheckboxes)
<td class="text-center">
<input type="checkbox" class="rowCheckbox" value="{{ $row['id'] }}">
</td>
@endif
@foreach ($columns as $column)
<td>{{ $row[$column['key']] ?? '' }}</td>
@endforeach
@if (!empty($actions))
<td class="text-center">
@if (in_array('view', $actions))
<a href="{{ route('terms-and-privacy.show', $row['id']) }}" class="btn btn-sm view-btn me-1" title="View">
<i class="fa-solid fa-eye"></i>
</a>
@endif
@if (in_array('edit', $actions))
<a href="{{ route('terms-and-privacy.edit', $row['id']) }}" class="btn btn-sm edit-btn me-1" title="Edit">
<i class="fa-solid fa-pen"></i>
</a>
@endif
@if (in_array('delete', $actions))
<form id="delete-form-{{ $row['id'] }}" action="{{ route('terms-and-privacy.destroy', $row['id']) }}" method="POST" style="display: inline;">
@csrf
@method('DELETE')
<a href="#" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this item?')) { document.getElementById('delete-form-{{ $row['id'] }}').submit(); }">
<i class="fa-solid fa-trash"></i>
</a>
</form>
@endif
</td>
@endif
</tr>
@endforeach
</tbody>
<tbody id="tableBody"></tbody>
</table>
</div>
@ -109,33 +73,13 @@
<div class="d-flex justify-content-between align-items-center mt-4">
@if ($showBatchDelete)
<div>
<form id="batch-delete-form" action="{{ route('terms-and-privacy.batchDelete') }}" method="POST">
@csrf
<input type="hidden" name="tp_uuid" id="batchDeleteUuids">
<button type="submit" class="btn btn-danger btn-sm" id="deleteSelected" disabled>
<i class="fa-solid fa-trash-can me-1"></i> Delete Selected
</button>
</form>
<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">
<ul class="pagination pagination-sm" id="pagination">
<li class="page-item {{ $currentPage == 1 ? 'disabled' : '' }}">
<a class="page-link" href="{{ route('terms-and-privacy', ['page' => $currentPage - 1, '_search' => request()->input('_search')]) }}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
@for ($i = 1; $i <= $lastPage; $i++)
<li class="page-item {{ $currentPage == $i ? 'active' : '' }}">
<a class="page-link" href="{{ route('terms-and-privacy', ['page' => $i, '_search' => request()->input('_search')]) }}">{{ $i }}</a>
</li>
@endfor
<li class="page-item {{ $currentPage == $lastPage ? 'disabled' : '' }}">
<a class="page-link" href="{{ route('terms-and-privacy', ['page' => $currentPage + 1, '_search' => request()->input('_search')]) }}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
<ul class="pagination pagination-sm" id="pagination"></ul>
</nav>
</div>
</div>
@ -146,33 +90,120 @@
font-weight: 400;
line-height: 1.5;
}
.table-container {
overflow-x: auto;
.card-header h5 {
font-weight: 500;
}
.table th, .table td {
white-space: nowrap;
.table thead th {
font-weight: 500;
font-size: 0.8rem;
}
.form-label {
font-weight: 500;
font-size: 0.9rem;
}
.card {
border-radius: 10px;
}
.card-header {
background-color: transparent;
}
.btn-primary {
background-color: #E74610;
border-color: #E74610;
}
.btn-primary:hover {
background-color: #E74610;
border-color: #E74610;
}
.sortable {
cursor: pointer;
position: relative;
}
.sortable:hover {
background-color: #f1f3f5;
}
.table {
font-size: 0.85rem;
width: 100%;
table-layout: auto;
}
.table th, .table td {
padding: 0.5rem;
vertical-align: middle;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.table th:first-child, .table td:first-child {
width: 40px;
text-align: center;
}
.table th:last-child, .table td:last-child {
width: 120px;
text-align: center;
}
.table td:nth-child(5), .table th:nth-child(5) {
width: 100px;
}
.table td:nth-child(6), .table th:nth-child(6) {
max-width: 200px;
}
.edit-btn {
border-color: #E74610;
color: #E74610;
}
.edit-btn:hover {
background-color: #E74610;
border-color: #E74610;
color: #fff;
}
.view-btn {
border-color: #0d6efd;
color: #0d6efd;
}
.view-btn:hover {
background-color: #0d6efd;
color: #fff;
}
.delete-btn {
border-color: #dc3545;
color: #dc3545;
}
.delete-btn:hover {
background-color: #dc3545;
color: #fff;
}
.table-hover tbody tr:hover {
cursor: pointer;
background-color: #f8f9fa;
}
.sortable i {
margin-left: 5px;
color: #6c757d;
@media (max-width: 576px) {
.table {
font-size: 0.75rem;
}
.table thead th {
font-size: 0.75rem;
}
.table th, .table td {
padding: 0.3rem;
}
.btn-sm {
padding: 0.2rem 0.4rem;
font-size: 0.75rem;
}
.input-group-sm>.form-control {
font-size: 0.75rem;
}
.pagination-sm .page-link {
padding: 0.2rem 0.4rem;
font-size: 0.75rem;
}
.table td:nth-child(6) {
max-width: 150px;
}
.form-control, .form-select {
font-size: 0.85rem;
}
}
.clickable-row:hover {
background-color: #f1f1f1;
cursor: pointer;
}
.view-btn { border-color: #0d6efd; color: #0d6efd; }
.view-btn:hover { background-color: #0d6efd; color: #fff; }
.edit-btn { border-color: #ffc107; color: #ffc107; }
.edit-btn:hover { background-color: #ffc107; color: #fff; }
.delete-btn { border-color: #dc3545; color: #dc3545; }
.delete-btn:hover { background-color: #dc3545; color: #fff; }
</style>
<script>
@ -188,6 +219,7 @@
currentPage: {{ $currentPage }},
lastPage: {{ $lastPage }},
total: {{ $total }},
csrfToken: '{{ csrf_token() }}',
};
const rowsPerPage = 5;
@ -200,57 +232,99 @@
if (!tableBody) return;
tableBody.innerHTML = '';
const startIndex = (currentPage - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;
const paginatedRows = filteredRows.slice(startIndex, endIndex);
const paginatedRows = filteredRows;
paginatedRows.forEach(row => {
const tr = document.createElement('tr');
tr.setAttribute('data-id', row.id);
tr.classList.add('clickable-row');
let rowHtml = '';
if (paginatedRows.length === 0) {
tableBody.innerHTML = `<tr><td colspan="${tableConfig.showCheckboxes ? tableConfig.columns.length + 1 : tableConfig.columns.length}" class="text-center">No data available</td></tr>`;
} else {
paginatedRows.forEach(row => {
const tr = document.createElement('tr');
tr.setAttribute('data-id', row.id);
tr.classList.add('clickable-row');
let rowHtml = '';
if (tableConfig.showCheckboxes) {
rowHtml += `<td class="text-center"><input type="checkbox" class="rowCheckbox" value="${row.id}"></td>`;
}
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] || '';
rowHtml += `<td>${value}</td>`;
});
if (tableConfig.actions.length > 0) {
rowHtml += `<td class="text-center">`;
tableConfig.actions.forEach(action => {
if (action === 'view') {
rowHtml += `<a href="{{ route('terms-and-privacy.show', '') }}/${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 += `<a href="{{ route('terms-and-privacy.edit', '') }}/${row.id}" class="btn btn-sm edit-btn me-1" title="Edit"><i class="fa-solid fa-pen"></i></a>`;
} else if (action === 'delete') {
rowHtml += `<form id="delete-form-${row.id}" action="{{ route('terms-and-privacy.destroy', '') }}/${row.id}" method="POST" style="display: inline;">
@csrf
@method('DELETE')
<a href="#" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this item?')) { document.getElementById('delete-form-${row.id}').submit(); }">
<i class="fa-solid fa-trash"></i>
</a>
</form>`;
}
tableConfig.columns.forEach(col => {
let value = row[col.key] || '';
rowHtml += `<td>${value}</td>`;
});
rowHtml += `</td>`;
}
tr.innerHTML = rowHtml;
tableBody.appendChild(tr);
});
if (tableConfig.actions.length > 0) {
rowHtml += `<td class="text-center">`;
tableConfig.actions.forEach(action => {
if (action === 'view') {
rowHtml += `<a href="{{ route('terms-and-privacy.show', '') }}/${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 += `<a href="{{ route('terms-and-privacy.edit', '') }}/${row.id}" class="btn btn-sm edit-btn me-1" title="Edit"><i class="fa-solid fa-pen"></i></a>`;
} else if (action === 'delete') {
rowHtml += `<form id="delete-form-${row.id}" action="{{ route('terms-and-privacy.destroy', '') }}/${row.id}" method="POST" style="display: inline;">
@csrf
@method('DELETE')
<a href="#" class="btn btn-sm delete-btn" title="Delete" onclick="event.preventDefault(); if(confirm('Are you sure you want to delete this item?')) { document.getElementById('delete-form-${row.id}').submit(); }">
<i class="fa-solid fa-trash"></i>
</a>
</form>`;
}
});
rowHtml += `</td>`;
}
tr.innerHTML = rowHtml;
tableBody.appendChild(tr);
});
}
attachEventListeners();
updateNoDataMessage();
updateDeleteButton();
}
function updateNoDataMessage() {
const noDataMessage = document.getElementById('no-data-message');
if (noDataMessage) {
noDataMessage.style.display = filteredRows.length === 0 ? 'block' : 'none';
function renderPagination() {
const pagination = document.getElementById('pagination');
if (!pagination) return;
pagination.innerHTML = '';
const prevLi = document.createElement('li');
prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
prevLi.innerHTML = `<a class="page-link" href="#" aria-label="Previous"><span aria-hidden="true">«</span></a>`;
prevLi.addEventListener('click', (e) => {
e.preventDefault();
if (currentPage > 1) {
window.location.href = `{{ route('terms-and-privacy') }}?page=${currentPage - 1}&_search=${encodeURIComponent(document.getElementById('searchInput')?.value || '')}`;
}
});
pagination.appendChild(prevLi);
for (let i = 1; i <= tableConfig.lastPage; i++) {
const li = document.createElement('li');
li.className = `page-item ${currentPage === i ? 'active' : ''}`;
li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
li.addEventListener('click', (e) => {
e.preventDefault();
window.location.href = `{{ route('terms-and-privacy') }}?page=${i}&_search=${encodeURIComponent(document.getElementById('searchInput')?.value || '')}`;
});
pagination.appendChild(li);
}
const nextLi = document.createElement('li');
nextLi.className = `page-item ${currentPage === tableConfig.lastPage ? 'disabled' : ''}`;
nextLi.innerHTML = `<a class="page-link" href="#" aria-label="Next"><span aria-hidden="true">»</span></a>`;
nextLi.addEventListener('click', (e) => {
e.preventDefault();
if (currentPage < tableConfig.lastPage) {
window.location.href = `{{ route('terms-and-privacy') }}?page=${currentPage + 1}&_search=${encodeURIComponent(document.getElementById('searchInput')?.value || '')}`;
}
});
pagination.appendChild(nextLi);
}
function updateDeleteButton() {
const deleteSelected = document.getElementById('deleteSelected');
if (deleteSelected) {
const checkedBoxes = document.querySelectorAll('.rowCheckbox:checked');
deleteSelected.disabled = checkedBoxes.length === 0;
}
}
@ -266,14 +340,14 @@
});
currentPage = 1;
renderTable();
renderPagination();
const url = new URL(window.location);
if (searchTerm) {
url.searchParams.set('_search', searchTerm);
window.location.href = url;
} else {
url.searchParams.delete('_search');
window.history.pushState({}, '', url);
}
window.history.pushState({}, '', url);
});
}
@ -295,13 +369,14 @@
}
filteredRows.sort((a, b) => {
let aValue = (a[key] || '').toString().toLowerCase();
let bValue = (b[key] || '').toString().toLowerCase();
const aValue = (a[key] || '').toString().toLowerCase();
const bValue = (b[key] || '').toString().toLowerCase();
return sortDirection[columnIndex] === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
});
currentPage = 1;
renderTable();
renderPagination();
});
});
@ -317,6 +392,7 @@
filteredRows = [...tableConfig.data];
currentPage = 1;
renderTable();
renderPagination();
const url = new URL(window.location);
url.searchParams.delete('_search');
window.history.pushState({}, '', url);
@ -326,7 +402,6 @@
const checkboxes = document.querySelectorAll('.rowCheckbox');
const selectAll = document.getElementById('selectAll');
const deleteSelected = document.getElementById('deleteSelected');
const batchDeleteUuids = document.getElementById('batchDeleteUuids');
if (selectAll) {
selectAll.addEventListener('change', function() {
@ -341,17 +416,40 @@
});
}
if (deleteSelected && batchDeleteUuids) {
deleteSelected.addEventListener('click', function(e) {
e.preventDefault();
const selectedUuids = Array.from(document.querySelectorAll('.rowCheckbox:checked')).map(cb => cb.value);
if (selectedUuids.length > 0 && confirm('Are you sure you want to delete the selected items?')) {
batchDeleteUuids.value = JSON.stringify(selectedUuids);
document.getElementById('batch-delete-form').submit();
}
});
if (deleteSelected) {
deleteSelected.addEventListener('click', function(e) {
e.preventDefault();
const selectedUuids = Array.from(document.querySelectorAll('.rowCheckbox:checked')).map(cb => cb.value);
if (selectedUuids.length === 0) {
alert('Please select at least one item to delete.');
return;
}
if (confirm('Are you sure you want to delete the selected items?')) {
console.log('Submitting batch delete form with UUIDs:', selectedUuids);
const form = document.createElement('form');
form.method = 'POST';
form.action = '{{ route('terms-and-privacy.batchDelete') }}';
form.style.display = 'none';
const csrfInput = document.createElement('input');
csrfInput.type = 'hidden';
csrfInput.name = '_token';
csrfInput.value = tableConfig.csrfToken;
form.appendChild(csrfInput);
const uuidInput = document.createElement('input');
uuidInput.type = 'hidden';
uuidInput.name = 'tp_uuid';
uuidInput.value = JSON.stringify(selectedUuids);
form.appendChild(uuidInput);
document.body.appendChild(form);
form.submit();
}
});
}
document.querySelectorAll('.clickable-row').forEach(row => {
row.addEventListener('click', function(e) {
if (e.target.closest('.rowCheckbox, .edit-btn, .view-btn, .delete-btn')) {
@ -363,11 +461,7 @@
});
}
function updateDeleteButton() {
const deleteSelected = document.getElementById('deleteSelected');
const checkedBoxes = document.querySelectorAll('.rowCheckbox:checked');
deleteSelected.disabled = checkedBoxes.length === 0;
}
renderTable();
</script>
renderPagination();
</script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

View File

@ -189,7 +189,7 @@ Route::get('/terms-and-privacy/{uuid}', [TermsAndPrivacyController::class, 'show
Route::get('/terms-and-privacy/{uuid}/edit', [TermsAndPrivacyController::class, 'edit'])->name('terms-and-privacy.edit');
Route::put('/terms-and-privacy/{uuid}', [TermsAndPrivacyController::class, 'update'])->name('terms-and-privacy.update');
Route::delete('/terms-and-privacy/{uuid}', [TermsAndPrivacyController::class, 'destroy'])->name('terms-and-privacy.destroy');
Route::delete('/terms-and-privacy/batch-delete', [TermsAndPrivacyController::class, 'batchDelete'])->name('terms-and-privacy.batchDelete');
Route::post('terms-and-privacy/batchDelete', [TermsAndPrivacyController::class, 'batchDelete'])->name('terms-and-privacy.batchDelete');
//Card Types
Route::get('/card-types', [CardTypeController::class, 'index'])->name('card-types');