fix: Add redirectsList JavaScript function to redirects index page

- Add complete redirectsList() function with API integration
- Include analytics_slug support in JavaScript
- Fix missing function that was causing page to not load
- Add proper error handling and loading states
This commit is contained in:
1sonhador committed 2025-10-15 13:39:13 +01:00
1 parent 3f66fcf984
commit 11d9bf8e4f
3 files changed
+227 -3

No files matched your search

+214 -1
View File
@@ -150,4 +150,217 @@
</div>
</div>
</div>
</div>
</div>
<script>
function redirectsList() {
return {
// Data
redirects: [],
stats: {
total: 0,
active: 0,
inactive: 0,
total_clicks: 0
},
pagination: {
page: 1,
limit: 20,
total: 0,
pages: 0
},
filters: {
search: '',
status: ''
},
loading: false,
error: false,
lastUpdated: null,
// Lifecycle
init() {
this.loadRedirects();
},
// Methods
async loadRedirects() {
try {
this.loading = true;
this.error = false;
const params = new URLSearchParams({
page: this.pagination.page,
limit: this.pagination.limit,
...(this.filters.search && { search: this.filters.search }),
...(this.filters.status && { status: this.filters.status })
});
const response = await fetch(`/api/redirects?${params}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer mf_redirect_2025'
}
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const result = await response.json();
if (result.success) {
this.redirects = result.data.redirects;
this.stats = result.data.stats || { total: 0, active: 0, inactive: 0, total_clicks: 0 };
this.pagination = result.data.pagination || { page: 1, limit: 20, total: 0, pages: 0 };
this.lastUpdated = result.timestamp;
} else {
throw new Error(result.error || 'Erro ao carregar redirects');
}
} catch (error) {
console.error('Erro ao carregar redirects:', error);
this.error = true;
this.redirects = [];
this.stats = { total: 0, active: 0, inactive: 0, total_clicks: 0 };
} finally {
this.loading = false;
}
},
// Computed properties
get hasRedirects() {
return this.redirects.length > 0;
},
get filteredRedirects() {
return this.redirects;
},
// Utility methods
formatDate(dateString) {
if (!dateString) return '-';
return new Date(dateString).toLocaleDateString('pt-PT');
},
getStatusBadgeClass(status) {
const classes = {
'1': 'badge bg-success',
'0': 'badge bg-secondary',
'-1': 'badge bg-danger'
};
return classes[status] || 'badge bg-secondary';
},
getStatusText(status) {
const texts = {
'1': 'Ativo',
'0': 'Inativo',
'-1': 'Eliminado'
};
return texts[status] || status;
},
getTypeBadgeClass(type) {
const classes = {
'301': 'badge bg-primary',
'302': 'badge bg-info',
'meta': 'badge bg-warning',
'javascript': 'badge bg-secondary'
};
return classes[type] || 'badge bg-secondary';
},
getTrackingBadgeClass(enabled) {
return enabled ? 'badge bg-success' : 'badge bg-secondary';
},
getTrackingText(enabled) {
return enabled ? 'Ativo' : 'Inativo';
},
formatNumber(value) {
return new Intl.NumberFormat('pt-PT').format(value || 0);
},
truncateUrl(url, maxLength = 50) {
if (!url) return '-';
return url.length > maxLength ? url.substring(0, maxLength) + '...' : url;
},
// Actions
applyFilters() {
this.pagination.page = 1;
this.loadRedirects();
},
clearFilters() {
this.filters.search = '';
this.filters.status = '';
this.pagination.page = 1;
this.loadRedirects();
},
changePage(page) {
this.pagination.page = page;
this.loadRedirects();
},
changeStatus(status) {
this.filters.status = status;
this.pagination.page = 1;
this.loadRedirects();
},
refreshRedirects() {
this.loadRedirects();
},
goToView(id) {
window.location.href = `/redirects/redirects/${id}`;
},
goToEdit(id) {
window.location.href = `/redirects/redirects/${id}/edit`;
},
goToCreate() {
window.location.href = '/redirects/redirects/create';
},
async deleteRedirect(id, name) {
if (!confirm(`Tem a certeza que deseja eliminar o redirect "${name}"?`)) {
return;
}
try {
const response = await fetch(`/api/redirects/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer mf_redirect_2025'
}
});
const result = await response.json();
if (result.success) {
this.loadRedirects(); // Reload the list
} else {
alert('Erro: ' + result.error);
}
} catch (error) {
console.error('Erro:', error);
alert('Ocorreu um erro ao eliminar o redirect');
}
},
copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
// Could add a toast notification here
console.log('URL copied to clipboard');
});
}
};
}
</script>
+11
View File
@@ -0,0 +1,11 @@
<?php
require_once 'config.php';
$db = \App\Core\DatabaseManager::getInstance();
$redirects = $db->fetchAll('SELECT id, cuid, analytics_slug, name FROM redirects WHERE status >= 0 LIMIT 5');
echo "🔍 Verificando analytics_slug na base de dados...\n\n";
foreach ($redirects as $r) {
echo "ID: {$r['id']}, CUID: {$r['cuid']}, Analytics Slug: " . ($r['analytics_slug'] ?? 'NULL') . ", Name: {$r['name']}\n";
}
@@ -1,5 +1,4 @@
<?php
// Script para testar se a API está a retornar analytics_slug
require_once 'config.php';
use App\Modules\Redirects\Models\RedirectModel;
@@ -8,7 +7,7 @@ try {
$model = new RedirectModel();
$redirects = $model->getAll();
echo "🔍 Testando API de redirects...\n\n";
echo "🔍 Testando analytics_slug...\n\n";
echo "📊 Total de redirects: " . count($redirects) . "\n\n";
if (!empty($redirects)) {
@@ -24,6 +23,7 @@ try {
foreach ($redirects as $redirect) {
if (empty($redirect['analytics_slug'])) {
$withoutSlug++;
echo "❌ Redirect ID {$redirect['id']} sem analytics_slug\n";
}
}