- 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
910 lines
36 KiB
PHP
910 lines
36 KiB
PHP
<?php
|
|
namespace App\Modules\Advertising\Controllers\Api;
|
|
|
|
use App\Core\BaseController;
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
use App\Core\Sanitize;
|
|
use App\Core\InputSanitizer;
|
|
use App\Core\Auth;
|
|
use App\Modules\Advertising\Models\BrandModel;
|
|
use App\Modules\Advertising\Models\LandingTypeModel;
|
|
use App\Modules\Advertising\Services\AdvertisingActivityLogger;
|
|
use Exception;
|
|
use Visus\Cuid2\Cuid2;
|
|
|
|
class CampaignApiController extends BaseController
|
|
{
|
|
public function __construct()
|
|
{
|
|
parent::__construct('Advertising');
|
|
}
|
|
|
|
/**
|
|
* List all campaigns with pagination
|
|
*/
|
|
public function index(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
// Parâmetros de paginação
|
|
$page = max(1, InputSanitizer::integer('page', 'GET', 1));
|
|
$perPage = max(1, min(100, InputSanitizer::integer('per_page', 'GET', 20)));
|
|
$offset = ($page - 1) * $perPage;
|
|
|
|
// Parâmetros de filtro
|
|
$search = InputSanitizer::get('search', 'GET', '');
|
|
$status = InputSanitizer::get('status', 'GET', '');
|
|
$type = InputSanitizer::get('type', 'GET', '');
|
|
$budgetType = InputSanitizer::get('budget_type', 'GET', '');
|
|
$dateRange = InputSanitizer::get('date_range', 'GET', '');
|
|
$hasEndDate = InputSanitizer::get('has_end_date', 'GET', '');
|
|
$createdBy = InputSanitizer::get('created_by', 'GET', '');
|
|
$minBudget = InputSanitizer::get('min_budget', 'GET', '');
|
|
$maxBudget = InputSanitizer::get('max_budget', 'GET', '');
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Construir query base
|
|
$whereConditions = [];
|
|
$params = [];
|
|
|
|
// Adicionar filtros
|
|
if (!empty($search)) {
|
|
$whereConditions[] = "(name LIKE ? OR description LIKE ?)";
|
|
$searchTerm = '%' . $search . '%';
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
}
|
|
|
|
if (!empty($status)) {
|
|
$whereConditions[] = "status = ?";
|
|
$params[] = $status;
|
|
}
|
|
|
|
if (!empty($type)) {
|
|
$whereConditions[] = "type = ?";
|
|
$params[] = $type;
|
|
}
|
|
|
|
if (!empty($budgetType)) {
|
|
$whereConditions[] = "budget_type = ?";
|
|
$params[] = $budgetType;
|
|
}
|
|
|
|
if (!empty($hasEndDate)) {
|
|
if ($hasEndDate === 'yes') {
|
|
$whereConditions[] = "end_date IS NOT NULL";
|
|
} elseif ($hasEndDate === 'no') {
|
|
$whereConditions[] = "end_date IS NULL";
|
|
}
|
|
}
|
|
|
|
if (!empty($createdBy)) {
|
|
$whereConditions[] = "created_by = ?";
|
|
$params[] = $createdBy;
|
|
}
|
|
|
|
if (!empty($minBudget)) {
|
|
$whereConditions[] = "budget >= ?";
|
|
$params[] = (float)$minBudget;
|
|
}
|
|
|
|
if (!empty($maxBudget)) {
|
|
$whereConditions[] = "budget <= ?";
|
|
$params[] = (float)$maxBudget;
|
|
}
|
|
|
|
// Filtro por período de criação
|
|
if (!empty($dateRange)) {
|
|
$today = date('Y-m-d');
|
|
switch ($dateRange) {
|
|
case 'today':
|
|
$whereConditions[] = "DATE(created_at) = ?";
|
|
$params[] = $today;
|
|
break;
|
|
case 'week':
|
|
$whereConditions[] = "created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
|
|
break;
|
|
case 'month':
|
|
$whereConditions[] = "created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
|
|
break;
|
|
case 'quarter':
|
|
$whereConditions[] = "created_at >= DATE_SUB(NOW(), INTERVAL 90 DAY)";
|
|
break;
|
|
case 'year':
|
|
$whereConditions[] = "created_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)";
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Construir WHERE clause
|
|
if (empty($whereConditions)) {
|
|
$whereClause = "1=1"; // Sempre verdadeiro se não há condições
|
|
} else {
|
|
$whereClause = implode(' AND ', $whereConditions);
|
|
}
|
|
|
|
// Query para contar total
|
|
$countSql = "SELECT COUNT(*) as total FROM advertising_campaigns WHERE {$whereClause}";
|
|
$totalResult = $db->fetch($countSql, $params);
|
|
$total = $totalResult['total'] ?? 0;
|
|
|
|
// Query para buscar dados paginados
|
|
$dataSql = "
|
|
SELECT
|
|
c.id AS campaign_id,
|
|
c.name AS campaign_name,
|
|
c.description AS campaign_description,
|
|
c.status AS campaign_status,
|
|
c.type AS campaign_type,
|
|
c.budget AS campaign_budget,
|
|
c.start_date AS start_date,
|
|
c.end_date AS end_date,
|
|
|
|
c.site_group_id AS site_group_id,
|
|
c.created_at AS created_date,
|
|
c.updated_at AS updated_date
|
|
FROM
|
|
advertising_campaigns c
|
|
WHERE
|
|
{$whereClause}
|
|
ORDER BY
|
|
c.created_at DESC
|
|
LIMIT {$perPage} OFFSET {$offset}
|
|
";
|
|
$campaigns = $db->fetchAll($dataSql, $params);
|
|
|
|
// Calcular informações de paginação
|
|
$totalPages = ceil($total / $perPage);
|
|
$hasNextPage = $page < $totalPages;
|
|
$hasPrevPage = $page > 1;
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $campaigns,
|
|
'pagination' => [
|
|
'current_page' => $page,
|
|
'per_page' => $perPage,
|
|
'total' => $total,
|
|
'total_pages' => $totalPages,
|
|
'has_next_page' => $hasNextPage,
|
|
'has_prev_page' => $hasPrevPage,
|
|
'next_page' => $hasNextPage ? $page + 1 : null,
|
|
'prev_page' => $hasPrevPage ? $page - 1 : null
|
|
]
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_index']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao buscar campanhas']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get distinct campaign types from database (no hardcoded values)
|
|
*/
|
|
public function types(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
$db = DatabaseManager::getInstance();
|
|
$types = $db->fetchAll(
|
|
"SELECT DISTINCT type AS campaign_type
|
|
FROM advertising_campaigns
|
|
WHERE type IS NOT NULL AND type != '' AND status >= 0
|
|
ORDER BY campaign_type"
|
|
) ?: [];
|
|
echo json_encode(['success' => true, 'data' => $types]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_types']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter tipos de campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get single campaign
|
|
*/
|
|
public function show(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
// Verificar se campanha existe
|
|
$campaign = $db->fetch("SELECT id, name, status, start_date, end_date, created_by, created_at, updated_at FROM advertising_campaigns WHERE id = ?", [$id]);
|
|
|
|
if (empty($campaign)) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $campaign
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_show', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao buscar campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create campaign
|
|
*/
|
|
public function create(): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
// Validar dados obrigatórios
|
|
if (empty($input['name'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Nome é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
// Obter o usuário logado
|
|
$userId = Auth::id();
|
|
if (!$userId) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Buscar o alias da equipa do usuário
|
|
$userInfo = $db->fetch("
|
|
SELECT 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 = ?
|
|
", [$userId]);
|
|
|
|
// Validar se tem equipa
|
|
if (empty($userInfo['team_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Usuário não está associado a nenhuma equipa']);
|
|
return;
|
|
}
|
|
|
|
// Obter próximo número de campanha para esta equipa/usuário
|
|
$result = $db->fetch(
|
|
"SELECT get_next_campaign_number(?, ?) as next_number",
|
|
[$userInfo['team_id'], $userId]
|
|
);
|
|
$campaignNumber = $result['next_number'];
|
|
|
|
// Montar o alias no formato TT-PA-XXX
|
|
$teamAlias = $userInfo['team_alias'] ?? 'XX';
|
|
$userAlias = $userInfo['user_alias'] ?? 'XX';
|
|
$formattedNumber = str_pad((string)$campaignNumber, 3, '0', STR_PAD_LEFT);
|
|
$fullAlias = "{$teamAlias}-{$userAlias}-{$formattedNumber}";
|
|
|
|
// Gerar CUID único
|
|
$cuid = $this->generateCuid();
|
|
|
|
// Sanitizar dados
|
|
$campaignData = [
|
|
'cuid' => $cuid,
|
|
'name' => Sanitize::string($input['name']),
|
|
'status' => Sanitize::string($input['status'] ?? 'active'),
|
|
'start_date' => Sanitize::date($input['start_date'] ?? date('Y-m-d')),
|
|
'end_date' => !empty($input['end_date']) ? Sanitize::date($input['end_date']) : null,
|
|
'created_by' => $userId,
|
|
'created_at' => date('Y-m-d H:i:s')
|
|
];
|
|
|
|
$id = $db->insert('advertising_campaigns', $campaignData);
|
|
|
|
// Log de atividade
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('create', 'campaign', (int)$id, $userId, 'Campanha criada', [
|
|
'name' => $campaignData['name']
|
|
]);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Campanha criada com sucesso',
|
|
'data' => ['id' => $id]
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_create']);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao criar campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update campaign
|
|
*/
|
|
public function update(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se campanha existe
|
|
$campaign = $db->fetch("SELECT id, name, status, start_date, end_date, has_end_date, created_by, created_at, updated_at FROM advertising_campaigns WHERE id = ?", [$id]);
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
// Obter o usuário logado
|
|
$userId = Auth::id();
|
|
if (!$userId) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']);
|
|
return;
|
|
}
|
|
|
|
// O alias não deve ser alterado após criação
|
|
// Remover alias dos dados de atualização
|
|
|
|
// Sanitizar dados (remover alias do input, sempre manter o original)
|
|
$campaignData = [
|
|
'name' => Sanitize::string($input['name'] ?? $campaign['name']),
|
|
'status' => (int)($input['status'] ?? $campaign['status']), // Status é inteiro, não string
|
|
'start_date' => Sanitize::date($input['start_date'] ?? $campaign['start_date']),
|
|
'end_date' => !empty($input['end_date']) ? Sanitize::date($input['end_date']) : null,
|
|
'updated_at' => date('Y-m-d H:i:s')
|
|
];
|
|
|
|
$db->update('advertising_campaigns', $campaignData, ['id' => $id]);
|
|
|
|
// Log de atividade
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('update', 'campaign', (int)$id, $userId, 'Campanha atualizada', [
|
|
'fields' => array_keys($campaignData)
|
|
]);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Campanha atualizada com sucesso'
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_update', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Delete campaign
|
|
*/
|
|
public function destroy(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se campanha existe
|
|
$campaign = $db->fetch("SELECT id, name FROM advertising_campaigns WHERE id = ?", [$id]);
|
|
if (!$campaign) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
// Obter o usuário logado
|
|
$userId = Auth::id();
|
|
if (!$userId) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']);
|
|
return;
|
|
}
|
|
|
|
// Soft delete (marcar como eliminada)
|
|
$db->query("UPDATE advertising_campaigns SET status = -1, updated_at = CURRENT_TIMESTAMP WHERE id = ?", [$id]);
|
|
|
|
// Log de atividade (com try/catch separado para não falhar o delete)
|
|
try {
|
|
$activityLogger = $this->resolveModuleService('service.AdvertisingActivityLogger');
|
|
$activityLogger::log('delete', 'campaign', (int)$id, $userId, 'Campanha eliminada', [
|
|
'name' => $campaign['name']
|
|
]);
|
|
} catch (\Exception $logError) {
|
|
// Se o log falhar, não falhar o delete
|
|
error_log("Erro no log de atividade: " . $logError->getMessage());
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Campanha eliminada com sucesso'
|
|
]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_destroy', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao eliminar campanha'
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get campaign trackers
|
|
*/
|
|
public function getTrackers(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
if ($id <= 0) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID inválido']);
|
|
return;
|
|
}
|
|
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Verificar se a campanha existe
|
|
$campaign = $db->fetchAll('SELECT id FROM advertising_campaigns WHERE id = ?', [$id]);
|
|
if (empty($campaign)) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
// Buscar trackers da campanha
|
|
$trackers = $db->fetchAll(
|
|
"SELECT
|
|
t.id,
|
|
t.name,
|
|
t.is_active,
|
|
t.brand_id,
|
|
t.landing_type_id,
|
|
ct.format_id,
|
|
ct.country as countries,
|
|
ct.order_position
|
|
FROM advertising_campaign_trackers ct
|
|
JOIN advertising_trackers t ON t.id = ct.tracker_id
|
|
WHERE ct.campaign_id = ?
|
|
ORDER BY ct.order_position ASC",
|
|
[$id]
|
|
);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $trackers
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'advertising_campaign_api_get_trackers', 'id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao buscar trackers']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update trackers for a campaign
|
|
*/
|
|
public function updateTrackers(int $id): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
try {
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$trackers = $input['trackers'] ?? [];
|
|
|
|
// Obter o usuário logado
|
|
$userId = Auth::id();
|
|
if (!$userId) {
|
|
http_response_code(401);
|
|
echo json_encode(['success' => false, 'message' => 'Utilizador não autenticado']);
|
|
return;
|
|
}
|
|
|
|
// Log de atividade para atualização de trackers
|
|
AdvertisingActivityLogger::log('update', 'trackers', (int)$id, $userId, 'Trackers atualizados', [
|
|
'count' => count($trackers),
|
|
'campaign_id' => $id
|
|
]);
|
|
|
|
if (!isset($input['trackers']) || !is_array($input['trackers'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
// Verificar se a campanha existe
|
|
$db = DatabaseManager::getInstance();
|
|
$campaign = $db->fetchAll('SELECT id FROM advertising_campaigns WHERE id = ?', [$id]);
|
|
if (empty($campaign)) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Campanha não encontrada']);
|
|
return;
|
|
}
|
|
|
|
$db->transaction(function($dbTrans) use ($id, $input, $userId) {
|
|
// Obter trackers existentes
|
|
$existingTrackers = $dbTrans->fetchAll(
|
|
"SELECT tracker_id FROM advertising_campaign_trackers WHERE campaign_id = ?",
|
|
[$id]
|
|
);
|
|
$existingTrackers = array_column($existingTrackers, 'tracker_id');
|
|
|
|
$processedTrackers = [];
|
|
|
|
foreach ($input['trackers'] as $trackerData) {
|
|
if (empty($trackerData['id']) || strpos($trackerData['id'], 'new_') === 0) {
|
|
// Criar novo tracker
|
|
$trackerInsertData = [
|
|
'cuid' => (string) new \Visus\Cuid2\Cuid2(),
|
|
'name' => $trackerData['name'],
|
|
'format_id' => $trackerData['format_id'] ?? 1,
|
|
'brand_id' => $trackerData['brand_id'] ?? null,
|
|
'landing_type_id' => $trackerData['landing_type_id'] ?? null,
|
|
'tracking_url' => $trackerData['tracking_url'] ?? null,
|
|
'is_active' => $trackerData['is_active'] ?? 1,
|
|
'created_at' => date('Y-m-d H:i:s')
|
|
];
|
|
|
|
$trackerId = $dbTrans->insert('advertising_trackers', $trackerInsertData);
|
|
|
|
// Log de atividade para criação de tracker
|
|
AdvertisingActivityLogger::log('create', 'tracker', (int)$trackerId, $userId, 'Tracker criado', [
|
|
'name' => $trackerData['name'],
|
|
'campaign_id' => $id
|
|
]);
|
|
|
|
// Adicionar à campanha
|
|
$dbTrans->insert('advertising_campaign_trackers', [
|
|
'campaign_id' => $id,
|
|
'tracker_id' => $trackerId,
|
|
'format_id' => $trackerData['format_id'] ?? 1,
|
|
'country' => is_array($trackerData['countries']) ? implode(',', $trackerData['countries']) : ($trackerData['countries'] ?? 'AA'),
|
|
'order_position' => $trackerData['order'] ?? 0
|
|
]);
|
|
|
|
} else {
|
|
// Atualizar tracker existente
|
|
$trackerId = (int)$trackerData['id'];
|
|
|
|
$dbTrans->update('advertising_trackers', [
|
|
'name' => $trackerData['name'],
|
|
'is_active' => $trackerData['is_active'] ?? 1,
|
|
'brand_id' => $trackerData['brand_id'] ?? null,
|
|
'landing_type_id' => $trackerData['landing_type_id'] ?? null
|
|
], ['id' => $trackerId]);
|
|
|
|
// Atualizar relação
|
|
$dbTrans->update('advertising_campaign_trackers', [
|
|
'format_id' => $trackerData['format_id'] ?? 1,
|
|
'country' => is_array($trackerData['countries']) ? implode(',', $trackerData['countries']) : ($trackerData['countries'] ?? 'AA'),
|
|
'order_position' => $trackerData['order'] ?? 0
|
|
], [
|
|
'campaign_id' => $id,
|
|
'tracker_id' => $trackerId
|
|
]);
|
|
}
|
|
|
|
$processedTrackers[] = $trackerId;
|
|
}
|
|
|
|
// Soft delete trackers que não estão mais na lista
|
|
$trackersToRemove = array_diff($existingTrackers, $processedTrackers);
|
|
if (!empty($trackersToRemove)) {
|
|
$placeholders = str_repeat('?,', count($trackersToRemove) - 1) . '?';
|
|
|
|
// Soft delete da relação
|
|
$dbTrans->query(
|
|
"UPDATE advertising_campaign_trackers
|
|
SET status = '-1', updated_at = CURRENT_TIMESTAMP
|
|
WHERE campaign_id = ? AND tracker_id IN ($placeholders)",
|
|
array_merge([$id], $trackersToRemove)
|
|
);
|
|
|
|
// Soft delete trackers órfãos
|
|
$dbTrans->query(
|
|
"UPDATE advertising_trackers
|
|
SET status = '-1', updated_at = CURRENT_TIMESTAMP
|
|
WHERE id IN ($placeholders)
|
|
AND id NOT IN (SELECT DISTINCT tracker_id FROM advertising_campaign_trackers WHERE status >= 0)",
|
|
$trackersToRemove
|
|
);
|
|
}
|
|
});
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Trackers atualizados com sucesso'
|
|
]);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar trackers']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all active brands
|
|
*/
|
|
public function getBrands(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
|
|
$brandModel = new BrandModel();
|
|
$brands = $brandModel->getActiveBrands();
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $brands
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Get landing types for a brand
|
|
*/
|
|
public function getLandingTypes(string $brandId): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
error_log('[CampaignApiController] getLandingTypes called with brandId=' . $brandId);
|
|
|
|
try {
|
|
$landingTypeModel = new LandingTypeModel();
|
|
$landingTypes = $landingTypeModel->getByBrandId((int)$brandId);
|
|
error_log('[CampaignApiController] landingTypes result: ' . json_encode($landingTypes));
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $landingTypes
|
|
]);
|
|
} catch (\Exception $e) {
|
|
error_log('[CampaignApiController] Error in getLandingTypes: ' . $e->getMessage());
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'Erro ao buscar landing types: ' . $e->getMessage()
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Endpoint para eventos de atividade
|
|
*/
|
|
public function activityLog(): void
|
|
{
|
|
header('Content-Type: application/json');
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
$events = $db->fetchAll(
|
|
"SELECT\n+ id, cuid, event_type, entity_type, entity_id, user_id, description, created_at\n+ FROM advertising_activity_log\n+ ORDER BY created_at DESC\n+ LIMIT 10"
|
|
);
|
|
echo json_encode(['success' => true, 'data' => $events]);
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao buscar eventos de atividade']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Generate CUID
|
|
*/
|
|
private function generateCuid(): string
|
|
{
|
|
return (string) new Cuid2();
|
|
}
|
|
|
|
// ===== CAMPAIGN DOMAINS MANAGEMENT =====
|
|
|
|
/**
|
|
* Get domains associated with a campaign
|
|
*/
|
|
public function getCampaignDomains(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$campaignDomainsService = new \App\Modules\Advertising\Services\CampaignDomainsService();
|
|
$domains = $campaignDomainsService->getCampaignDomains($id);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $domains,
|
|
'message' => 'Domínios da campanha obtidos com sucesso'
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'campaign_domains_get', 'campaign_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter domínios da campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get available domains for a campaign (from its site group)
|
|
*/
|
|
public function getAvailableDomains(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$campaignDomainsService = new \App\Modules\Advertising\Services\CampaignDomainsService();
|
|
$domains = $campaignDomainsService->getAvailableDomainsForCampaign($id);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'data' => $domains,
|
|
'message' => 'Domínios disponíveis obtidos com sucesso'
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'campaign_available_domains', 'campaign_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao obter domínios disponíveis']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Associate a domain with a campaign
|
|
*/
|
|
public function associateDomain(int $id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
if (empty($input['site_domain_id'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'ID do domínio é obrigatório']);
|
|
return;
|
|
}
|
|
|
|
$campaignDomainsService = new \App\Modules\Advertising\Services\CampaignDomainsService();
|
|
$targetingSettings = $input['targeting_settings'] ?? [];
|
|
|
|
$success = $campaignDomainsService->associateDomainToCampaign(
|
|
$id,
|
|
(int)$input['site_domain_id'],
|
|
$targetingSettings
|
|
);
|
|
|
|
if ($success) {
|
|
// Log activity
|
|
AdvertisingActivityLogger::log('associate', 'campaign_domain', $id, Auth::id() ?? 1,
|
|
'Domínio associado à campanha', [
|
|
'site_domain_id' => $input['site_domain_id'],
|
|
'targeting_settings' => $targetingSettings
|
|
]
|
|
);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Domínio associado à campanha com sucesso'
|
|
]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao associar domínio à campanha']);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'campaign_associate_domain', 'campaign_id' => $id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao associar domínio à campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove domain association from campaign
|
|
*/
|
|
public function dissociateDomain(int $id, int $domain_id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$campaignDomainsService = new \App\Modules\Advertising\Services\CampaignDomainsService();
|
|
$success = $campaignDomainsService->dissociateDomainFromCampaign($id, $domain_id);
|
|
|
|
if ($success) {
|
|
// Log activity
|
|
AdvertisingActivityLogger::log('dissociate', 'campaign_domain', $id, Auth::id() ?? 1,
|
|
'Domínio removido da campanha', [
|
|
'site_domain_id' => $domain_id
|
|
]
|
|
);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Domínio removido da campanha com sucesso'
|
|
]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao remover domínio da campanha']);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'campaign_dissociate_domain', 'campaign_id' => $id, 'domain_id' => $domain_id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao remover domínio da campanha']);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update targeting settings for a campaign domain association
|
|
*/
|
|
public function updateDomainTargeting(int $id, int $domain_id): void
|
|
{
|
|
try {
|
|
header('Content-Type: application/json');
|
|
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
if (!$input) {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Dados inválidos']);
|
|
return;
|
|
}
|
|
|
|
$targetingSettings = $input['targeting_settings'] ?? [];
|
|
|
|
$campaignDomainsService = new \App\Modules\Advertising\Services\CampaignDomainsService();
|
|
$success = $campaignDomainsService->updateTargetingSettings($id, $domain_id, $targetingSettings);
|
|
|
|
if ($success) {
|
|
// Log activity
|
|
AdvertisingActivityLogger::log('update', 'campaign_domain', $id, Auth::id() ?? 1,
|
|
'Configurações de targeting atualizadas', [
|
|
'site_domain_id' => $domain_id,
|
|
'targeting_settings' => $targetingSettings
|
|
]
|
|
);
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => 'Configurações de targeting atualizadas com sucesso'
|
|
]);
|
|
} else {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar configurações de targeting']);
|
|
}
|
|
|
|
} catch (Exception $e) {
|
|
ErrorReporter::report($e, ['context' => 'campaign_update_domain_targeting', 'campaign_id' => $id, 'domain_id' => $domain_id]);
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Erro ao atualizar configurações de targeting']);
|
|
}
|
|
}
|
|
}
|