89 lines
4.3 KiB
PHP
89 lines
4.3 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Client;
|
|
use App\Models\GoogleAd;
|
|
use App\Models\GoogleAdGroup;
|
|
use App\Models\GoogleAdGroupMetric;
|
|
use App\Models\GoogleAdMetric;
|
|
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 GetGoogleAdsMetric extends Command
|
|
{
|
|
protected $signature = 'google-ads:get-ads-metric';
|
|
protected $description = 'Get ads 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) {
|
|
$ads = GoogleAd::where('google_ad_group_id', $adGroup->id)->get();
|
|
if ($ads->isEmpty()) {
|
|
$this->info("No ads found for Ad Group ID: {$adGroup->ad_group_id} under Client ID: {$client->customer_id}");
|
|
continue;
|
|
} else {
|
|
foreach ($ads as $ad) {
|
|
$metrics = $adsService->getAdMetricsById($client->customer_id, $ad->ad_id, '1970-01-01');
|
|
// $metrics = $adsService->getAdMetricsById($client->customer_id, $ad->ad_id);
|
|
if (! empty($metrics)) {
|
|
foreach ($metrics as $metric) {
|
|
GoogleAdMetric::updateOrCreate(
|
|
[
|
|
'google_ad_id' => $ad->id,
|
|
'date' => $metric['date'],
|
|
],
|
|
[
|
|
'impressions' => $metric['impressions'],
|
|
'clicks' => $metric['clicks'],
|
|
'actual_spend' => $metric['spend'],
|
|
'conversions' => $metric['conversions'],
|
|
]
|
|
);
|
|
$this->info("Ad Metric for Ad ID: {$ad->ad_id} under Client ID: {$client->customer_id} for Date: {$metric['date']} has been updated/created.");
|
|
}
|
|
} else {
|
|
$this->info("No metrics found for Ad ID: {$ad->ad_id} under Client ID: {$client->customer_id}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
DB::commit();
|
|
} catch (\Exception $e) {
|
|
DB::rollBack();
|
|
Log::error('Error getting campaign details: '.$e->getMessage(), [
|
|
'trace' => $e->getTraceAsString(),
|
|
]);
|
|
return 1;
|
|
}
|
|
|
|
}
|
|
}
|