- Fix storage permissions to use 'www' user instead of 'www-data' - Fix UserModel getAllForAdmin query to avoid placeholders in LIMIT/OFFSET - Import missing modules: Advertising, Dashboard, Analytics - Update deploy script to copy files to public directory
153 lines
4.8 KiB
PHP
153 lines
4.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Advertising\Services;
|
|
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Auth;
|
|
|
|
class SiteGroupAliasService
|
|
{
|
|
private DatabaseManager $db;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->db = DatabaseManager::getInstance();
|
|
}
|
|
|
|
/**
|
|
* Generate unique alias for site group
|
|
* Format: TT-PA-XXX (Team-User-Number) - Same as campaign matricula logic
|
|
*/
|
|
public function generateUniqueAlias(?int $forUserId = null): string
|
|
{
|
|
try {
|
|
// Get user ID (from parameter or authenticated user)
|
|
$userId = $forUserId ?? Auth::id();
|
|
if (!$userId) {
|
|
throw new \Exception('Utilizador não autenticado');
|
|
}
|
|
|
|
// Get user and team data
|
|
$userData = $this->db->fetch(
|
|
"SELECT u.id, u.user_alias, u.team_id, t.alias as team_alias
|
|
FROM users u
|
|
LEFT JOIN teams t ON u.team_id = t.id
|
|
WHERE u.id = ? AND u.is_active = 1",
|
|
[$userId]
|
|
);
|
|
|
|
if (!$userData) {
|
|
throw new \Exception('Dados do utilizador não encontrados');
|
|
}
|
|
|
|
$teamAlias = $userData['team_alias'] ?? 'XX';
|
|
$userAlias = $userData['user_alias'] ?? 'XX';
|
|
|
|
// Start with count of existing site groups for this user + 1
|
|
$result = $this->db->fetch(
|
|
"SELECT COUNT(*) as total FROM advertising_site_groups WHERE created_by = ? AND deleted_at IS NULL",
|
|
[$userId]
|
|
);
|
|
|
|
$counter = ($result['total'] ?? 0) + 1;
|
|
|
|
// Loop until we find a unique alias
|
|
do {
|
|
$formattedNumber = str_pad((string)$counter, 3, '0', STR_PAD_LEFT);
|
|
$alias = "{$teamAlias}-{$userAlias}-{$formattedNumber}";
|
|
|
|
// Check if this alias already exists
|
|
$existing = $this->db->fetch(
|
|
"SELECT id FROM advertising_site_groups WHERE alias = ? AND deleted_at IS NULL",
|
|
[$alias]
|
|
);
|
|
|
|
if (!$existing) {
|
|
return $alias; // Found unique alias
|
|
}
|
|
|
|
$counter++; // Try next number
|
|
|
|
} while ($counter <= 999); // Safety limit
|
|
|
|
// If we reach here, fallback
|
|
throw new \Exception('Unable to generate unique alias after 999 attempts');
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'site_group_alias_generation',
|
|
'user_id' => Auth::id() ?? null
|
|
]);
|
|
|
|
// Fallback: generate simple sequential alias
|
|
return $this->generateFallbackAlias();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Fallback alias generation if main method fails
|
|
*/
|
|
private function generateFallbackAlias(): string
|
|
{
|
|
try {
|
|
// Simple count-based approach with fallback format
|
|
$result = $this->db->fetch(
|
|
"SELECT COUNT(*) as total FROM advertising_site_groups WHERE deleted_at IS NULL"
|
|
);
|
|
|
|
$count = ($result['total'] ?? 0) + 1;
|
|
$formattedNumber = str_pad((string)$count, 3, '0', STR_PAD_LEFT);
|
|
|
|
// Use XX-XX-XXX format for fallback (unknown team/user)
|
|
return "XX-XX-{$formattedNumber}";
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'site_group_alias_fallback_generation'
|
|
]);
|
|
|
|
// Ultimate fallback
|
|
$timestamp = substr((string)time(), -3);
|
|
return "XX-XX-{$timestamp}";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Validate alias format
|
|
* Accepts both TT-PA-XXX (new format) and SG-XXX (legacy format)
|
|
*/
|
|
public function isValidAlias(string $alias): bool
|
|
{
|
|
// New format: TT-PA-XXX (Team-User-Number)
|
|
if (preg_match('/^[A-Z]{2}-[A-Z0-9]{2}-\d{3}$/', $alias) === 1) {
|
|
return true;
|
|
}
|
|
|
|
// Legacy format: SG-XXX (for backward compatibility)
|
|
if (preg_match('/^SG-\d{3}$/', $alias) === 1) {
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Check if alias is unique
|
|
*/
|
|
public function isAliasUnique(string $alias, ?int $excludeId = null): bool
|
|
{
|
|
$sql = "SELECT id FROM advertising_site_groups WHERE alias = ? AND deleted_at IS NULL";
|
|
$params = [$alias];
|
|
|
|
if ($excludeId) {
|
|
$sql .= " AND id != ?";
|
|
$params[] = $excludeId;
|
|
}
|
|
|
|
$existing = $this->db->fetch($sql, $params);
|
|
return !$existing;
|
|
}
|
|
} |