- Replace "BetZoo CRM" with "MoneyFlix" in Advertising module description - Replace "Betzoo" option with "MoneyFlix" in ErrorMonitoring project filter - Update GoogleSheetsService to use environment variable for credentials path - Update CDN config from betzoo.app to moneyflix.com - Remove WDMI-specific checks in layouts (topbar, sidebar, main, public-blank) - Update database profile examples from wdmi_importer to moneyflix_importer - Keep BitReport references (company/product name)
476 lines
17 KiB
PHP
476 lines
17 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Modules\Advertising\Services;
|
|
|
|
use App\Core\DatabaseManager;
|
|
use App\Core\ErrorReporter;
|
|
|
|
/**
|
|
* Google Sheets Integration Service
|
|
*
|
|
* Handles reading and writing data to/from Google Sheets
|
|
* for the Advertising module integration.
|
|
*/
|
|
class GoogleSheetsService
|
|
{
|
|
private DatabaseManager $db;
|
|
private ?object $googleClient = null;
|
|
private ?object $sheetsService = null;
|
|
|
|
// Google Sheets configuration
|
|
private const SPREADSHEET_ID = '1JrvSYDAFB03Hri3aV4NeB5z7_vZHKr-d18NNzQneQyo';
|
|
private const SCRIPTS_RANGE = 'SCRIPTS!A:Z';
|
|
private const ROTATOR_RANGE = 'ROTATOR!A:Z';
|
|
private const VERSIONS_RANGE = 'Versions!A:Z';
|
|
|
|
public function __construct()
|
|
{
|
|
$this->db = DatabaseManager::getInstance();
|
|
$this->loadGoogleLibraries();
|
|
$this->initializeGoogleClient();
|
|
}
|
|
|
|
/**
|
|
* Load Google Libraries from script-builder
|
|
*/
|
|
private function loadGoogleLibraries(): void
|
|
{
|
|
// Use script-builder's vendor directory which has Google API libraries
|
|
$vendorAutoload = __DIR__ . '/../../../../projects/script-builder/vendor/autoload.php';
|
|
if (file_exists($vendorAutoload)) {
|
|
require_once $vendorAutoload;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Initialize Google Sheets client
|
|
*/
|
|
private function initializeGoogleClient(): void
|
|
{
|
|
try {
|
|
// Google Sheets credentials path (configure in environment if needed)
|
|
$credentialsPath = getenv('GOOGLE_CREDENTIALS_PATH') ?: __DIR__ . '/../../../../config/google-credentials.json';
|
|
$credentialsPath = realpath($credentialsPath);
|
|
|
|
if (!$credentialsPath || !file_exists($credentialsPath)) {
|
|
// Demo mode: Google Sheets not available
|
|
$this->googleClient = null;
|
|
$this->sheetsService = null;
|
|
return;
|
|
}
|
|
|
|
// Set environment variable for Google credentials
|
|
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credentialsPath);
|
|
|
|
$this->googleClient = new \Google_Client();
|
|
$this->googleClient->setApplicationName('BitReport CRM - Advertising Module');
|
|
$this->googleClient->useApplicationDefaultCredentials();
|
|
$this->googleClient->addScope(\Google_Service_Sheets::SPREADSHEETS);
|
|
|
|
$this->sheetsService = new \Google_Service_Sheets($this->googleClient);
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'google_sheets_service_init',
|
|
'credentials_path' => $credentialsPath ?? 'not_set'
|
|
]);
|
|
|
|
// Google Sheets not available - set to null
|
|
$this->googleClient = null;
|
|
$this->sheetsService = null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Read campaigns data from Google Sheets SCRIPTS tab
|
|
*/
|
|
public function readCampaignsFromSheets(): array
|
|
{
|
|
try {
|
|
if (!$this->sheetsService) {
|
|
// Google Sheets not available - throw exception instead of using demo data
|
|
throw new \Exception('Google Sheets service not available. Please check credentials and connection.');
|
|
}
|
|
|
|
$response = $this->sheetsService->spreadsheets_values->get(
|
|
self::SPREADSHEET_ID,
|
|
self::SCRIPTS_RANGE
|
|
);
|
|
|
|
$values = $response->getValues();
|
|
if (empty($values)) {
|
|
return [];
|
|
}
|
|
|
|
// First row contains headers
|
|
$headers = array_shift($values);
|
|
$campaigns = [];
|
|
|
|
foreach ($values as $row) {
|
|
if (empty($row[0])) continue; // Skip empty rows
|
|
|
|
$campaign = [];
|
|
foreach ($headers as $index => $header) {
|
|
$campaign[$header] = $row[$index] ?? '';
|
|
}
|
|
|
|
// Map Google Sheets fields to CRM fields
|
|
$campaigns[] = $this->mapSheetsToCampaignFields($campaign);
|
|
}
|
|
|
|
return $campaigns;
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'google_sheets_read_campaigns',
|
|
'spreadsheet_id' => self::SPREADSHEET_ID
|
|
]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Read creatives data from Google Sheets ROTATOR tab
|
|
*/
|
|
public function readCreativesFromSheets(): array
|
|
{
|
|
try {
|
|
if (!$this->sheetsService) {
|
|
// Google Sheets not available - throw exception instead of using demo data
|
|
throw new \Exception('Google Sheets service not available. Please check credentials and connection.');
|
|
}
|
|
|
|
$response = $this->sheetsService->spreadsheets_values->get(
|
|
self::SPREADSHEET_ID,
|
|
self::ROTATOR_RANGE
|
|
);
|
|
|
|
$values = $response->getValues();
|
|
if (empty($values)) {
|
|
return [];
|
|
}
|
|
|
|
// First row contains headers
|
|
$headers = array_shift($values);
|
|
$creatives = [];
|
|
|
|
foreach ($values as $row) {
|
|
if (empty($row[0])) continue; // Skip empty rows
|
|
|
|
$creative = [];
|
|
foreach ($headers as $index => $header) {
|
|
$creative[$header] = $row[$index] ?? '';
|
|
}
|
|
|
|
// Map Google Sheets fields to CRM fields
|
|
$creatives[] = $this->mapSheetsToCreativeFields($creative);
|
|
}
|
|
|
|
return $creatives;
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'google_sheets_read_creatives',
|
|
'spreadsheet_id' => self::SPREADSHEET_ID
|
|
]);
|
|
throw $e;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Map Google Sheets fields to CRM campaign fields
|
|
*/
|
|
private function mapSheetsToCampaignFields(array $sheetsData): array
|
|
{
|
|
return [
|
|
// Core campaign fields - map from actual Google Sheets headers
|
|
'script_id' => $sheetsData['ScriptID'] ?? '',
|
|
'name' => $this->generateCampaignName($sheetsData), // Generate proper campaign name
|
|
'campaign_code' => $sheetsData['Tracker'] ?? '',
|
|
'description' => $sheetsData['Delay/notes'] ?? '',
|
|
|
|
// Google Sheets specific fields
|
|
'allowed_geos' => $sheetsData['Country'] ?? '',
|
|
'click_mode' => filter_var($sheetsData['Click?'] ?? false, FILTER_VALIDATE_BOOLEAN),
|
|
'brand' => $sheetsData['Brand'] ?? '',
|
|
'campaign_slug' => $sheetsData['SLUG'] ?? '',
|
|
'allow_close' => filter_var($sheetsData['Close?'] ?? true, FILTER_VALIDATE_BOOLEAN),
|
|
'analytics_token' => $sheetsData['Analytics Token'] ?? '',
|
|
'init_after_element_selector' => $sheetsData['Load After Element'] ?? '',
|
|
|
|
// Financial and targeting
|
|
'budget' => !empty($sheetsData['BUDGET']) ? (float)$sheetsData['BUDGET'] : null,
|
|
'impressions_target' => !empty($sheetsData['IMPRESSIONS']) ? (int)$sheetsData['IMPRESSIONS'] : null,
|
|
'upfront_payment' => !empty($sheetsData['UPFRONT_PAYMENT']) ? (float)$sheetsData['UPFRONT_PAYMENT'] : null,
|
|
'duration_days' => !empty($sheetsData['DURATION_OF_THE_CAMPAIGN']) ? (int)$sheetsData['DURATION_OF_THE_CAMPAIGN'] : null,
|
|
|
|
// Dates
|
|
'start_date' => !empty($sheetsData['START_DATE']) ? $sheetsData['START_DATE'] : null,
|
|
'end_date' => !empty($sheetsData['END_DATE']) ? $sheetsData['END_DATE'] : null,
|
|
|
|
// Status and type
|
|
'status' => $this->mapSheetsStatus($sheetsData['Status'] ?? 'active'),
|
|
'type' => $this->mapSheetsType($sheetsData['Banner Type'] ?? 'banner'),
|
|
|
|
// Custom fields (p, q, r, s, t, u, v, w, x, y, z, INFO, INFO2, mu, Status)
|
|
'custom_fields' => json_encode([
|
|
'p' => $sheetsData['p'] ?? '',
|
|
'q' => $sheetsData['q'] ?? '',
|
|
'r' => $sheetsData['r'] ?? '',
|
|
's' => $sheetsData['s'] ?? '',
|
|
't' => $sheetsData['t'] ?? '',
|
|
'u' => $sheetsData['u'] ?? '',
|
|
'v' => $sheetsData['v'] ?? '',
|
|
'w' => $sheetsData['w'] ?? '',
|
|
'x' => $sheetsData['x'] ?? '',
|
|
'y' => $sheetsData['y'] ?? '',
|
|
'z' => $sheetsData['z'] ?? '',
|
|
'INFO' => $sheetsData['INFO'] ?? '',
|
|
'INFO2' => $sheetsData['INFO2'] ?? '',
|
|
'mu' => $sheetsData['mu'] ?? '', // Multiple domains field
|
|
'Status' => $sheetsData['Status'] ?? '', // Status from column G
|
|
]),
|
|
|
|
// Agent assignment (coluna Z)
|
|
'created_by' => $this->mapAgentToUserId($sheetsData['z'] ?? ''),
|
|
|
|
// Sync control
|
|
'google_sheets_hash' => md5(json_encode($sheetsData)),
|
|
'last_sync_at' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Map Google Sheets fields to CRM creative fields
|
|
*/
|
|
private function mapSheetsToCreativeFields(array $sheetsData): array
|
|
{
|
|
return [
|
|
// Core creative fields - map from actual ROTATOR headers
|
|
'script_id' => $sheetsData['Script ID'] ?? '',
|
|
'creative_slug' => $sheetsData['Rotator SLUG'] ?? '',
|
|
'name' => $sheetsData['Rotator SLUG'] ?? '', // Use slug as name for now
|
|
'description' => $sheetsData['SITE'] ?? '',
|
|
|
|
// Google Sheets specific fields
|
|
'geo' => $sheetsData['Geo'] ?? '',
|
|
'click_mode_override' => !empty($sheetsData['Click?']) ? filter_var($sheetsData['Click?'], FILTER_VALIDATE_BOOLEAN) : null,
|
|
'view_url' => $sheetsData['View URL'] ?? $sheetsData['URL'] ?? '',
|
|
'creative_type' => 'rotator', // Rotator tab entries are always rotator type
|
|
|
|
// Sync control
|
|
'rotator_hash' => md5(json_encode($sheetsData)),
|
|
'last_sync_at' => date('Y-m-d H:i:s'),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Map Google Sheets status to CRM status
|
|
*/
|
|
private function mapSheetsStatus(string $sheetsStatus): int
|
|
{
|
|
$statusMap = [
|
|
'active' => 1,
|
|
'inactive' => 0,
|
|
'paused' => 2,
|
|
'draft' => 3,
|
|
'archived' => 4,
|
|
'to be retired' => 0, // Map "to be retired" to inactive
|
|
'live' => 1,
|
|
];
|
|
|
|
return $statusMap[strtolower($sheetsStatus)] ?? 1;
|
|
}
|
|
|
|
/**
|
|
* Map Google Sheets banner type to CRM type
|
|
*/
|
|
private function mapSheetsType(string $sheetsType): string
|
|
{
|
|
$typeMap = [
|
|
'banner' => 'banner',
|
|
'popup' => 'popup',
|
|
'native' => 'native',
|
|
'video' => 'video',
|
|
'interstitial' => 'interstitial',
|
|
];
|
|
|
|
return $typeMap[strtolower($sheetsType)] ?? 'banner';
|
|
}
|
|
|
|
/**
|
|
* Generate proper campaign name from Google Sheets data
|
|
*/
|
|
private function generateCampaignName(array $sheetsData): string
|
|
{
|
|
// Get first domain from mu field (domains separated by \n)
|
|
$mu = $sheetsData['mu'] ?? '';
|
|
|
|
if (empty($mu)) {
|
|
return 'Campanha sem domínio';
|
|
}
|
|
|
|
// Split by line breaks to get individual domains (support both \n and \r\n)
|
|
$domains = preg_split('/\r?\n/', trim($mu));
|
|
|
|
// Find first valid domain (not "ALL")
|
|
foreach ($domains as $domain) {
|
|
$domain = trim($domain);
|
|
if (!empty($domain) && strtoupper($domain) !== 'ALL') {
|
|
// Clean the domain (remove protocols, www, etc.)
|
|
$domain = preg_replace('/^https?:\/\//', '', $domain);
|
|
$domain = preg_replace('/^www\./', '', $domain);
|
|
|
|
// Limit length
|
|
$domain = substr($domain, 0, 100);
|
|
|
|
return $domain;
|
|
}
|
|
}
|
|
|
|
return 'Campanha sem domínio válido';
|
|
}
|
|
|
|
/**
|
|
* Write campaign data back to Google Sheets
|
|
*/
|
|
public function writeCampaignToSheets(array $campaignData): bool
|
|
{
|
|
try {
|
|
// This method would write data back to Google Sheets
|
|
// Implementation depends on specific requirements
|
|
// For now, we focus on reading from sheets
|
|
|
|
return true;
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'google_sheets_write_campaign',
|
|
'campaign_data' => $campaignData
|
|
]);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get Google Sheets version/hash for sync control
|
|
*/
|
|
public function getSheetsVersion(): ?string
|
|
{
|
|
try {
|
|
$response = $this->sheetsService->spreadsheets_values->get(
|
|
self::SPREADSHEET_ID,
|
|
self::VERSIONS_RANGE
|
|
);
|
|
|
|
$values = $response->getValues();
|
|
if (!empty($values)) {
|
|
// Look for trackers.json version
|
|
foreach ($values as $row) {
|
|
if (isset($row[0]) && $row[0] === 'trackers.json') {
|
|
return $row[1] ?? null; // Version in second column
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'google_sheets_get_version'
|
|
]);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if Google Sheets service is available
|
|
*/
|
|
public function isAvailable(): bool
|
|
{
|
|
return $this->sheetsService !== null;
|
|
}
|
|
|
|
// Demo data functions removed - system now requires real Google Sheets connection
|
|
|
|
/**
|
|
* Map agent name from Google Sheets to user ID
|
|
*
|
|
* @param string $agentName Agent name from column Z
|
|
* @return int User ID or default fallback
|
|
*/
|
|
private function mapAgentToUserId(string $agentName): int
|
|
{
|
|
if (empty($agentName)) {
|
|
return 1; // Default fallback user
|
|
}
|
|
|
|
try {
|
|
$db = DatabaseManager::getInstance();
|
|
|
|
// Map common agent name variations to database names
|
|
$nameMapping = [
|
|
'Eduardo Terrivel' => 'Eduardo Terrivel',
|
|
'Eduardo' => 'Eduardo Terrivel',
|
|
'ET' => 'Eduardo Terrivel',
|
|
'Alexandre Broadley' => 'Alexandre Broadley',
|
|
'Alexandre' => 'Alexandre Broadley',
|
|
'AB' => 'Alexandre Broadley',
|
|
'Pedro Alves' => 'Pedro Alves',
|
|
'Pedro' => 'Pedro Alves',
|
|
'PA' => 'Pedro Alves',
|
|
];
|
|
|
|
$searchName = $nameMapping[$agentName] ?? $agentName;
|
|
|
|
// Try to find user by full name
|
|
$user = $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 = $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 = $db->fetch(
|
|
"SELECT id FROM users WHERE user_alias = ? AND is_active = 1 LIMIT 1",
|
|
[$agentName]
|
|
);
|
|
|
|
if ($user) {
|
|
return (int)$user['id'];
|
|
}
|
|
|
|
// Log unknown agent for debugging
|
|
ErrorReporter::report(new \Exception('Unknown agent in Google Sheets'), [
|
|
'context' => 'google_sheets_agent_mapping',
|
|
'agent_name' => $agentName,
|
|
'search_name' => $searchName
|
|
]);
|
|
|
|
return 1; // Default fallback user
|
|
|
|
} catch (\Exception $e) {
|
|
ErrorReporter::report($e, [
|
|
'context' => 'agent_mapping_error',
|
|
'agent_name' => $agentName
|
|
]);
|
|
return 1; // Default fallback user
|
|
}
|
|
}
|
|
} |