Files
MoneyFlix/crm/Modules/Advertising/Services/ScriptBuilderIntegrationService.php
T
1sonhador 88a5659fe8 fix: Correct user permissions and UserModel query
- 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
2025-10-15 14:14:00 +01:00

1475 lines
57 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Advertising\Services;
use App\Core\DatabaseManager;
use App\Core\ErrorReporter;
use App\Core\Sanitize;
use App\Modules\Advertising\Models\CampaignModel;
use App\Modules\Advertising\Models\CreativeModel;
use App\Modules\Advertising\Services\MultiBookService;
use Visus\Cuid2\Cuid2;
/**
* Script Builder Integration Service
*
* Handles bidirectional synchronization between Google Sheets,
* CRM Advertising module, and script-builder system.
*/
class ScriptBuilderIntegrationService
{
private DatabaseManager $db;
private GoogleSheetsService $googleSheetsService;
private CampaignModel $campaignModel;
private CreativeModel $creativeModel;
private MultiBookService $multiBookService;
public function __construct()
{
$this->db = DatabaseManager::getInstance();
$this->googleSheetsService = new GoogleSheetsService();
$this->campaignModel = new CampaignModel();
$this->creativeModel = new CreativeModel();
$this->multiBookService = new MultiBookService();
}
/**
* Perform full synchronization from Google Sheets to CRM
*/
public function syncFromGoogleSheets(): array
{
$results = [
'campaigns' => ['imported' => 0, 'updated' => 0, 'errors' => []],
'creatives' => ['imported' => 0, 'updated' => 0, 'errors' => []],
'total_time' => 0,
];
$startTime = microtime(true);
try {
// Allow sync even when Google Sheets is not available (demo mode)
// Sync multibooks and campaigns from SCRIPTS tab
$campaignResults = $this->syncMultiBooksAndCampaignsFromSheets();
$results['campaigns'] = $campaignResults;
// Sync creatives from ROTATOR tab
$creativeResults = $this->syncCreativesFromSheets();
$results['creatives'] = $creativeResults;
// Generate trackers.json for script-builder compatibility
$this->generateTrackersJson();
$results['total_time'] = round(microtime(true) - $startTime, 2);
$results['success'] = true;
return $results;
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'script_builder_integration_sync',
'results' => $results
]);
$results['success'] = false;
$results['error'] = $e->getMessage();
$results['total_time'] = round(microtime(true) - $startTime, 2);
return $results;
}
}
/**
* Sync multibooks and campaigns from Google Sheets SCRIPTS tab
* Each script line = 1 multibook + 1 campaign inside it
*/
private function syncMultiBooksAndCampaignsFromSheets(): array
{
$results = ['imported' => 0, 'updated' => 0, 'errors' => []];
try {
$sheetsCampaigns = $this->googleSheetsService->readCampaignsFromSheets();
foreach ($sheetsCampaigns as $sheetsData) {
try {
if (empty($sheetsData['script_id'])) {
$results['errors'][] = "Script missing script_id: " . ($sheetsData['name'] ?? 'Unknown');
continue;
}
// Step 1: Create or find site group for this script_id
$siteGroup = $this->createOrFindSiteGroup($sheetsData);
if (!$siteGroup) {
$results['errors'][] = "Failed to create site group for script_id: " . $sheetsData['script_id'];
continue;
}
// Step 2: Create or update campaign inside the site group
$existing = $this->findCampaignByScriptId($sheetsData['script_id']);
if ($existing) {
// Update existing campaign
if ($this->shouldUpdateCampaign($existing, $sheetsData)) {
$this->updateCampaignFromSheets($existing['id'], $sheetsData, $siteGroup['id']);
$results['updated']++;
}
} else {
// Create new campaign inside the site group
$this->createCampaignFromSheets($sheetsData, $siteGroup['id']);
$results['imported']++;
}
} catch (\Exception $e) {
$results['errors'][] = "Campaign {$sheetsData['script_id']}: " . $e->getMessage();
ErrorReporter::report($e, [
'context' => 'sync_campaign_from_sheets',
'campaign_data' => $sheetsData
]);
}
}
return $results;
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'sync_campaigns_from_sheets']);
throw $e;
}
}
/**
* Sync creatives from Google Sheets ROTATOR tab
*/
private function syncCreativesFromSheets(): array
{
$results = ['imported' => 0, 'updated' => 0, 'errors' => []];
try {
$sheetsCreatives = $this->googleSheetsService->readCreativesFromSheets();
foreach ($sheetsCreatives as $sheetsData) {
try {
if (empty($sheetsData['creative_slug'])) {
// Use CUID as slug when no specific slug exists
$sheetsData['creative_slug'] = $this->generateCuid();
}
// Check if creative already exists
$existing = $this->findCreativeBySlug($sheetsData['creative_slug']);
if ($existing) {
// Update existing creative
if ($this->shouldUpdateCreative($existing, $sheetsData)) {
$this->updateCreativeFromSheets($existing['id'], $sheetsData);
$results['updated']++;
}
} else {
// Create new creative
$this->createCreativeFromSheets($sheetsData);
$results['imported']++;
}
} catch (\Exception $e) {
$results['errors'][] = "Creative {$sheetsData['creative_slug']}: " . $e->getMessage();
ErrorReporter::report($e, [
'context' => 'sync_creative_from_sheets',
'creative_data' => $sheetsData
]);
}
}
return $results;
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'sync_creatives_from_sheets']);
throw $e;
}
}
/**
* Find campaign by script_id
*/
private function findCampaignByScriptId(string $scriptId): ?array
{
return $this->db->fetch(
"SELECT * FROM advertising_campaigns WHERE script_id = ? AND deleted_at IS NULL",
[$scriptId]
);
}
/**
* Find creative by slug
*/
private function findCreativeBySlug(string $slug): ?array
{
return $this->db->fetch(
"SELECT * FROM advertising_creatives WHERE creative_slug = ? AND deleted_at IS NULL",
[$slug]
);
}
/**
* Create or find multibook for script_id
*/
private function createOrFindSiteGroup(array $sheetsData): ?array
{
try {
// Try to find existing site group by script_id (stored in settings)
$existing = $this->db->fetch(
"SELECT * FROM advertising_site_groups WHERE settings LIKE ? AND deleted_at IS NULL",
['%"script_id":"' . $sheetsData['script_id'] . '"%']
);
if ($existing) {
// If site group exists, update status from Google Sheets and check domains
$statusMap = [
'active' => 'active',
'inactive' => 'inactive',
'pending' => 'pending',
'in preparation' => 'in_preparation',
'ready' => 'ready',
'live' => 'live',
'to do' => 'to_do',
'awaiting creatives' => 'awaiting_creatives',
'created but error' => 'created_but_error',
'n/a' => 'n_a',
'to be retired' => 'to_be_retired',
'retired' => 'retired',
'requires brand change' => 'requires_brand_change',
'requires url change' => 'requires_url_change',
'requires format change' => 'requires_format_change',
'requires cap change' => 'requires_cap_change',
'paused' => 'paused',
'format needs coding' => 'format_needs_coding',
// Legacy mappings for backwards compatibility
'draft' => 'pending',
'archived' => 'inactive'
];
$newStatus = $statusMap[strtolower($sheetsData['Status'] ?? 'active')] ?? 'active';
// Update status if it changed
if ($existing['status'] != $newStatus) {
$this->db->query(
"UPDATE advertising_site_groups SET status = ? WHERE id = ?",
[$newStatus, $existing['id']]
);
$existing['status'] = $newStatus;
}
// Check if we need to update domains for "all" wildcard
$this->processMuFieldForExistingSiteGroup($existing['id'], $sheetsData);
return $existing;
}
// Create new site group
$brand = $sheetsData['brand'] ?? 'Unknown';
$country = $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA'; // Default to AA
// Take first country if multiple
if (strpos($country, ',') !== false) {
$country = trim(explode(',', $country)[0]);
}
// Ensure country is 2 chars
$country = strtoupper(substr($country, 0, 2));
// Get first domain from mu field for site group name
$firstDomain = $this->getFirstDomainFromMu($sheetsData);
$siteGroupName = $firstDomain ? "{$firstDomain} - {$country}" : "{$brand} - {$country}";
// Limit name to 250 characters to avoid database truncation
if (strlen($siteGroupName) > 250) {
$siteGroupName = substr($siteGroupName, 0, 247) . '...';
}
// Generate CUID for site group
$cuid = $this->generateCuid();
// Get user ID for created_by (from agent assignment or default)
$createdBy = $this->mapAgentToUserId($sheetsData['z'] ?? '');
$sql = "INSERT INTO advertising_site_groups (
cuid, name, description, status, settings, created_by, created_at, alias
) VALUES (?, ?, ?, ?, ?, ?, NOW(), ?)
ON DUPLICATE KEY UPDATE
name = VALUES(name),
description = VALUES(description),
status = VALUES(status),
settings = VALUES(settings),
alias = VALUES(alias)";
// Generate proper alias using SiteGroupAliasService
$aliasService = new \App\Modules\Advertising\Services\SiteGroupAliasService();
$alias = $aliasService->generateUniqueAlias($createdBy);
// Map status from Google Sheets (column G)
$customFields = json_decode($sheetsData['custom_fields'] ?? '{}', true) ?: [];
$sheetsStatus = $customFields['Status'] ?? $sheetsData['Status'] ?? 'active';
$statusMap = [
'active' => 'active',
'inactive' => 'inactive',
'pending' => 'pending',
'in preparation' => 'in_preparation',
'ready' => 'ready',
'live' => 'live',
'to do' => 'to_do',
'awaiting creatives' => 'awaiting_creatives',
'created but error' => 'created_but_error',
'n/a' => 'n_a',
'to be retired' => 'to_be_retired',
'retired' => 'retired',
'requires brand change' => 'requires_brand_change',
'requires url change' => 'requires_url_change',
'requires format change' => 'requires_format_change',
'requires cap change' => 'requires_cap_change',
'paused' => 'paused',
'format needs coding' => 'format_needs_coding',
// Legacy mappings for backwards compatibility
'draft' => 'pending',
'archived' => 'inactive'
];
$status = $statusMap[strtolower($sheetsStatus)] ?? 'active';
$params = [
$cuid,
$siteGroupName, // Name: first domain + country
"Site Group para {$firstDomain} no país {$country}", // Description
$status, // Use status from Google Sheets
json_encode([
'google_sheets_sync' => true,
'analytics_token' => $sheetsData['analytics_token'] ?? null,
'campaign_slug' => $sheetsData['campaign_slug'] ?? null,
'brand' => $brand,
'country' => $country,
'first_domain' => $firstDomain,
'script_id' => $sheetsData['script_id'] // Store script_id in settings
]),
$createdBy,
$alias // Use proper TT-PA-XXX format alias
];
$this->db->query($sql, $params);
$siteGroupId = $this->db->lastInsertId();
// Process mu field for new site group
$this->processMuFieldForNewSiteGroup($siteGroupId, $sheetsData);
return [
'id' => $siteGroupId,
'cuid' => $cuid,
'name' => "{$brand} - {$country}",
'alias' => $sheetsData['script_id'],
'status' => 1
];
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'create_site_group_from_sheets',
'script_id' => $sheetsData['script_id'] ?? 'unknown'
]);
return null;
}
}
/**
* Process mu field for new site group - handle "all" wildcard
*/
private function processMuFieldForNewSiteGroup(int $siteGroupId, array $sheetsData): void
{
// Extract mu from custom_fields if not directly available
$mu = $sheetsData['mu'] ?? '';
if (empty($mu) && isset($sheetsData['custom_fields'])) {
$customFields = json_decode($sheetsData['custom_fields'], true);
$mu = $customFields['mu'] ?? '';
}
if (empty($mu)) {
return;
}
// Split by line breaks to get individual domains
$domains = preg_split('/\r?\n/', trim($mu));
foreach ($domains as $domain) {
$domain = trim($domain);
if (empty($domain)) {
continue;
}
// Check if this is "all" wildcard
if (strtoupper($domain) === 'ALL') {
$this->addAllDomainsToSiteGroup($siteGroupId, $sheetsData);
} else {
// Add specific domain
$this->addDomainToSiteGroup($siteGroupId, $domain);
}
}
}
/**
* Process mu field for existing site group - handle "all" wildcard
*/
private function processMuFieldForExistingSiteGroup(int $siteGroupId, array $sheetsData): void
{
// Extract mu from custom_fields if not directly available
$mu = $sheetsData['mu'] ?? '';
if (empty($mu) && isset($sheetsData['custom_fields'])) {
$customFields = json_decode($sheetsData['custom_fields'], true);
$mu = $customFields['mu'] ?? '';
}
if (empty($mu)) {
return;
}
// Check if site group already has domains
$existingDomains = $this->db->fetchAll(
"SELECT COUNT(*) as count FROM advertising_site_domains WHERE site_group_id = ? AND deleted_at IS NULL",
[$siteGroupId]
);
if ($existingDomains[0]['count'] > 0) {
return; // Already has domains, don't overwrite
}
// Process mu field for existing site group
$this->processMuFieldForNewSiteGroup($siteGroupId, $sheetsData);
}
/**
* Add "all" wildcard to site group
*/
private function addAllDomainsToSiteGroup(int $siteGroupId, array $sheetsData): void
{
try {
// Simply add "all" as a wildcard domain
$this->addDomainToSiteGroup($siteGroupId, 'all', true);
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'add_all_domains_to_site_group',
'site_group_id' => $siteGroupId
]);
}
}
/**
* Add specific domain to site group
*/
private function addDomainToSiteGroup(int $siteGroupId, string $domain, bool $isPrimary = false): void
{
try {
// Don't clean "all" wildcard
if (strtoupper($domain) !== 'ALL') {
// Clean the domain
$domain = preg_replace('/^https?:\/\//', '', $domain);
$domain = preg_replace('/^www\./', '', $domain);
$domain = trim($domain);
}
if (empty($domain)) {
return;
}
// Generate CUID for domain
$cuid = substr(md5($siteGroupId . '_' . $domain), 0, 32);
// Insert domain
$this->db->query("
INSERT INTO advertising_site_domains (cuid, site_group_id, domain, status, is_primary, created_by, created_at)
VALUES (?, ?, ?, 1, ?, 1, NOW())
ON DUPLICATE KEY UPDATE domain = domain
", [
$cuid,
$siteGroupId,
$domain,
$isPrimary ? 1 : 0
]);
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'add_domain_to_site_group',
'site_group_id' => $siteGroupId,
'domain' => $domain
]);
}
}
/**
* Check if campaign should be updated based on hash
*/
private function shouldUpdateCampaign(array $existing, array $sheetsData): bool
{
return $existing['google_sheets_hash'] !== $sheetsData['google_sheets_hash'];
}
/**
* Check if creative should be updated based on hash
*/
private function shouldUpdateCreative(array $existing, array $sheetsData): bool
{
return $existing['rotator_hash'] !== $sheetsData['rotator_hash'];
}
/**
* Create campaign from Google Sheets data inside a multibook
*/
private function createCampaignFromSheets(array $sheetsData, int $siteGroupId): int
{
// Map to CRM campaign structure
$campaignData = [
'name' => $sheetsData['name'],
'type' => $sheetsData['type'],
'description' => $sheetsData['description'],
'status' => $sheetsData['status'],
'budget' => $sheetsData['budget'],
'start_date' => $sheetsData['start_date'],
'end_date' => $sheetsData['end_date'],
'created_by' => 1, // System user
'cuid' => $sheetsData['script_id'], // Use script_id directly as cuid
'site_group_id' => $siteGroupId, // Link to site group
// Google Sheets specific fields
'script_id' => $sheetsData['script_id'] ?? '',
'campaign_code' => $sheetsData['campaign_code'] ?? '',
'allowed_countries' => $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA',
'click_mode' => !empty($sheetsData['click_mode']) ? 1 : 0,
'brand' => $sheetsData['brand'] ?? '',
'tracker_url' => $sheetsData['tracker'] ?? '',
'campaign_slug' => $sheetsData['campaign_slug'] ?? '',
'allow_close' => !empty($sheetsData['allow_close']) ? 1 : 0,
'analytics_token' => $sheetsData['analytics_token'] ?? '',
'init_after_element_selector' => $sheetsData['init_after_element_selector'] ?? '',
'impressions_target' => $sheetsData['impressions_target'] ?? 0,
'upfront_payment' => $sheetsData['upfront_payment'] ?? 0,
'duration_days' => $sheetsData['duration_days'] ?? 0,
'custom_fields' => $sheetsData['custom_fields'] ?? '{}',
'google_sheets_hash' => $sheetsData['google_sheets_hash'] ?? '',
'last_sync_at' => $sheetsData['last_sync_at'] ?? null,
];
// Use direct SQL insert to avoid model validation issues in demo mode
$sql = "REPLACE INTO advertising_campaigns (
cuid, name, type, description, status, budget, start_date, end_date, created_by, site_group_id,
script_id, campaign_code, allowed_countries, click_mode, brand, tracker_url, campaign_slug,
allow_close, analytics_token, init_after_element_selector, impressions_target,
upfront_payment, duration_days, custom_fields, google_sheets_hash, last_sync_at,
created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
$params = [
$campaignData['cuid'],
$campaignData['name'],
$campaignData['type'],
$campaignData['description'],
$campaignData['status'],
$campaignData['budget'],
$campaignData['start_date'],
$campaignData['end_date'],
$campaignData['created_by'],
$campaignData['site_group_id'],
$campaignData['script_id'],
$campaignData['campaign_code'],
$campaignData['allowed_countries'],
!empty($campaignData['click_mode']) ? 1 : 0,
$campaignData['brand'],
$campaignData['tracker_url'],
$campaignData['campaign_slug'],
$campaignData['allow_close'] ? 1 : 0,
$campaignData['analytics_token'],
$campaignData['init_after_element_selector'],
$campaignData['impressions_target'],
$campaignData['upfront_payment'],
$campaignData['duration_days'],
$campaignData['custom_fields'],
$campaignData['google_sheets_hash'],
$campaignData['last_sync_at']
];
$this->db->query($sql, $params);
$campaignId = $this->db->lastInsertId();
// Create default trackers for the campaign
$this->createDefaultTrackersForCampaign($campaignId, $sheetsData);
return $campaignId;
}
/**
* Create default trackers for a campaign
*/
private function createDefaultTrackersForCampaign(int $campaignId, array $sheetsData): void
{
try {
// Get or create format based on tipo from Google Sheets
$formatId = $this->getOrCreateFormatByType($campaignId, $sheetsData);
// Get or create brand and landing type
$brandId = $this->getOrCreateBrand($sheetsData['brand'] ?? 'Default Brand');
$landingTypeId = $this->getOrCreateLandingType($sheetsData['landing'] ?? 'Basic Landing', $brandId);
// Use tracker template from brand or fallback to Google Sheets data
$trackerUrl = $this->getTrackerTemplateForBrand($brandId, $sheetsData) ??
$sheetsData['tracker'] ??
$sheetsData['tracker_url'] ??
null;
// If no tracker URL is available, skip creating trackers
if (!$trackerUrl) {
ErrorReporter::report(new \Exception("No tracker URL available for campaign"), [
'context' => 'create_default_trackers_for_campaign',
'campaign_id' => $campaignId,
'sheets_data' => $sheetsData
]);
return;
}
// Create trackers for different tracking types
$trackingTypes = ['view', 'click', 'register'];
foreach ($trackingTypes as $trackingType) {
$cuid = $this->generateCuid();
// Build tracking URL based on type
$finalTrackingUrl = $trackerUrl;
if (strpos($trackerUrl, '?') !== false) {
$finalTrackingUrl .= "&type={$trackingType}";
} else {
$finalTrackingUrl .= "?type={$trackingType}";
}
$sql = "INSERT INTO advertising_trackers (
cuid, format_id, brand_id, landing_type_id, name, tracking_type, tracking_url,
tracking_params, is_active, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE
name = VALUES(name),
tracking_type = VALUES(tracking_type),
tracking_url = VALUES(tracking_url),
tracking_params = VALUES(tracking_params),
is_active = VALUES(is_active)";
$this->db->query($sql, [
$cuid,
$formatId,
$brandId,
$landingTypeId,
"Tracker {$trackingType} - {$sheetsData['name']}",
$trackingType,
$finalTrackingUrl,
json_encode([
'campaign_id' => $campaignId,
'script_id' => $sheetsData['script_id'] ?? '',
'type' => $trackingType,
'geo' => $sheetsData['allowed_geos'] ?? 'AA',
'brand' => $sheetsData['brand'] ?? 'Default Brand',
'landing' => $sheetsData['landing'] ?? 'Basic Landing'
]),
true
]);
$trackerId = $this->db->lastInsertId();
// Link tracker to campaign
$this->db->query(
"INSERT INTO advertising_campaign_trackers (campaign_id, tracker_id, order_position) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE order_position = VALUES(order_position)",
[$campaignId, $trackerId, array_search($trackingType, $trackingTypes) + 1]
);
}
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'create_default_trackers_for_campaign',
'campaign_id' => $campaignId,
'sheets_data' => $sheetsData
]);
}
}
/**
* Get or create brand
*/
private function getOrCreateBrand(string $brandName): int
{
// Check if brand already exists
$existingBrand = $this->db->fetch(
"SELECT id FROM advertising_brands WHERE name = ? OR slug = ? LIMIT 1",
[$brandName, strtolower(str_replace(' ', '-', $brandName))]
);
if ($existingBrand) {
return $existingBrand['id'];
}
// Create new brand
$cuid = $this->generateCuid();
$slug = strtolower(str_replace(' ', '-', $brandName));
$sql = "INSERT INTO advertising_brands (
cuid, name, slug, description, is_active, status, created_by, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
ON DUPLICATE KEY UPDATE
name = VALUES(name),
slug = VALUES(slug),
description = VALUES(description),
is_active = VALUES(is_active),
status = VALUES(status),
updated_at = NOW()";
$this->db->query($sql, [
$cuid,
$brandName,
$slug,
"Brand: {$brandName}",
true,
1,
1
]);
return $this->db->lastInsertId();
}
/**
* Get or create landing type
*/
private function getOrCreateLandingType(string $landingName, int $brandId): int
{
// Create landing name based on brand
$brandLandingName = $landingName . " - " . $this->getBrandName($brandId);
// Check if landing type already exists for this brand
$existingBrandLanding = $this->db->fetch(
"SELECT id FROM advertising_brand_landing_types WHERE brand_id = ? AND name = ? LIMIT 1",
[$brandId, $brandLandingName]
);
if ($existingBrandLanding) {
return $existingBrandLanding['id'];
}
// Create new brand landing type
$cuid = $this->generateCuid();
$slug = strtolower(str_replace(' ', '-', $brandLandingName));
$sql = "INSERT INTO advertising_brand_landing_types (
cuid, brand_id, name, slug, type, template_url, is_active, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
ON DUPLICATE KEY UPDATE
name = VALUES(name),
slug = VALUES(slug),
type = VALUES(type),
template_url = VALUES(template_url),
is_active = VALUES(is_active),
updated_at = NOW()";
$this->db->query($sql, [
$cuid,
$brandId,
$brandLandingName,
$slug,
'sales',
null, // Landing URL will be set from actual brand configuration
true
]);
return $this->db->lastInsertId();
}
/**
* Get brand name by ID
*/
private function getBrandName(int $brandId): string
{
$brand = $this->db->fetch(
"SELECT name FROM advertising_brands WHERE id = ? LIMIT 1",
[$brandId]
);
return $brand ? $brand['name'] : 'Unknown Brand';
}
/**
* Get tracker template for brand and replace {alias} with actual alias
*/
private function getTrackerTemplateForBrand(int $brandId, array $sheetsData): ?string
{
// Get template from database
$template = $this->db->fetch(
"SELECT template_url, alias_parameter FROM advertising_brand_templates
WHERE brand_id = ? AND type = 'tracker' AND is_active = 1 LIMIT 1",
[$brandId]
);
if (!$template) {
return null;
}
// Get alias from sheets data or generate from script_id
$alias = $sheetsData['script_id'] ?? $this->generateAlias($sheetsData);
if (!$alias) {
return null;
}
// Replace {alias} with actual alias
$trackerUrl = str_replace('{alias}', $alias, $template['template_url']);
return $trackerUrl;
}
/**
* Generate alias from campaign data
*/
private function generateAlias(array $sheetsData): ?string
{
// Try to extract alias from existing tracker URL
if (!empty($sheetsData['tracker'])) {
$patterns = [
'/[?&]c=([^&]+)/', // c=alias
'/[?&]alias=([^&]+)/', // alias=value
'/[?&]ref=([^&]+)/', // ref=value
'/[?&]aid=([^&]+)/', // aid=value
'/[?&]campaign=([^&]+)/', // campaign=value
'/[?&]pid=([^&]+)/', // pid=value
'/[?&]tracker=([^&]+)/', // tracker=value
'/[?&]code=([^&]+)/', // code=value
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $sheetsData['tracker'], $matches)) {
return $matches[1];
}
}
}
// Use script_id as fallback
return $sheetsData['script_id'] ?? null;
}
/**
* Get or create format based on tipo from Google Sheets
*/
private function getOrCreateFormatByType(int $campaignId, array $sheetsData): int
{
// Get type from Google Sheets data or campaign data
$tipo = $sheetsData['tipo'] ?? $sheetsData['type'] ?? 'banner';
// Map Google Sheets types to format names from Config sheet
$formatMap = [
'overlay' => 'Interstitial',
'interstitial' => 'Interstitial',
'sticky' => 'Sticky Bottom Banner',
'scrollable' => 'Scrollable Top Banner',
'cube' => 'Cube',
'320x50' => '320x50',
'320x100' => '320x100',
'800x600' => '800x600',
'300x600' => '300x600',
'multibook' => 'Multibook',
'banner' => 'Sticky Bottom Banner' // default
];
$formatName = $formatMap[strtolower($tipo)] ?? 'Sticky Bottom Banner';
// Try to find existing format by name (global, not campaign-specific)
$existingFormat = $this->db->fetch(
"SELECT id FROM advertising_formats WHERE name = ? AND is_active = 1 LIMIT 1",
[$formatName]
);
if ($existingFormat) {
return $existingFormat['id'];
}
// If format doesn't exist, create a default one
$cuid = $this->generateCuid();
// Get default dimensions based on format name
$dimensions = $this->getDefaultDimensions($formatName);
$sql = "INSERT INTO advertising_formats (
cuid, campaign_id, name, width, height, format_type, pub_type,
html_template, css_styles, js_code, is_active, weight, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE
name = VALUES(name),
width = VALUES(width),
height = VALUES(height),
format_type = VALUES(format_type),
pub_type = VALUES(pub_type),
html_template = VALUES(html_template),
css_styles = VALUES(css_styles),
js_code = VALUES(js_code),
is_active = VALUES(is_active),
weight = VALUES(weight),
updated_at = NOW()";
$this->db->query($sql, [
$cuid,
$campaignId,
$formatName,
$dimensions['width'],
$dimensions['height'],
$dimensions['format_type'],
$dimensions['pub_type'],
$this->getDefaultHtmlTemplate($formatName),
$this->getDefaultCssStyles($formatName),
$this->getDefaultJsCode($formatName),
true,
1
]);
return $this->db->lastInsertId();
}
/**
* Get default dimensions for format type
*/
private function getDefaultDimensions(string $formatName): array
{
$dimensions = [
// Format names from Config sheet
'Sticky Bottom Banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'],
'Scrollable Top Banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'],
'Interstitial' => ['width' => 800, 'height' => 600, 'format_type' => 'popup', 'pub_type' => 'interstitial'],
'Cube' => ['width' => 300, 'height' => 250, 'format_type' => 'banner', 'pub_type' => 'banner'],
'320x50' => ['width' => 320, 'height' => 50, 'format_type' => 'banner', 'pub_type' => 'banner'],
'320x100' => ['width' => 320, 'height' => 100, 'format_type' => 'banner', 'pub_type' => 'banner'],
'800x600' => ['width' => 800, 'height' => 600, 'format_type' => 'banner', 'pub_type' => 'banner'],
'300x600' => ['width' => 300, 'height' => 600, 'format_type' => 'banner', 'pub_type' => 'banner'],
'Multibook' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'],
// Legacy format types
'banner' => ['width' => 728, 'height' => 90, 'format_type' => 'banner', 'pub_type' => 'banner'],
'popup' => ['width' => 800, 'height' => 600, 'format_type' => 'popup', 'pub_type' => 'interstitial'],
'native' => ['width' => 728, 'height' => 90, 'format_type' => 'native', 'pub_type' => 'native'],
'video' => ['width' => 640, 'height' => 360, 'format_type' => 'video', 'pub_type' => 'video']
];
return $dimensions[$formatName] ?? $dimensions['Sticky Bottom Banner'];
}
/**
* Get default HTML template for format type
*/
private function getDefaultHtmlTemplate(string $formatType): string
{
$templates = [
'banner' => '<div class="ad-banner">Banner Content</div>',
'popup' => '<div class="ad-popup">Popup Content</div>',
'native' => '<div class="ad-native">Native Content</div>',
'video' => '<div class="ad-video">Video Content</div>'
];
return $templates[$formatType] ?? $templates['banner'];
}
/**
* Get default CSS styles for format type
*/
private function getDefaultCssStyles(string $formatType): string
{
$styles = [
'banner' => '.ad-banner { width: 728px; height: 90px; }',
'popup' => '.ad-popup { width: 300px; height: 250px; }',
'native' => '.ad-native { width: 300px; height: 250px; }',
'video' => '.ad-video { width: 640px; height: 360px; }'
];
return $styles[$formatType] ?? $styles['banner'];
}
/**
* Get default JS code for format type
*/
private function getDefaultJsCode(string $formatType): string
{
$code = [
'banner' => 'console.log("Banner loaded");',
'popup' => 'console.log("Popup loaded");',
'native' => 'console.log("Native ad loaded");',
'video' => 'console.log("Video ad loaded");'
];
return $code[$formatType] ?? $code['banner'];
}
/**
* Get or create default format for a campaign (legacy method)
*/
private function getOrCreateDefaultFormat(int $campaignId, array $sheetsData): int
{
// Check if campaign already has formats
$existingFormat = $this->db->fetch(
"SELECT id FROM advertising_formats WHERE campaign_id = ? LIMIT 1",
[$campaignId]
);
if ($existingFormat) {
return $existingFormat['id'];
}
// Create default format
$cuid = $this->generateCuid();
$sql = "INSERT INTO advertising_formats (
cuid, campaign_id, name, width, height, format_type,
html_template, css_styles, js_code, is_active, weight, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
$this->db->query($sql, [
$cuid,
$campaignId,
'Default Banner Format',
728,
90,
'banner',
'<div class="ad-banner">Banner Content</div>',
'.ad-banner { width: 728px; height: 90px; }',
'console.log("Banner loaded");',
true,
1
]);
return $this->db->lastInsertId();
}
/**
* Update campaign from Google Sheets data
*/
private function updateCampaignFromSheets(int $campaignId, array $sheetsData, int $siteGroupId): bool
{
$updateData = [
'name' => $sheetsData['name'],
'type' => $sheetsData['type'],
'description' => $sheetsData['description'],
'status' => $sheetsData['status'],
'budget' => $sheetsData['budget'],
'start_date' => $sheetsData['start_date'],
'end_date' => $sheetsData['end_date'],
// Google Sheets specific fields
'campaign_code' => $sheetsData['campaign_code'] ?? '',
'allowed_countries' => $sheetsData['allowed_geos'] ?? $sheetsData['Country'] ?? 'AA',
'click_mode' => !empty($sheetsData['click_mode']) ? 1 : 0,
'brand' => $sheetsData['brand'] ?? '',
'campaign_slug' => $sheetsData['campaign_slug'] ?? '',
'allow_close' => !empty($sheetsData['allow_close']) ? 1 : 0,
'analytics_token' => $sheetsData['analytics_token'] ?? '',
'init_after_element_selector' => $sheetsData['init_after_element_selector'] ?? '',
'impressions_target' => $sheetsData['impressions_target'] ?? 0,
'upfront_payment' => $sheetsData['upfront_payment'] ?? 0,
'duration_days' => $sheetsData['duration_days'] ?? 0,
'custom_fields' => $sheetsData['custom_fields'] ?? '{}',
'google_sheets_hash' => $sheetsData['google_sheets_hash'] ?? '',
'last_sync_at' => $sheetsData['last_sync_at'] ?? null,
];
return $this->campaignModel->update($campaignId, $updateData);
}
/**
* Create creative from Google Sheets data
*/
private function createCreativeFromSheets(array $sheetsData): int
{
// Find related campaign
$campaign = $this->findCampaignByScriptId($sheetsData['script_id']);
$campaignId = $campaign ? $campaign['id'] : null;
$creativeData = [
'cuid' => $this->generateCuid(), // Generate proper CUID
'format_id' => null, // No format required for now
'name' => $sheetsData['name'],
'file_name' => $sheetsData['creative_slug'] . '.html',
'file_path' => '/creatives/' . $sheetsData['creative_slug'] . '.html',
'file_size' => 1024, // Default size
'mime_type' => 'text/html',
'width' => 300,
'height' => 250,
'alt_text' => $sheetsData['description'],
'is_active' => 1,
'description' => $sheetsData['description'],
// Google Sheets specific fields
'script_id' => $sheetsData['script_id'],
'creative_slug' => $sheetsData['creative_slug'],
'target_country' => substr($sheetsData['geo'] ?? '', 0, 10), // Truncate geo field
'click_mode_override' => $sheetsData['click_mode_override'],
'view_url' => $sheetsData['view_url'],
'creative_type' => 'rotator', // All creatives from rotator tab are 'rotator' type
'rotator_hash' => $sheetsData['rotator_hash'],
'last_sync_at' => $sheetsData['last_sync_at'],
];
// Use direct SQL insert to avoid model validation issues in demo mode
$sql = "INSERT INTO advertising_creatives (
cuid, format_id, name, file_name, file_path, file_size, mime_type, width, height,
alt_text, is_active, description, script_id, creative_slug, target_country, click_mode_override,
view_url, creative_type, rotator_hash, last_sync_at, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
ON DUPLICATE KEY UPDATE
name = VALUES(name),
file_name = VALUES(file_name),
file_path = VALUES(file_path),
file_size = VALUES(file_size),
mime_type = VALUES(mime_type),
width = VALUES(width),
height = VALUES(height),
alt_text = VALUES(alt_text),
is_active = VALUES(is_active),
description = VALUES(description),
script_id = VALUES(script_id),
creative_slug = VALUES(creative_slug),
target_country = VALUES(target_country),
click_mode_override = VALUES(click_mode_override),
view_url = VALUES(view_url),
creative_type = VALUES(creative_type),
rotator_hash = VALUES(rotator_hash),
last_sync_at = VALUES(last_sync_at),
updated_at = NOW()";
$params = [
$creativeData['cuid'],
$creativeData['format_id'],
$creativeData['name'],
$creativeData['file_name'],
$creativeData['file_path'],
$creativeData['file_size'],
$creativeData['mime_type'],
$creativeData['width'],
$creativeData['height'],
$creativeData['alt_text'],
$creativeData['is_active'],
$creativeData['description'],
$creativeData['script_id'],
$creativeData['creative_slug'],
$creativeData['target_country'],
$creativeData['click_mode_override'] !== null ? ($creativeData['click_mode_override'] ? 1 : 0) : null,
$creativeData['view_url'],
$creativeData['creative_type'],
$creativeData['rotator_hash'],
$creativeData['last_sync_at']
];
// Insert creative data
$this->db->query($sql, $params);
return $this->db->lastInsertId();
}
/**
* Update creative from Google Sheets data
*/
private function updateCreativeFromSheets(int $creativeId, array $sheetsData): bool
{
// Find related campaign
$campaign = $this->findCampaignByScriptId($sheetsData['script_id']);
$campaignId = $campaign ? $campaign['id'] : null;
$updateData = [
'campaign_id' => $campaignId,
'name' => $sheetsData['name'],
'description' => $sheetsData['description'],
// Google Sheets specific fields
'geo' => $sheetsData['geo'],
'click_mode_override' => $sheetsData['click_mode_override'],
'view_url' => $sheetsData['view_url'],
'creative_type' => $sheetsData['creative_type'],
'rotator_hash' => $sheetsData['rotator_hash'],
'last_sync_at' => $sheetsData['last_sync_at'],
];
return $this->creativeModel->update($creativeId, $updateData);
}
/**
* Generate trackers.json for script-builder compatibility
*/
private function generateTrackersJson(): void
{
try {
// Get all campaigns and creatives from CRM
$campaigns = $this->db->fetchAll(
"SELECT * FROM advertising_campaigns WHERE script_id IS NOT NULL AND deleted_at IS NULL"
);
$creatives = $this->db->fetchAll(
"SELECT * FROM advertising_creatives WHERE script_id IS NOT NULL AND deleted_at IS NULL"
);
// Build trackers.json structure (compatible with script-builder)
$trackers = [];
foreach ($campaigns as $campaign) {
$trackers[$campaign['script_id']] = [
'script_id' => $campaign['script_id'] ?? '',
'campaign_slug' => $campaign['campaign_slug'] ?? '',
'name' => $campaign['name'] ?? '',
'status' => $campaign['status'] ?? 'active',
'click_mode' => (bool)($campaign['click_mode'] ?? false),
'allowed_geos' => $campaign['allowed_geos'] ?? 'AA',
'brand' => $campaign['brand'] ?? '',
'analytics_token' => $campaign['analytics_token'] ?? '',
'custom_fields' => json_decode($campaign['custom_fields'] ?? '{}', true),
'last_sync' => $campaign['last_sync_at'] ?? null,
];
// Add related creatives
$campaignCreatives = array_filter($creatives, function($creative) use ($campaign) {
return $creative['script_id'] === $campaign['script_id'];
});
$trackers[$campaign['script_id']]['creatives'] = array_map(function($creative) {
return [
'slug' => $creative['creative_slug'] ?? '',
'geo' => $creative['geo'] ?? 'AA',
'url' => $creative['view_url'] ?? '',
'type' => $creative['creative_type'] ?? 'banner',
];
}, $campaignCreatives);
}
// Save to file (script-builder compatible location)
$trackersPath = realpath(__DIR__ . '/../../../../projects/script-builder/') . '/trackers.json';
$trackersJson = json_encode($trackers, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if (!file_put_contents($trackersPath, $trackersJson)) {
throw new \Exception("Failed to write trackers.json to: $trackersPath");
}
// Update version in database for sync control
$version = md5($trackersJson);
$this->db->query(
"INSERT INTO advertising_sync_versions (type, version, updated_at) VALUES (?, ?, NOW())
ON DUPLICATE KEY UPDATE version = VALUES(version), updated_at = VALUES(updated_at)",
['trackers_json', $version]
);
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'generate_trackers_json'
]);
throw $e;
}
}
/**
* Get synchronization statistics
*/
public function getSyncStats(): array
{
try {
$stats = [
'campaigns' => [
'total' => 0,
'synced' => 0,
'last_sync' => null,
],
'creatives' => [
'total' => 0,
'synced' => 0,
'last_sync' => null,
],
'google_sheets_available' => $this->googleSheetsService->isAvailable(),
];
// Campaign stats
$campaignStats = $this->db->fetch(
"SELECT
COUNT(*) as total,
COUNT(script_id) as synced,
MAX(last_sync_at) as last_sync
FROM advertising_campaigns
WHERE deleted_at IS NULL"
);
$stats['campaigns'] = [
'total' => (int)$campaignStats['total'],
'synced' => (int)$campaignStats['synced'],
'last_sync' => $campaignStats['last_sync'],
];
// Creative stats
$creativeStats = $this->db->fetch(
"SELECT
COUNT(*) as total,
COUNT(script_id) as synced,
MAX(last_sync_at) as last_sync
FROM advertising_creatives
WHERE deleted_at IS NULL"
);
$stats['creatives'] = [
'total' => (int)$creativeStats['total'],
'synced' => (int)$creativeStats['synced'],
'last_sync' => $creativeStats['last_sync'],
];
return $stats;
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'get_sync_stats']);
return [
'error' => $e->getMessage(),
'google_sheets_available' => false,
];
}
}
/**
* Create missing trackers for campaigns that don't have any
*/
public function createMissingTrackersForCampaigns(): array
{
$results = ['created' => 0, 'errors' => []];
try {
// Get campaigns without trackers
$campaignsWithoutTrackers = $this->db->fetchAll(
"SELECT c.* FROM advertising_campaigns c
LEFT JOIN advertising_campaign_trackers ct ON c.id = ct.campaign_id
WHERE c.deleted_at IS NULL AND ct.tracker_id IS NULL"
);
foreach ($campaignsWithoutTrackers as $campaign) {
try {
// Create default trackers for this campaign
$this->createDefaultTrackersForCampaign($campaign['id'], [
'name' => $campaign['name'],
'script_id' => $campaign['script_id'] ?? '',
'allowed_geos' => $campaign['allowed_geos'] ?? 'AA',
'brand' => $campaign['brand'] ?? 'Default Brand',
'landing' => 'Basic Landing', // Default landing type for existing campaigns
'type' => $campaign['type'] ?? 'banner', // Use existing campaign type
'tracker_url' => $campaign['tracker_url'] ?? null // Use existing tracker URL or null if not available
]);
$results['created']++;
} catch (\Exception $e) {
$results['errors'][] = "Campaign {$campaign['id']}: " . $e->getMessage();
ErrorReporter::report($e, [
'context' => 'create_missing_trackers_for_campaign',
'campaign_id' => $campaign['id']
]);
}
}
return $results;
} catch (\Exception $e) {
ErrorReporter::report($e, ['context' => 'create_missing_trackers_for_campaigns']);
throw $e;
}
}
/**
* Generate CUID for new records
*/
private function generateCuid(): string
{
return (string) new Cuid2();
}
/**
* Map agent name from Google Sheets to user ID
*/
private function mapAgentToUserId(string $agentName): int
{
if (empty($agentName)) {
return 1; // Default fallback user
}
try {
// Map common agent name variations to database names
$nameMapping = [
'Eduardo Terrivel' => 'Eduardo Terrivel',
'Eduardo' => 'Eduardo Terrivel',
'ET' => 'Eduardo Terrivel',
'eduardo.terrivel' => 'Eduardo Terrivel',
'Alexandre Broadley' => 'Alexandre Broadley',
'Alexandre' => 'Alexandre Broadley',
'AB' => 'Alexandre Broadley',
'alexandre.broadley' => 'Alexandre Broadley',
'Pedro Alves' => 'Pedro Alves',
'Pedro' => 'Pedro Alves',
'PA' => 'Pedro Alves',
];
$searchName = $nameMapping[$agentName] ?? $agentName;
// Try to find user by full name
$user = $this->db->fetch(
"SELECT id FROM users WHERE name = ? AND is_active = 1 LIMIT 1",
[$searchName]
);
if ($user) {
return (int)$user['id'];
}
// Try to find by first name
$firstName = explode(' ', $searchName)[0];
$user = $this->db->fetch(
"SELECT id FROM users WHERE first_name = ? AND is_active = 1 LIMIT 1",
[$firstName]
);
if ($user) {
return (int)$user['id'];
}
// Try to find by user alias
$user = $this->db->fetch(
"SELECT id FROM users WHERE user_alias = ? AND is_active = 1 LIMIT 1",
[$agentName]
);
if ($user) {
return (int)$user['id'];
}
return 1; // Default fallback user
} catch (\Exception $e) {
ErrorReporter::report($e, [
'context' => 'agent_mapping_error',
'agent_name' => $agentName
]);
return 1; // Default fallback user
}
}
/**
* Get first domain from mu field for site group naming
*/
private function getFirstDomainFromMu(array $sheetsData): ?string
{
// Extract mu from custom_fields if not directly available
$mu = $sheetsData['mu'] ?? '';
if (empty($mu) && isset($sheetsData['custom_fields'])) {
$customFields = json_decode($sheetsData['custom_fields'], true);
$mu = $customFields['mu'] ?? '';
}
if (empty($mu)) {
return null;
}
// Split by comma, newline, semicolon, or any whitespace sequence and get first domain
$domains = array_map('trim', preg_split('/[,\n\r\n;]+/', $mu));
$domains = array_filter($domains); // Remove empty entries
$firstDomain = $domains[0] ?? null;
// Skip "all" wildcard, get next domain
if ($firstDomain === 'all' && count($domains) > 1) {
$firstDomain = $domains[1] ?? null;
}
return $firstDomain;
}
}