86 lines
4.3 KiB
PHP
86 lines
4.3 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Client;
|
|
use App\Models\GoogleAdGroup;
|
|
use App\Models\GoogleCampaign;
|
|
use App\Models\GoogleCampaignMetric;
|
|
use App\Models\GoogleClient;
|
|
use App\Models\GoogleKeywordMetric;
|
|
use App\Models\GoogleKeywords;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use App\Services\GoogleAdsService;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class GetGoogleKeywordsMetric extends Command
|
|
{
|
|
protected $signature = 'google-ads:get-keywords-metric';
|
|
protected $description = 'Get keywords metric from Google Ads';
|
|
public function handle()
|
|
{
|
|
try {
|
|
DB::beginTransaction();
|
|
$this->info("Fetching campaign details from Google Ads...");
|
|
$adsService = new GoogleAdsService();
|
|
$clients = Client::where('status', 'ENABLED')->where('customer_id', '2048068576')->get();
|
|
foreach ($clients as $client) {
|
|
$campaigns = GoogleCampaign::where('client_id', $client->id)->get();
|
|
if ($campaigns->isEmpty()) {
|
|
$this->info("No campaigns found for Client ID: {$client->customer_id}");
|
|
continue;
|
|
} else {
|
|
foreach ($campaigns as $campaign) {
|
|
$adGroups = GoogleAdGroup::where('google_campaign_id', $campaign->id)->get();
|
|
if ($adGroups->isEmpty()) {
|
|
$this->info("No ad groups found for Client ID: {$client->customer_id}");
|
|
continue;
|
|
} else {
|
|
foreach ($adGroups as $adGroup) {
|
|
$keywords = GoogleKeywords::where('google_ad_group_id', $adGroup->id)->get();
|
|
if ($keywords->isEmpty()) {
|
|
$this->info("No keywords found for Client ID: {$client->customer_id}");
|
|
continue;
|
|
} else {
|
|
foreach ($keywords as $keyword) {
|
|
$metrics = $adsService->getKeywordMetricsById($client->customer_id, $keyword->keyword_id, '1970-01-01');
|
|
// $metrics = $adsService->getKeywordMetricsById($client->customer_id, $keyword->keyword_id);
|
|
if (! empty($metrics)) {
|
|
foreach ($metrics as $metric) {
|
|
GoogleKeywordMetric::updateOrCreate(
|
|
[
|
|
'google_keyword_id' => $keyword->id,
|
|
'date' => $metric['date'],
|
|
],
|
|
[
|
|
'impressions' => $metric['impressions'],
|
|
'clicks' => $metric['clicks'],
|
|
'actual_spend' => $metric['actual_spend'],
|
|
'conversions' => $metric['conversions'],
|
|
]
|
|
);
|
|
$this->info("Client ID: {$client->customer_id}, Keyword: {$keyword->text}, Date: {$metric['date']} , Impressions: {$metric['impressions']}, Clicks: {$metric['clicks']}, Cost: {$metric['actual_spend']}");
|
|
}
|
|
} else {
|
|
$this->info("No metrics found for Client ID: {$client->customer_id}, Keyword: {$keyword->text}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
DB::commit();
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
Log::error('Error getting campaign details: '.$e->getMessage(), [
|
|
'trace' => $e->getTraceAsString(),
|
|
]);
|
|
return 1;
|
|
}
|
|
|
|
}
|
|
}
|