fix: Add analytics URL copy functionality and fix delete redirect error
- Add analytics public URL input with copy button in redirect view - Fix deleteCreativeByRedirectId to handle missing creatives gracefully - Add copyAnalyticsUrl JavaScript function with visual feedback - Improve error handling in redirect deletion process
This commit is contained in:
1 parent
4c08a83707
commit
151bac0e20
6 files changed
+178
-198
No files matched your search
@@ -162,17 +162,24 @@ class RedirectCreativeService
|
||||
*/
|
||||
public function deleteCreativeByRedirectId(int $redirectId): bool
|
||||
{
|
||||
$creative = $this->getCreativeByRedirectId($redirectId);
|
||||
if (!$creative) {
|
||||
return false;
|
||||
try {
|
||||
$creative = $this->getCreativeByRedirectId($redirectId);
|
||||
if (!$creative) {
|
||||
// Se não existe creative associado, consideramos sucesso
|
||||
return true;
|
||||
}
|
||||
|
||||
$sql = "UPDATE advertising_creatives SET
|
||||
is_active = 0,
|
||||
deleted_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?";
|
||||
|
||||
return $this->db->query($sql, [$creative['id']]) > 0;
|
||||
} catch (\Exception $e) {
|
||||
// Log do erro mas não falha a operação
|
||||
error_log("Error deleting creative for redirect {$redirectId}: " . $e->getMessage());
|
||||
return true; // Consideramos sucesso para não bloquear a eliminação do redirect
|
||||
}
|
||||
|
||||
$sql = "UPDATE advertising_creatives SET
|
||||
is_active = 0,
|
||||
deleted_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?";
|
||||
|
||||
return $this->db->query($sql, [$creative['id']]) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -63,6 +63,31 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<!-- Analytics Public URL -->
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h6>Analytics Público</h6>
|
||||
<p class="text-muted small mb-2">Partilha este link para permitir acesso público aos analytics deste redirect</p>
|
||||
<div class="input-group">
|
||||
<input type="text"
|
||||
class="form-control"
|
||||
id="analyticsUrl"
|
||||
value="https://redirect.moneyflix.com/public/analytics/<?= htmlspecialchars($redirect['analytics_slug']) ?>"
|
||||
readonly>
|
||||
<button class="btn btn-outline-secondary" type="button" onclick="copyAnalyticsUrl()">
|
||||
<i class="ri-file-copy-line me-1"></i>Copiar
|
||||
</button>
|
||||
<a href="/public/analytics/<?= htmlspecialchars($redirect['analytics_slug']) ?>"
|
||||
target="_blank"
|
||||
class="btn btn-outline-primary">
|
||||
<i class="ri-external-link-line me-1"></i>Abrir
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<a href="/redirects/redirects/<?= $redirect['id'] ?>/edit" class="btn btn-primary me-2">Edit Redirect</a>
|
||||
<a href="/r/<?= $redirect['cuid'] ?>" target="_blank" class="btn btn-info me-2">Test Redirect</a>
|
||||
@@ -253,6 +278,49 @@ function deleteFilter(filterId) {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function copyAnalyticsUrl() {
|
||||
const analyticsUrl = document.getElementById('analyticsUrl');
|
||||
analyticsUrl.select();
|
||||
analyticsUrl.setSelectionRange(0, 99999); // For mobile devices
|
||||
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
|
||||
// Show success feedback
|
||||
const button = event.target.closest('button');
|
||||
const originalText = button.innerHTML;
|
||||
button.innerHTML = '<i class="ri-check-line me-1"></i>Copiado!';
|
||||
button.classList.remove('btn-outline-secondary');
|
||||
button.classList.add('btn-success');
|
||||
|
||||
setTimeout(() => {
|
||||
button.innerHTML = originalText;
|
||||
button.classList.remove('btn-success');
|
||||
button.classList.add('btn-outline-secondary');
|
||||
}, 2000);
|
||||
|
||||
} catch (err) {
|
||||
// Fallback for modern browsers
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(analyticsUrl.value).then(() => {
|
||||
const button = event.target.closest('button');
|
||||
const originalText = button.innerHTML;
|
||||
button.innerHTML = '<i class="ri-check-line me-1"></i>Copiado!';
|
||||
button.classList.remove('btn-outline-secondary');
|
||||
button.classList.add('btn-success');
|
||||
|
||||
setTimeout(() => {
|
||||
button.innerHTML = originalText;
|
||||
button.classList.remove('btn-success');
|
||||
button.classList.add('btn-outline-secondary');
|
||||
}, 2000);
|
||||
});
|
||||
} else {
|
||||
alert('Não foi possível copiar automaticamente. Por favor, selecione e copie manualmente.');
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
// Script para verificar tabelas no servidor
|
||||
$host = 'localhost';
|
||||
$port = 3306;
|
||||
$dbname = 'redirects_moneyflix';
|
||||
$username = 'redirects_user';
|
||||
$password = 'mf_redirect_2025';
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4", $username, $password);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
echo "🔍 Verificando tabelas no servidor...\n\n";
|
||||
|
||||
// Verificar se advertising_creatives existe
|
||||
$stmt = $pdo->query("SHOW TABLES LIKE 'advertising_creatives'");
|
||||
$exists = $stmt->rowCount() > 0;
|
||||
echo "📋 Tabela advertising_creatives: " . ($exists ? "✅ EXISTE" : "❌ NÃO EXISTE") . "\n";
|
||||
|
||||
if ($exists) {
|
||||
// Verificar estrutura da tabela
|
||||
$stmt = $pdo->query("DESCRIBE advertising_creatives");
|
||||
$columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
echo "📊 Colunas da tabela advertising_creatives:\n";
|
||||
foreach ($columns as $column) {
|
||||
echo " - {$column['Field']} ({$column['Type']})\n";
|
||||
}
|
||||
|
||||
// Contar registos
|
||||
$stmt = $pdo->query("SELECT COUNT(*) as count FROM advertising_creatives");
|
||||
$count = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
echo "📈 Total de registos: {$count['count']}\n";
|
||||
}
|
||||
|
||||
// Verificar outras tabelas relacionadas
|
||||
$tables = ['redirects', 'redirect_stats', 'redirect_filters'];
|
||||
foreach ($tables as $table) {
|
||||
$stmt = $pdo->query("SHOW TABLES LIKE '$table'");
|
||||
$exists = $stmt->rowCount() > 0;
|
||||
echo "📋 Tabela $table: " . ($exists ? "✅ EXISTE" : "❌ NÃO EXISTE") . "\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro: " . $e->getMessage() . "\n";
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
<?php
|
||||
// Script para popular analytics_slug nos redirects existentes usando CUID2
|
||||
require_once 'config.php';
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Modules\Redirects\Models\RedirectModel;
|
||||
|
||||
try {
|
||||
$db = DatabaseManager::getInstance();
|
||||
$model = new RedirectModel();
|
||||
|
||||
echo "🚀 Populando analytics_slug nos redirects existentes...\n\n";
|
||||
|
||||
// Buscar todos os redirects que não têm analytics_slug
|
||||
$redirects = $db->fetchAll("
|
||||
SELECT id, name, cuid, analytics_slug
|
||||
FROM redirects
|
||||
WHERE status >= 0 AND (analytics_slug IS NULL OR analytics_slug = '')
|
||||
");
|
||||
|
||||
echo "📋 Encontrados " . count($redirects) . " redirects sem analytics_slug\n";
|
||||
|
||||
$updated = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($redirects as $redirect) {
|
||||
try {
|
||||
// Gerar analytics_slug único usando CUID2
|
||||
$analyticsSlug = (string) new \Visus\Cuid2\Cuid2();
|
||||
|
||||
// Verificar se já existe (muito improvável com CUID2, mas por segurança)
|
||||
$exists = $db->fetch(
|
||||
"SELECT COUNT(*) as count FROM redirects WHERE analytics_slug = ?",
|
||||
[$analyticsSlug]
|
||||
);
|
||||
|
||||
if (($exists['count'] ?? 0) > 0) {
|
||||
echo "⚠️ Analytics slug duplicado detectado, gerando novo...\n";
|
||||
$analyticsSlug = (string) new \Visus\Cuid2\Cuid2();
|
||||
}
|
||||
|
||||
// Atualizar no banco
|
||||
$result = $db->query(
|
||||
"UPDATE redirects SET analytics_slug = ? WHERE id = ?",
|
||||
[$analyticsSlug, $redirect['id']]
|
||||
);
|
||||
|
||||
if ($result > 0) {
|
||||
echo "✅ Redirect {$redirect['id']} ({$redirect['name']}) - analytics_slug: {$analyticsSlug}\n";
|
||||
$updated++;
|
||||
} else {
|
||||
echo "❌ Falha ao atualizar redirect {$redirect['id']}\n";
|
||||
$errors++;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro no redirect {$redirect['id']}: " . $e->getMessage() . "\n";
|
||||
$errors++;
|
||||
}
|
||||
}
|
||||
|
||||
echo "\n🎉 Processo concluído!\n";
|
||||
echo "📊 {$updated} redirects atualizados com analytics_slug\n";
|
||||
if ($errors > 0) {
|
||||
echo "⚠️ {$errors} erros encontrados\n";
|
||||
}
|
||||
|
||||
// Verificar resultado final
|
||||
$total = $db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
|
||||
$withSlug = $db->fetch("SELECT COUNT(*) as count FROM redirects WHERE status >= 0 AND analytics_slug IS NOT NULL AND analytics_slug != ''");
|
||||
|
||||
echo "📈 Total de redirects: {$total['count']}\n";
|
||||
echo "📈 Com analytics_slug: {$withSlug['count']}\n";
|
||||
|
||||
if ($total['count'] == $withSlug['count']) {
|
||||
echo "✅ Todos os redirects têm analytics_slug!\n";
|
||||
} else {
|
||||
echo "⚠️ Ainda há redirects sem analytics_slug\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro geral: " . $e->getMessage() . "\n";
|
||||
echo "Stack trace: " . $e->getTraceAsString() . "\n";
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
<?php
|
||||
// Script simples para popular analytics_slug (sem autoloader)
|
||||
require_once 'config.php';
|
||||
|
||||
// Configuração de base de dados
|
||||
$host = 'localhost';
|
||||
$dbname = 'moneyflix_crm';
|
||||
$username = 'root';
|
||||
$password = '';
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
echo "🚀 Populando analytics_slug nos redirects existentes...\n\n";
|
||||
|
||||
// Buscar todos os redirects que não têm analytics_slug
|
||||
$stmt = $pdo->prepare("
|
||||
SELECT id, name, cuid, analytics_slug
|
||||
FROM redirects
|
||||
WHERE status >= 0 AND (analytics_slug IS NULL OR analytics_slug = '')
|
||||
");
|
||||
$stmt->execute();
|
||||
$redirects = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📋 Encontrados " . count($redirects) . " redirects sem analytics_slug\n";
|
||||
|
||||
$updated = 0;
|
||||
$errors = 0;
|
||||
|
||||
foreach ($redirects as $redirect) {
|
||||
try {
|
||||
// Gerar analytics_slug único usando CUID2
|
||||
$analyticsSlug = generateCuid2();
|
||||
|
||||
// Verificar se já existe (muito improvável com CUID2, mas por segurança)
|
||||
$checkStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE analytics_slug = ?");
|
||||
$checkStmt->execute([$analyticsSlug]);
|
||||
$exists = $checkStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (($exists['count'] ?? 0) > 0) {
|
||||
echo "⚠️ Analytics slug duplicado detectado, gerando novo...\n";
|
||||
$analyticsSlug = generateCuid2();
|
||||
}
|
||||
|
||||
// Atualizar no banco
|
||||
$updateStmt = $pdo->prepare("UPDATE redirects SET analytics_slug = ? WHERE id = ?");
|
||||
$result = $updateStmt->execute([$analyticsSlug, $redirect['id']]);
|
||||
|
||||
if ($result) {
|
||||
echo "✅ Redirect {$redirect['id']} ({$redirect['name']}) - analytics_slug: {$analyticsSlug}\n";
|
||||
$updated++;
|
||||
} else {
|
||||
echo "❌ Falha ao atualizar redirect {$redirect['id']}\n";
|
||||
$errors++;
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro no redirect {$redirect['id']}: " . $e->getMessage() . "\n";
|
||||
$errors++;
|
||||
}
|
||||
}
|
||||
|
||||
echo "\n🎉 Processo concluído!\n";
|
||||
echo "📊 {$updated} redirects atualizados com analytics_slug\n";
|
||||
if ($errors > 0) {
|
||||
echo "⚠️ {$errors} erros encontrados\n";
|
||||
}
|
||||
|
||||
// Verificar resultado final
|
||||
$totalStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE status >= 0");
|
||||
$totalStmt->execute();
|
||||
$total = $totalStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
$withSlugStmt = $pdo->prepare("SELECT COUNT(*) as count FROM redirects WHERE status >= 0 AND analytics_slug IS NOT NULL AND analytics_slug != ''");
|
||||
$withSlugStmt->execute();
|
||||
$withSlug = $withSlugStmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📈 Total de redirects: {$total['count']}\n";
|
||||
echo "📈 Com analytics_slug: {$withSlug['count']}\n";
|
||||
|
||||
if ($total['count'] == $withSlug['count']) {
|
||||
echo "✅ Todos os redirects têm analytics_slug!\n";
|
||||
} else {
|
||||
echo "⚠️ Ainda há redirects sem analytics_slug\n";
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro geral: " . $e->getMessage() . "\n";
|
||||
}
|
||||
|
||||
function generateCuid2(): string
|
||||
{
|
||||
// Função que simula CUID2 (25 caracteres alfanuméricos)
|
||||
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
|
||||
$cuid = '';
|
||||
|
||||
// Gerar 25 caracteres (tamanho padrão do CUID2)
|
||||
for ($i = 0; $i < 25; $i++) {
|
||||
$cuid .= $characters[random_int(0, strlen($characters) - 1)];
|
||||
}
|
||||
|
||||
return $cuid;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
// Script para testar se analytics_slug está a ser carregado
|
||||
$host = 'localhost';
|
||||
$port = 3306;
|
||||
$dbname = 'redirects_moneyflix';
|
||||
$username = 'redirects_user';
|
||||
$password = 'mf_redirect_2025';
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4", $username, $password);
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
|
||||
echo "🔍 Testando analytics_slug nos redirects...\n\n";
|
||||
|
||||
// Buscar alguns redirects com analytics_slug
|
||||
$stmt = $pdo->prepare("
|
||||
SELECT id, name, cuid, analytics_slug
|
||||
FROM redirects
|
||||
WHERE status >= 0
|
||||
ORDER BY id DESC
|
||||
LIMIT 5
|
||||
");
|
||||
$stmt->execute();
|
||||
$redirects = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📋 Redirects encontrados:\n";
|
||||
foreach ($redirects as $redirect) {
|
||||
echo "ID: {$redirect['id']}\n";
|
||||
echo "Nome: {$redirect['name']}\n";
|
||||
echo "CUID: {$redirect['cuid']}\n";
|
||||
echo "Analytics Slug: " . ($redirect['analytics_slug'] ?: 'NULL') . "\n";
|
||||
echo "---\n";
|
||||
}
|
||||
|
||||
// Verificar se há redirects sem analytics_slug
|
||||
$stmt = $pdo->prepare("
|
||||
SELECT COUNT(*) as count
|
||||
FROM redirects
|
||||
WHERE status >= 0 AND (analytics_slug IS NULL OR analytics_slug = '')
|
||||
");
|
||||
$stmt->execute();
|
||||
$result = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
echo "📊 Redirects sem analytics_slug: {$result['count']}\n";
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro: " . $e->getMessage() . "\n";
|
||||
}
|
||||
Reference in new issue
Block a user