diff --git a/crm/Core/Database/Migrations/AddAnalyticsSlugToRedirects.php b/crm/Core/Database/Migrations/AddAnalyticsSlugToRedirects.php
new file mode 100644
index 0000000..6b8cdb6
--- /dev/null
+++ b/crm/Core/Database/Migrations/AddAnalyticsSlugToRedirects.php
@@ -0,0 +1,24 @@
+addColumn('redirects', 'analytics_slug', function($table) {
+ $table->string('analytics_slug', 100)->nullable();
+ });
+
+ // Criar índice único para performance
+ $this->addIndex('redirects', 'idx_analytics_slug', ['analytics_slug']);
+ }
+
+ public function down(): void
+ {
+ $this->dropIndex('redirects', 'idx_analytics_slug');
+ $this->dropColumn('redirects', 'analytics_slug');
+ }
+}
diff --git a/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php
index fdee6f8..0021379 100644
--- a/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php
+++ b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php
@@ -31,3 +31,4 @@ class AddRawRequestToRedirectStats extends Migration
+
diff --git a/crm/Modules/Controllers/PublicCampaignsController.php b/crm/Modules/Controllers/PublicCampaignsController.php
index b7f268f..f6ab8fe 100644
--- a/crm/Modules/Controllers/PublicCampaignsController.php
+++ b/crm/Modules/Controllers/PublicCampaignsController.php
@@ -105,11 +105,11 @@ class PublicCampaignsController extends BaseController
}
/**
- * Get redirect by slug (cuid)
+ * Get redirect by analytics slug
*/
private function getRedirectBySlug(string $slug): ?array
{
- $sql = "SELECT id, name, cuid, target_url, status FROM redirects WHERE cuid = :slug AND status >= 0";
+ $sql = "SELECT id, name, cuid, analytics_slug, target_url, status FROM redirects WHERE analytics_slug = :slug AND status >= 0";
return $this->db->fetch($sql, [':slug' => $slug]);
}
diff --git a/crm/Redirects/Models/RedirectModel.php b/crm/Redirects/Models/RedirectModel.php
index a83b362..9cb023d 100644
--- a/crm/Redirects/Models/RedirectModel.php
+++ b/crm/Redirects/Models/RedirectModel.php
@@ -18,6 +18,7 @@ class RedirectModel
$sql = "SELECT
r.id,
r.cuid,
+ r.analytics_slug,
r.name,
r.source_url,
r.target_url,
@@ -67,6 +68,7 @@ class RedirectModel
$sql = "SELECT
r.id,
r.cuid,
+ r.analytics_slug,
r.name,
r.source_url,
r.target_url,
@@ -103,6 +105,7 @@ class RedirectModel
$sql = "SELECT
r.id,
r.cuid,
+ r.analytics_slug,
r.name,
r.source_url,
r.target_url,
@@ -136,17 +139,19 @@ class RedirectModel
public function create(array $data): bool
{
$cuid = $this->generateCuid();
+ $analyticsSlug = $this->generateAnalyticsSlug();
$sql = "INSERT INTO redirects (
- cuid, name, source_url, target_url, fallback_url,
+ cuid, analytics_slug, name, source_url, target_url, fallback_url,
status, redirect_type, tracking_enabled, max_clicks,
expires_at, created_by
) VALUES (
- ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$params = [
$cuid,
+ $analyticsSlug,
$data['name'] ?? '',
$data['source_url'] ?? '',
$data['target_url'] ?? '',
@@ -332,4 +337,10 @@ class RedirectModel
{
return (string) new \Visus\Cuid2\Cuid2();
}
+
+ private function generateAnalyticsSlug(): string
+ {
+ // Usar cuid2 para gerar slug único para analytics (diferente do cuid principal)
+ return (string) new \Visus\Cuid2\Cuid2();
+ }
}
\ No newline at end of file
diff --git a/crm/Redirects/Views/dashboard.php b/crm/Redirects/Views/dashboard.php
index 54881cf..c7f51f4 100644
--- a/crm/Redirects/Views/dashboard.php
+++ b/crm/Redirects/Views/dashboard.php
@@ -197,6 +197,7 @@
diff --git a/crm/Redirects/Views/redirects/index.php b/crm/Redirects/Views/redirects/index.php
index b22219b..bbe37e2 100644
--- a/crm/Redirects/Views/redirects/index.php
+++ b/crm/Redirects/Views/redirects/index.php
@@ -134,6 +134,7 @@
Ver
Editar
Testar
+ Analytics Público
Apagar
diff --git a/crm/populate_analytics_slugs.php b/crm/populate_analytics_slugs.php
new file mode 100644
index 0000000..a661208
--- /dev/null
+++ b/crm/populate_analytics_slugs.php
@@ -0,0 +1,84 @@
+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";
+}
diff --git a/crm/populate_simple.php b/crm/populate_simple.php
new file mode 100644
index 0000000..f7eaa70
--- /dev/null
+++ b/crm/populate_simple.php
@@ -0,0 +1,104 @@
+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;
+}