Commit 09b535b6 by Vladislav

fix both in app/Console/Kernel.php

2 parents c1a48d60 ff2fdde6
Showing with 908 additions and 105 deletions
...@@ -3,11 +3,9 @@ ...@@ -3,11 +3,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Models\Variable;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class AdGroupsAdd extends Command class AdGroupsAdd extends Command
{ {
......
<?php
namespace App\Console\Commands;
use App\Models\Campaigns;
use App\Models\Tokens;
use App\Service\API\API;
use App\Service\Requests\APIRequest;
use Illuminate\Console\Command;
class AdGroupsLoadKeywords extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'adgroups:loadKeywords';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Загрузка фраз РК';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
* @throws \Exception
*/
public function handle()
{
$campaigns = Campaigns::has('groupsForKeywordsLoadable')
->with('groupsForKeywordsLoadable')
->forManaged()->forEnabled()->forNotGroupsLoadable()->get();
if (!$campaigns->count()) {
return;
}
$token = Tokens::where('type', Tokens::MAIN)->first();
if (!$token) {
throw new \Exception('Не найден токен блин');
}
$ad_group_ids = $campaigns->pluck('groupsForKeywordsLoadable')
->collapse()
->pluck('external_id')
->all();
$factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token);
$factory->getRequest('Keywords', 'get')
->call([
'AdGroupIds' => $ad_group_ids,
]);
return 0;
}
}
...@@ -2,18 +2,11 @@ ...@@ -2,18 +2,11 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\AdGroup; use App\Models\AdGroup;
use App\Models\Campaigns;
use App\Models\Pivots\DictionaryCampaign;
use App\Models\Tokens; use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Direct\CheckDictionaries;
use App\Service\Direct\GetCampaigns;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Facades\Bus;
class AdGroupsLoadUpdated extends Command class AdGroupsLoadUpdated extends Command
{ {
...@@ -49,22 +42,32 @@ class AdGroupsLoadUpdated extends Command ...@@ -49,22 +42,32 @@ class AdGroupsLoadUpdated extends Command
public function handle() public function handle()
{ {
$adGroups = AdGroup::has('campaignForEnabledForManaged')->forUpdatedSelf()->get(); $adGroups = AdGroup::has('campaignForEnabledForManaged')->forUpdatedSelf()->get();
if (!$adGroups->count()) {
return; if ($adGroups->count()) {
}
$token = Tokens::where('type', Tokens::MAIN)->first(); $token = Tokens::where('type', Tokens::MAIN)->first();
if (!$token) { if (!$token) {
throw new \Exception('Не найден токен блин'); throw new \Exception('Не найден токен блин');
} }
$ids = $adGroups->pluck('external_id')->all();
$factory = APIRequest::getInstance(API::YANDEX); $factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token); $factory->setToken($token);
$factory->getRequest('AdGroups', 'get')->call([ $factory->getRequest('AdGroups', 'get')->call([
'Ids' => $adGroups->pluck('external_id')->all(), 'Ids' => $ids,
]); ]);
$factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token);
$factory->getRequest('Keywords', 'get')->call([
'AdGroupIds' => $ids,
]);
}
$tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf') $tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf')
->with('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf') ->with('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf')
->where('type', '!=', Tokens::MAIN) ->where('type', '!=', Tokens::MAIN)
...@@ -74,11 +77,20 @@ class AdGroupsLoadUpdated extends Command ...@@ -74,11 +77,20 @@ class AdGroupsLoadUpdated extends Command
$factory = APIRequest::getInstance(API::YANDEX); $factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token); $factory->setToken($token);
$factory->getRequest('AdGroups', 'get')->call([ $ids = $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('groupsForExternalForUpdatedSelf')
'Ids' => $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('groupsForExternalForUpdatedSelf')
->collapse() ->collapse()
->pluck('external_id') ->pluck('external_id')
->all(), ->all();
$factory->getRequest('AdGroups', 'get')->call([
'Ids' => $ids,
]);
$factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token);
$factory->getRequest('Keywords', 'get')->call([
'AdGroupIds' => $ids,
]); ]);
} }
......
...@@ -3,11 +3,9 @@ ...@@ -3,11 +3,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Models\Variable;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class AdGroupsUpdate extends Command class AdGroupsUpdate extends Command
{ {
...@@ -55,7 +53,7 @@ class AdGroupsUpdate extends Command ...@@ -55,7 +53,7 @@ class AdGroupsUpdate extends Command
$factory->setToken($token); $factory->setToken($token);
$factory->getRequest('AdGroup', 'update') $factory->getRequest('AdGroups', 'update')
->call([ ->call([
'goalAdGroups' => $token->dictionaryCampaignsEnabledForExternalUpdated->pluck('groupsForExternalForNeedUpdated') 'goalAdGroups' => $token->dictionaryCampaignsEnabledForExternalUpdated->pluck('groupsForExternalForNeedUpdated')
->collapse(), ->collapse(),
......
...@@ -3,11 +3,9 @@ ...@@ -3,11 +3,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Models\Variable;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class CampaignsAdd extends Command class CampaignsAdd extends Command
{ {
......
...@@ -2,17 +2,11 @@ ...@@ -2,17 +2,11 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Campaigns; use App\Models\Campaigns;
use App\Models\Pivots\DictionaryCampaign;
use App\Models\Tokens; use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Direct\CheckDictionaries;
use App\Service\Direct\GetCampaigns;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Facades\Bus;
class CampaignsCheckUpdatedChildrenAdGroups extends Command class CampaignsCheckUpdatedChildrenAdGroups extends Command
{ {
...@@ -47,9 +41,7 @@ class CampaignsCheckUpdatedChildrenAdGroups extends Command ...@@ -47,9 +41,7 @@ class CampaignsCheckUpdatedChildrenAdGroups extends Command
*/ */
public function handle() public function handle()
{ {
if (!Campaigns::forUpdatedChildren()->exists()) { if (Campaigns::forUpdatedChildren()->exists()) {
return;
}
$token = Tokens::where('type', Tokens::MAIN)->first(); $token = Tokens::where('type', Tokens::MAIN)->first();
if (!$token) { if (!$token) {
...@@ -67,6 +59,8 @@ class CampaignsCheckUpdatedChildrenAdGroups extends Command ...@@ -67,6 +59,8 @@ class CampaignsCheckUpdatedChildrenAdGroups extends Command
'Timestamp' => $token->check_changes_ad_group_at->toIso8601ZuluString(), 'Timestamp' => $token->check_changes_ad_group_at->toIso8601ZuluString(),
]); ]);
}
$tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedChildren') $tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedChildren')
->with('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedChildren') ->with('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedChildren')
->where('type', '!=', Tokens::MAIN) ->where('type', '!=', Tokens::MAIN)
......
...@@ -6,6 +6,7 @@ use App\Models\Tokens; ...@@ -6,6 +6,7 @@ use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class CampaignsFirstLoad extends Command class CampaignsFirstLoad extends Command
{ {
...@@ -48,8 +49,10 @@ class CampaignsFirstLoad extends Command ...@@ -48,8 +49,10 @@ class CampaignsFirstLoad extends Command
$factory = APIRequest::getInstance(API::YANDEX); $factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token); $factory->setToken($token);
$factory->getRequest('Changes', 'CheckDictionaries')->call();
$factory->getRequest('Campaigns', 'get')->call(); $factory->getRequest('Campaigns', 'get')->call();
Artisan::call(DictionariesLoad::class);
Artisan::call(CampaignsLoadGroups::class);
Artisan::call(AdGroupsLoadKeywords::class);
return 0; return 0;
} }
......
...@@ -43,6 +43,7 @@ class CampaignsLoadGroups extends Command ...@@ -43,6 +43,7 @@ class CampaignsLoadGroups extends Command
public function handle() public function handle()
{ {
$campaigns = Campaigns::forManaged()->forEnabled()->forGroupsLoadable()->get(); $campaigns = Campaigns::forManaged()->forEnabled()->forGroupsLoadable()->get();
if (!$campaigns->count()) { if (!$campaigns->count()) {
return; return;
} }
...@@ -55,10 +56,11 @@ class CampaignsLoadGroups extends Command ...@@ -55,10 +56,11 @@ class CampaignsLoadGroups extends Command
$factory = APIRequest::getInstance(API::YANDEX); $factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token); $factory->setToken($token);
$campaign_ids = $campaigns->pluck('external_id')->all();
$factory->getRequest('AdGroups', 'get') $factory->getRequest('AdGroups', 'get')
->call([ ->call([
'CampaignIds' => $campaigns->pluck('external_id')->all(), 'CampaignIds' => $campaign_ids,
]); ]);
return 0; return 0;
......
...@@ -2,17 +2,13 @@ ...@@ -2,17 +2,13 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Campaigns; use App\Models\Campaigns;
use App\Models\Pivots\DictionaryCampaign;
use App\Models\Tokens; use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Direct\CheckDictionaries; use App\Service\Direct\CheckDictionaries;
use App\Service\Direct\GetCampaigns; use App\Service\Direct\GetCampaigns;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Support\Facades\Bus;
class CampaignsLoadUpdated extends Command class CampaignsLoadUpdated extends Command
{ {
...@@ -48,9 +44,8 @@ class CampaignsLoadUpdated extends Command ...@@ -48,9 +44,8 @@ class CampaignsLoadUpdated extends Command
public function handle() public function handle()
{ {
$campaigns = Campaigns::forEnabled()->forUpdatedSelf()->get(); $campaigns = Campaigns::forEnabled()->forUpdatedSelf()->get();
if (!$campaigns->count()) {
return; if ($campaigns->count()) {
}
$token = Tokens::where('type', Tokens::MAIN)->first(); $token = Tokens::where('type', Tokens::MAIN)->first();
if (!$token) { if (!$token) {
...@@ -64,6 +59,8 @@ class CampaignsLoadUpdated extends Command ...@@ -64,6 +59,8 @@ class CampaignsLoadUpdated extends Command
'ids' => $campaigns->pluck('external_id')->all(), 'ids' => $campaigns->pluck('external_id')->all(),
]); ]);
}
$tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedSelf') $tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedSelf')
->with('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedSelf') ->with('dictionaryCampaignsEnabledForExternalSynchronizedUpdatedSelf')
->where('type', '!=', Tokens::MAIN) ->where('type', '!=', Tokens::MAIN)
......
...@@ -3,12 +3,9 @@ ...@@ -3,12 +3,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Models\Variable;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class CampaignsResume extends Command class CampaignsResume extends Command
{ {
......
...@@ -6,8 +6,6 @@ use App\Models\Tokens; ...@@ -6,8 +6,6 @@ use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class CampaignsSuspend extends Command class CampaignsSuspend extends Command
{ {
......
...@@ -3,11 +3,9 @@ ...@@ -3,11 +3,9 @@
namespace App\Console\Commands; namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Models\Variable;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
class CampaignsUpdate extends Command class CampaignsUpdate extends Command
{ {
......
...@@ -4,8 +4,6 @@ namespace App\Console\Commands; ...@@ -4,8 +4,6 @@ namespace App\Console\Commands;
use App\Models\Tokens; use App\Models\Tokens;
use App\Service\API\API; use App\Service\API\API;
use App\Service\Direct\CheckDictionaries;
use App\Service\Direct\GetCampaigns;
use App\Service\Requests\APIRequest; use App\Service\Requests\APIRequest;
use Illuminate\Console\Command; use Illuminate\Console\Command;
......
...@@ -9,6 +9,7 @@ use App\Console\Commands\CampaignsAdd; ...@@ -9,6 +9,7 @@ use App\Console\Commands\CampaignsAdd;
use App\Console\Commands\CampaignsCheckChange; use App\Console\Commands\CampaignsCheckChange;
use App\Console\Commands\CampaignsCheckUpdatedChildrenAdGroups; use App\Console\Commands\CampaignsCheckUpdatedChildrenAdGroups;
use App\Console\Commands\CampaignsLoadGroups; use App\Console\Commands\CampaignsLoadGroups;
use App\Console\Commands\AdGroupsLoadKeywords;
use App\Console\Commands\CampaignsResume; use App\Console\Commands\CampaignsResume;
use App\Console\Commands\CampaignsSuspend; use App\Console\Commands\CampaignsSuspend;
use App\Console\Commands\CampaignsUpdate; use App\Console\Commands\CampaignsUpdate;
...@@ -48,8 +49,9 @@ class Kernel extends ConsoleKernel ...@@ -48,8 +49,9 @@ class Kernel extends ConsoleKernel
$schedule->command(CampaignsResume::class)->hourlyAt(20); $schedule->command(CampaignsResume::class)->hourlyAt(20);
$schedule->command(CampaignsSuspend::class)->hourlyAt(20); $schedule->command(CampaignsSuspend::class)->hourlyAt(20);
$schedule->command(AdGroupsLoadUpdated::class)->hourlyAt(20); $schedule->command(AdGroupsLoadUpdated::class)->hourlyAt(20);
$schedule->command(AdGroupsLoadKeywords::class)->hourlyAt(20);
// $schedule->command(CampaignsLoadGroups::class)->hourlyAt(40); $schedule->command(CampaignsLoadGroups::class)->hourlyAt(40);
$schedule->command(AdGroupsAdd::class)->hourlyAt(30); $schedule->command(AdGroupsAdd::class)->hourlyAt(30);
$schedule->command(AdGroupsUpdate::class)->hourlyAt(30); $schedule->command(AdGroupsUpdate::class)->hourlyAt(30);
} }
......
...@@ -97,9 +97,18 @@ class TokensController extends Controller ...@@ -97,9 +97,18 @@ class TokensController extends Controller
return Redirect::back(); return Redirect::back();
} }
$campaign->update([ $data = [
'manage' => !!request('managed'), 'manage' => !!request('managed'),
];
if ($data['manage']) {
$data['groups_loaded_at'] = null;
$campaign->groups()->update([
'keywords_loaded_at' => null,
]); ]);
}
$campaign->update($data);
return Redirect::back()->with('success', 'Campaign ' . ($campaign->manage ? 'added' : 'deleted') . '.'); return Redirect::back()->with('success', 'Campaign ' . ($campaign->manage ? 'added' : 'deleted') . '.');
} }
...@@ -116,14 +125,21 @@ class TokensController extends Controller ...@@ -116,14 +125,21 @@ class TokensController extends Controller
return Redirect::back(); return Redirect::back();
} }
$enabled = !!request('enabled'); $data = [
'enabled' => !!request('enabled'),
];
$campaign->update([ if ($data['enabled']) {
'enabled' => $enabled, $data['groups_loaded_at'] = null;
$campaign->groups()->update([
'keywords_loaded_at' => null,
]); ]);
}
$campaign->update($data);
$campaign->dictionaryCampaigns()->update([ $campaign->dictionaryCampaigns()->update([
'enabled' => $enabled, 'enabled' => $campaign->enabled,
]); ]);
return Redirect::back()->with('success', 'Campaign ' . ($campaign->enabled ? 'enabled' : 'disabled') . '.'); return Redirect::back()->with('success', 'Campaign ' . ($campaign->enabled ? 'enabled' : 'disabled') . '.');
......
...@@ -25,6 +25,13 @@ use Illuminate\Support\Collection; ...@@ -25,6 +25,13 @@ use Illuminate\Support\Collection;
* @property array|null $region_ids * @property array|null $region_ids
* @property array|null $negative_keywords * @property array|null $negative_keywords
* @property array|null $negative_keyword_shared_set_ids * @property array|null $negative_keyword_shared_set_ids
* @property array|null $mobile_app_ad_group
* @property array|null $dynamic_text_ad_group
* @property array|null $dynamic_text_feed_ad_group
* @property array|null $cpm_banner_user_profile_ad_group
* @property array|null $cpm_video_ad_group
* @property array|null $smart_ad_group
* @property \Illuminate\Support\Carbon|null $keywords_loaded_at
* @property \Illuminate\Support\Carbon|null $updated_self * @property \Illuminate\Support\Carbon|null $updated_self
* @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at * @property \Illuminate\Support\Carbon|null $updated_at
...@@ -32,6 +39,16 @@ use Illuminate\Support\Collection; ...@@ -32,6 +39,16 @@ use Illuminate\Support\Collection;
* @property-read \App\Models\Campaigns|null $campaignForEnabledForManaged * @property-read \App\Models\Campaigns|null $campaignForEnabledForManaged
* @property-read \Illuminate\Database\Eloquent\Collection|GoalAdGroup[] $goalGroups * @property-read \Illuminate\Database\Eloquent\Collection|GoalAdGroup[] $goalGroups
* @property-read int|null $goal_groups_count * @property-read int|null $goal_groups_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Keyword[] $keywords
* @property-read int|null $keywords_count
* @method static Builder|AdGroup whereCpmBannerUserProfileAdGroup($value)
* @method static Builder|AdGroup whereCpmVideoAdGroup($value)
* @method static Builder|AdGroup whereDynamicTextAdGroup($value)
* @method static Builder|AdGroup whereDynamicTextFeedAdGroup($value)
* @method static Builder|AdGroup whereKeywordsLoadedAt($value)
* @method static Builder|AdGroup whereMobileAppAdGroup($value)
* @method static Builder|AdGroup whereSmartAdGroup($value)
* @method static Builder|AdGroup forKeywordsLoadable()
* @method static Builder|AdGroup forUpdatedSelf() * @method static Builder|AdGroup forUpdatedSelf()
* @method static Builder|AdGroup newModelQuery() * @method static Builder|AdGroup newModelQuery()
* @method static Builder|AdGroup newQuery() * @method static Builder|AdGroup newQuery()
...@@ -102,10 +119,10 @@ class AdGroup extends Model ...@@ -102,10 +119,10 @@ class AdGroup extends Model
'serving_status', 'serving_status',
'restricted_region_ids', 'restricted_region_ids',
'updated_self', 'updated_self',
'keywords_loaded_at',
]; ];
protected $casts = [ protected $casts = [
'campaign_id' => 'int',
'region_ids' => 'array', 'region_ids' => 'array',
'negative_keywords' => 'json', 'negative_keywords' => 'json',
'negative_keyword_shared_set_ids' => 'json', 'negative_keyword_shared_set_ids' => 'json',
...@@ -117,6 +134,7 @@ class AdGroup extends Model ...@@ -117,6 +134,7 @@ class AdGroup extends Model
'smart_ad_group' => 'json', 'smart_ad_group' => 'json',
'restricted_region_ids' => 'json', 'restricted_region_ids' => 'json',
'updated_self' => 'datetime', 'updated_self' => 'datetime',
'keywords_loaded_at' => 'datetime',
]; ];
/** /**
...@@ -183,11 +201,25 @@ class AdGroup extends Model ...@@ -183,11 +201,25 @@ class AdGroup extends Model
return $query->whereNotNull("{$query->getModel()->getTable()}.updated_self"); return $query->whereNotNull("{$query->getModel()->getTable()}.updated_self");
} }
/**
* @param Builder $query
* @return Builder
*/
public function scopeForKeywordsLoadable($query)
{
return $query->whereNull('keywords_loaded_at');
}
public function goalGroups() public function goalGroups()
{ {
return $this->hasMany(GoalAdGroup::class, 'ad_group_id'); return $this->hasMany(GoalAdGroup::class, 'ad_group_id');
} }
public function keywords()
{
return $this->hasMany(Keyword::class, 'ad_group_id');
}
public function campaign() public function campaign()
{ {
return $this->belongsTo(Campaigns::class, 'campaign_id'); return $this->belongsTo(Campaigns::class, 'campaign_id');
......
...@@ -5,6 +5,7 @@ namespace App\Models; ...@@ -5,6 +5,7 @@ namespace App\Models;
use App\Models\Pivots\DictionaryCampaignVariable; use App\Models\Pivots\DictionaryCampaignVariable;
use App\Models\Pivots\DictionaryCampaign; use App\Models\Pivots\DictionaryCampaign;
use App\Models\Pivots\GoalAdGroup; use App\Models\Pivots\GoalAdGroup;
use App\Models\Pivots\GoalKeyword;
use Carbon\Carbon; use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Factories\HasFactory;
...@@ -40,12 +41,16 @@ use Illuminate\Support\Collection; ...@@ -40,12 +41,16 @@ use Illuminate\Support\Collection;
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Dictionary[] $dictionaries * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Dictionary[] $dictionaries
* @property-read int|null $dictionaries_count * @property-read int|null $dictionaries_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $groups * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $groups
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $groupsForKeywordsLoadable
* @property-read int|null $groups_count * @property-read int|null $groups_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Variable[] $dictionaryCampaignVariables * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Variable[] $dictionaryCampaignVariables
* @property-read int|null $dictionary_campaign_variables_count * @property-read int|null $dictionary_campaign_variables_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Variable[] $dictionaryCampaigns * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Variable[] $dictionaryCampaigns
* @property-read int|null $dictionary_campaigns_count * @property-read int|null $dictionary_campaigns_count
* @property string|null $keywords_loaded_at
* @method static Builder|Campaigns whereKeywordsLoadedAt($value)
* @method static Builder|Campaigns forGroupsLoadable() * @method static Builder|Campaigns forGroupsLoadable()
* @method static Builder|Campaigns forNotGroupsLoadable()
* @method static Builder|Campaigns forManaged($value = true) * @method static Builder|Campaigns forManaged($value = true)
* @method static Builder|Campaigns forEnabled($value = true) * @method static Builder|Campaigns forEnabled($value = true)
* @method static Builder|Campaigns notDisabled() * @method static Builder|Campaigns notDisabled()
...@@ -103,6 +108,7 @@ class Campaigns extends Model ...@@ -103,6 +108,7 @@ class Campaigns extends Model
'relevant_keywords', 'relevant_keywords',
'attribution_model', 'attribution_model',
'priority_goals', 'priority_goals',
'groups_loaded_at',
'updated_self', 'updated_self',
'updated_children', 'updated_children',
'manage', 'manage',
...@@ -176,6 +182,7 @@ class Campaigns extends Model ...@@ -176,6 +182,7 @@ class Campaigns extends Model
if ($campaign->manage) { if ($campaign->manage) {
$campaign->copyInGoalCampaign(); $campaign->copyInGoalCampaign();
$campaign->copyGroupInGoalGroup(); $campaign->copyGroupInGoalGroup();
$campaign->copyGroupInGoalKeyword();
} }
}); });
...@@ -185,6 +192,7 @@ class Campaigns extends Model ...@@ -185,6 +192,7 @@ class Campaigns extends Model
if ($campaign->manage) { if ($campaign->manage) {
$campaign->copyInGoalCampaign(); $campaign->copyInGoalCampaign();
$campaign->copyGroupInGoalGroup(); $campaign->copyGroupInGoalGroup();
$campaign->copyGroupInGoalKeyword();
} else { } else {
$campaign->dictionaries()->detach(); $campaign->dictionaries()->detach();
} }
...@@ -230,8 +238,9 @@ class Campaigns extends Model ...@@ -230,8 +238,9 @@ class Campaigns extends Model
$campaign->groups()->get()->each(function (AdGroup $adGroup) use ($dictionaryCampaign) { $campaign->groups()->get()->each(function (AdGroup $adGroup) use ($dictionaryCampaign) {
$dictionaryCampaign->groups()->updateOrCreate([ GoalAdGroup::updateOrCreate([
'campaign_external_id' => $dictionaryCampaign->external_id, 'dictionary_campaign_id' => $dictionaryCampaign->getKey(),
'dictionary_campaign_external_id' => $dictionaryCampaign->external_id,
'ad_group_id' => $adGroup->getKey(), 'ad_group_id' => $adGroup->getKey(),
], GoalAdGroup::copyPropertyFromMain($adGroup)); ], GoalAdGroup::copyPropertyFromMain($adGroup));
...@@ -240,6 +249,31 @@ class Campaigns extends Model ...@@ -240,6 +249,31 @@ class Campaigns extends Model
}); });
} }
public function copyGroupInGoalKeyword()
{
$campaign = $this;
$campaign->dictionaryCampaigns()->get()->each(function (DictionaryCampaign $dictionaryCampaign) use ($campaign) {
$dictionaryCampaign->groups()->get()->each(function (GoalAdGroup $goalAdGroup) use ($campaign, $dictionaryCampaign) {
$goalAdGroup->group->keywords()->where('campaign_id', $campaign->getKey())->get()->each(function (Keyword $keyword) use ($dictionaryCampaign, $goalAdGroup) {
GoalKeyword::updateOrCreate([
'dictionary_campaign_id' => $dictionaryCampaign->getKey(),
'dictionary_campaign_external_id' => $dictionaryCampaign->external_id,
'goal_ad_group_id' => $goalAdGroup->getKey(),
'goal_ad_group_external_id' => $goalAdGroup->external_id,
'keyword_id' => $keyword->getKey(),
], GoalKeyword::copyPropertyFromMain($keyword));
});
});
});
}
public function getBiddingStrategyAttribute($bidding_strategy) public function getBiddingStrategyAttribute($bidding_strategy)
{ {
$bidding_strategy = json_decode($bidding_strategy, true); $bidding_strategy = json_decode($bidding_strategy, true);
...@@ -321,6 +355,11 @@ class Campaigns extends Model ...@@ -321,6 +355,11 @@ class Campaigns extends Model
return $this->hasMany(AdGroup::class, 'campaign_id'); return $this->hasMany(AdGroup::class, 'campaign_id');
} }
public function groupsForKeywordsLoadable()
{
return $this->groups()->forKeywordsLoadable();
}
public function dictionaryCampaigns() public function dictionaryCampaigns()
{ {
return $this->hasMany(DictionaryCampaign::class, 'campaign_id'); return $this->hasMany(DictionaryCampaign::class, 'campaign_id');
...@@ -368,6 +407,15 @@ class Campaigns extends Model ...@@ -368,6 +407,15 @@ class Campaigns extends Model
/** /**
* @param Builder $query * @param Builder $query
* @return Builder
*/
public function scopeForNotGroupsLoadable($query)
{
return $query->whereNotNull('groups_loaded_at');
}
/**
* @param Builder $query
* @param bool $manage * @param bool $manage
* @return Builder * @return Builder
*/ */
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
namespace App\Models; namespace App\Models;
use App\Models\Pivots\DictionaryCampaign; use App\Models\Pivots\DictionaryCampaign;
use App\Models\Pivots\DictionaryCampaignVariable;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
/** /**
......
<?php
namespace App\Models;
use App\Models\Pivots\GoalKeyword;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
/**
* App\Models\Keyword
*
* @property int $id
* @property int $external_id
* @property int $ad_group_external_id
* @property int $campaign_external_id
* @property int $ad_group_id
* @property int $campaign_id
* @property string|null $keyword
* @property string|null $user_param_1
* @property string|null $user_param_2
* @property int|null $bid
* @property int|null $context_bid
* @property string|null $state
* @property string|null $status
* @property string|null $serving_status
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \App\Models\Campaigns $campaign
* @property-read \Illuminate\Database\Eloquent\Collection|GoalKeyword[] $goalKeywords
* @property-read int|null $goal_keywords_count
* @property-read \App\Models\AdGroup $group
* @method static \Illuminate\Database\Eloquent\Builder|Keyword newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Keyword newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|Keyword query()
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereAdGroupExternalId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereAdGroupId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereBid($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereCampaignExternalId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereCampaignId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereContextBid($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereExternalId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereKeyword($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereServingStatus($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereState($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereStatus($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereUserParam1($value)
* @method static \Illuminate\Database\Eloquent\Builder|Keyword whereUserParam2($value)
* @mixin \Eloquent
*/
class Keyword extends Model
{
const STATE_OFF = 'OFF';
const STATE_ON = 'ON';
const STATE_SUSPENDED = 'SUSPENDED';
const STATUS_ACCEPTED = 'ACCEPTED';
const STATUS_DRAFT = 'DRAFT';
const STATUS_REJECTED = 'REJECTED';
const STATUS_UNKNOWN = 'UNKNOWN';
const SERVING_STATUS_ELIGIBLE = 'ELIGIBLE';
const SERVING_STATUS_RARELY_SERVED = 'RARELY_SERVED';
protected $fillable = [
'external_id',
'ad_group_external_id',
'campaign_external_id',
'ad_group_id',
'campaign_id',
'keyword',
'user_param_1',
'user_param_2',
'bid',
'context_bid',
'state',
'status',
'serving_status',
'updated_self',
];
protected $casts = [
'updated_self' => 'datetime',
];
/**
* @return Collection
*/
static public function getPropertiesWatch()
{
return collect([
'keyword',
'user_param_1',
'user_param_2',
]);
}
public static function boot()
{
parent::boot();
static::created(function (Keyword $keyword) {
if ($keyword->campaign) {
$keyword->campaign->copyGroupInGoalKeyword();
}
});
static::updated(function (Keyword $keyword) {
if (GoalKeyword::getPropertiesCopyWithPivot()->first(function ($property_name) use ($keyword) {
return $keyword->{$property_name} !== $keyword->getOriginal($property_name);
})) {
if (!is_null($keyword->campaign_id) && is_null($keyword->getOriginal('campaign_id'))) {
$keyword->campaign->copyGroupInGoalKeyword();
} else {
$keyword->goalKeywords()->update(
GoalKeyword::copyPropertyFromMain($keyword)
);
}
}
if (self::getPropertiesWatch()->first(function ($property_name) use ($keyword) {
return $keyword->{$property_name} !== $keyword->getOriginal($property_name);
})) {
$keyword->goalKeywords()->update([
'updated_need' => Carbon::now(),
]);
}
});
}
public function goalKeywords()
{
return $this->hasMany(GoalKeyword::class, 'keyword_id');
}
public function group()
{
return $this->belongsTo(AdGroup::class, 'ad_group_id');
}
public function campaign()
{
return $this->belongsTo(Campaigns::class, 'campaign_id');
}
}
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
namespace App\Models\Pivots; namespace App\Models\Pivots;
use \App\Models\Pivots\GoalAdGroup;
use App\Models\Campaigns; use App\Models\Campaigns;
use App\Models\Dictionary; use App\Models\Dictionary;
use App\Models\Variable; use App\Models\Variable;
...@@ -77,6 +76,8 @@ use Illuminate\Support\Collection; ...@@ -77,6 +76,8 @@ use Illuminate\Support\Collection;
* @method static Builder|DictionaryCampaign whereSynced($value) * @method static Builder|DictionaryCampaign whereSynced($value)
* @method static Builder|DictionaryCampaign whereUpdatedChildren($value) * @method static Builder|DictionaryCampaign whereUpdatedChildren($value)
* @method static Builder|DictionaryCampaign whereUpdatedSelf($value) * @method static Builder|DictionaryCampaign whereUpdatedSelf($value)
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Pivots\GoalKeyword[] $goalKeywords
* @property-read int|null $goal_keywords_count
*/ */
class DictionaryCampaign extends Pivot class DictionaryCampaign extends Pivot
{ {
...@@ -102,8 +103,6 @@ class DictionaryCampaign extends Pivot ...@@ -102,8 +103,6 @@ class DictionaryCampaign extends Pivot
]; ];
protected $casts = [ protected $casts = [
'campaign_id' => 'int',
'dictionary_id' => 'int',
'negative_keywords' => 'array', 'negative_keywords' => 'array',
'excluded_sites' => 'array', 'excluded_sites' => 'array',
'external_upload_at' => 'datetime', 'external_upload_at' => 'datetime',
...@@ -330,4 +329,9 @@ class DictionaryCampaign extends Pivot ...@@ -330,4 +329,9 @@ class DictionaryCampaign extends Pivot
return $this->groups()->forExternal()->needUpdated(); return $this->groups()->forExternal()->needUpdated();
} }
public function goalKeywords()
{
return $this->hasMany(GoalKeyword::class, 'dictionary_campaign_id');
}
} }
...@@ -40,8 +40,6 @@ class DictionaryCampaignVariable extends Pivot ...@@ -40,8 +40,6 @@ class DictionaryCampaignVariable extends Pivot
]; ];
protected $casts = [ protected $casts = [
'dictionary_campaign_id' => 'int',
'variable_id' => 'int',
]; ];
static public function getWithPivot() static public function getWithPivot()
......
...@@ -13,7 +13,7 @@ use Illuminate\Support\Collection; ...@@ -13,7 +13,7 @@ use Illuminate\Support\Collection;
* *
* @property int $id * @property int $id
* @property int|null $external_id * @property int|null $external_id
* @property int|null $campaign_external_id * @property int|null $dictionary_campaign_external_id
* @property int $dictionary_campaign_id * @property int $dictionary_campaign_id
* @property string|null $name * @property string|null $name
* @property array|null $negative_keywords * @property array|null $negative_keywords
...@@ -51,6 +51,8 @@ use Illuminate\Support\Collection; ...@@ -51,6 +51,8 @@ use Illuminate\Support\Collection;
* @method static Builder|GoalAdGroup whereUpdatedNeed($value) * @method static Builder|GoalAdGroup whereUpdatedNeed($value)
* @method static Builder|GoalAdGroup whereUpdatedSelf($value) * @method static Builder|GoalAdGroup whereUpdatedSelf($value)
* @mixin \Eloquent * @mixin \Eloquent
* @property-read \App\Models\Pivots\GoalKeyword $goalKeywords
* @method static Builder|GoalAdGroup whereDictionaryCampaignExternalId($value)
*/ */
class GoalAdGroup extends Pivot class GoalAdGroup extends Pivot
{ {
...@@ -59,7 +61,7 @@ class GoalAdGroup extends Pivot ...@@ -59,7 +61,7 @@ class GoalAdGroup extends Pivot
protected $fillable = [ protected $fillable = [
'external_id', 'external_id',
'campaign_external_id', 'dictionary_campaign_external_id',
'ad_group_id', 'ad_group_id',
'dictionary_campaign_id', 'dictionary_campaign_id',
'name', 'name',
...@@ -71,8 +73,6 @@ class GoalAdGroup extends Pivot ...@@ -71,8 +73,6 @@ class GoalAdGroup extends Pivot
]; ];
protected $casts = [ protected $casts = [
'ad_group_id' => 'int',
'dictionary_campaign_id' => 'int',
'negative_keywords' => 'array', 'negative_keywords' => 'array',
'external_upload_at' => 'datetime', 'external_upload_at' => 'datetime',
'external_updated_at' => 'datetime', 'external_updated_at' => 'datetime',
...@@ -85,7 +85,7 @@ class GoalAdGroup extends Pivot ...@@ -85,7 +85,7 @@ class GoalAdGroup extends Pivot
return [ return [
'id', 'id',
'external_id', 'external_id',
'campaign_external_id', 'dictionary_campaign_external_id',
'ad_group_id', 'ad_group_id',
'dictionary_campaign_id', 'dictionary_campaign_id',
'name', 'name',
...@@ -180,17 +180,9 @@ class GoalAdGroup extends Pivot ...@@ -180,17 +180,9 @@ class GoalAdGroup extends Pivot
return $this->belongsTo(DictionaryCampaign::class, 'dictionary_campaign_id'); return $this->belongsTo(DictionaryCampaign::class, 'dictionary_campaign_id');
} }
public function dictionaryCampaignVariables() public function goalKeywords()
{ {
return $this->hasMany(DictionaryCampaignVariable::class, 'dictionary_campaign_id'); return $this->belongsTo(GoalKeyword::class, 'goal_ad_group_id');
}
public function variables()
{
return $this->belongsToMany(Variable::class, 'dictionary_campaign_variables', 'dictionary_campaign_id', 'variable_id')
->using(DictionaryCampaignVariable::class)
->withPivot(DictionaryCampaignVariable::getWithPivot())
->withTimestamps();
} }
} }
<?php
namespace App\Models\Pivots;
use App\Models\Keyword;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Support\Collection;
/**
* App\Models\Pivots\GoalKeyword
*
* @property int $id
* @property int|null $external_id
* @property int|null $dictionary_campaign_external_id
* @property int|null $goal_ad_group_external_id
* @property int $dictionary_campaign_id
* @property int $goal_ad_group_id
* @property int $keyword_id
* @property \Illuminate\Support\Carbon|null $external_upload_at
* @property \Illuminate\Support\Carbon|null $external_updated_at
* @property \Illuminate\Support\Carbon|null $updated_need
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read Keyword $keyword
* @method static Builder|GoalKeyword forExternal()
* @method static Builder|GoalKeyword forNotExternal()
* @method static Builder|GoalKeyword needUpdated()
* @method static Builder|GoalKeyword newModelQuery()
* @method static Builder|GoalKeyword newQuery()
* @method static Builder|GoalKeyword query()
* @method static Builder|GoalKeyword whereCreatedAt($value)
* @method static Builder|GoalKeyword whereDictionaryCampaignExternalId($value)
* @method static Builder|GoalKeyword whereDictionaryCampaignId($value)
* @method static Builder|GoalKeyword whereExternalId($value)
* @method static Builder|GoalKeyword whereExternalUpdatedAt($value)
* @method static Builder|GoalKeyword whereExternalUploadAt($value)
* @method static Builder|GoalKeyword whereGoalAdGroupExternalId($value)
* @method static Builder|GoalKeyword whereGoalAdGroupId($value)
* @method static Builder|GoalKeyword whereId($value)
* @method static Builder|GoalKeyword whereKeywordId($value)
* @method static Builder|GoalKeyword whereUpdatedAt($value)
* @method static Builder|GoalKeyword whereUpdatedNeed($value)
* @mixin \Eloquent
*/
class GoalKeyword extends Pivot
{
protected $table = 'goal_keywords';
protected $fillable = [
'external_id',
'goal_ad_group_external_id',
'dictionary_campaign_external_id',
'goal_ad_group_id',
'dictionary_campaign_id',
'keyword_id',
'external_upload_at',
'external_updated_at',
'updated_need',
];
protected $casts = [
'external_upload_at' => 'datetime',
'external_updated_at' => 'datetime',
'updated_need' => 'datetime',
];
static public function getWithPivot()
{
return [
'id',
'external_id',
'goal_ad_group_external_id',
'dictionary_campaign_external_id',
'goal_ad_group_id',
'dictionary_campaign_id',
'keyword_id',
'external_upload_at',
'external_updated_at',
'updated_need',
];
}
/**
* @return Collection
*/
static public function getPropertiesCopyWithPivot()
{
return collect([
]);
}
/**
* @param Keyword|array $keyword
*
* @return array
*/
static public function copyPropertyFromMain($keyword)
{
return self::getPropertiesCopyWithPivot()
->transform(function ($property_name) use ($keyword) {
$value = null;
if ($keyword instanceof Keyword) {
$value = $keyword->{$property_name};
} elseif (is_array($keyword) && isset($keyword[$property_name])) {
$value = $keyword[$property_name];
}
return [
$property_name => $value
];
})
->collapse()
->put('keyword_id', $keyword[GoalKeyword::getModel()->getKeyName()])
->all();
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeForExternal($query)
{
return $query->whereNotNull('external_id');
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeForNotExternal($query)
{
return $query->whereNull('external_id');
}
/**
* @param Builder $query
* @return Builder
*/
public function scopeNeedUpdated($query)
{
return $query->whereNotNull('updated_need');
}
public function keyword()
{
return $this->belongsTo(Keyword::class, 'keyword_id');
}
}
...@@ -28,6 +28,7 @@ use Illuminate\Database\Eloquent\Model; ...@@ -28,6 +28,7 @@ use Illuminate\Database\Eloquent\Model;
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Campaigns[] $campaigns * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Campaigns[] $campaigns
* @property-read int|null $campaigns_count * @property-read int|null $campaigns_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $campaignsAdGroups * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $campaignsAdGroups
* @property-read int|null $campaigns_ad_groups_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $campaignsForEnabledAdGroupsForUpdatedSelf * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\AdGroup[] $campaignsForEnabledAdGroupsForUpdatedSelf
* @property-read int|null $campaigns_for_enabled_ad_groups_count * @property-read int|null $campaigns_for_enabled_ad_groups_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Campaigns[] $campaignsNotEnabledNotDisabled * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\Campaigns[] $campaignsNotEnabledNotDisabled
......
...@@ -58,7 +58,7 @@ class AddAdGroups extends DirectRequest ...@@ -58,7 +58,7 @@ class AddAdGroups extends DirectRequest
} }
foreach ($response['result']['AddResults'] as $key => $add_result) { foreach ($response['result']['AddResults'] as $key => $add_result) {
$external_id = $add_result['Id'] ?? ''; $external_id = (string)$add_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("AddAdGroup, empty Id"); Log::debug("AddAdGroup, empty Id");
...@@ -74,6 +74,10 @@ class AddAdGroups extends DirectRequest ...@@ -74,6 +74,10 @@ class AddAdGroups extends DirectRequest
'external_upload_at' => Carbon::now(), 'external_upload_at' => Carbon::now(),
]); ]);
$goalAdGroup->goalKeywords()->update([
'goal_ad_group_external_id' => $external_id,
]);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Log::debug($e); Log::debug($e);
...@@ -102,7 +106,7 @@ class AddAdGroups extends DirectRequest ...@@ -102,7 +106,7 @@ class AddAdGroups extends DirectRequest
$data = [ $data = [
'Name' => StrReplaceByVariables::getInstance($goalAdGroup->name, $list)->get(), 'Name' => StrReplaceByVariables::getInstance($goalAdGroup->name, $list)->get(),
'CampaignId' => $goalAdGroup->campaign_external_id, 'CampaignId' => $goalAdGroup->dictionary_campaign_external_id,
'RegionIds' => $goalAdGroup->group->region_ids, 'RegionIds' => $goalAdGroup->group->region_ids,
]; ];
......
...@@ -58,7 +58,7 @@ class AddCampaigns extends DirectRequest ...@@ -58,7 +58,7 @@ class AddCampaigns extends DirectRequest
} }
foreach ($response['result']['AddResults'] as $key => $add_result) { foreach ($response['result']['AddResults'] as $key => $add_result) {
$external_id = $add_result['Id'] ?? ''; $external_id = (string)$add_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("AddCampaigns, empty Id"); Log::debug("AddCampaigns, empty Id");
...@@ -75,7 +75,11 @@ class AddCampaigns extends DirectRequest ...@@ -75,7 +75,11 @@ class AddCampaigns extends DirectRequest
]); ]);
$dictionaryCampaign->groups()->update([ $dictionaryCampaign->groups()->update([
'campaign_external_id' => $external_id, 'dictionary_campaign_external_id' => $external_id,
]);
$dictionaryCampaign->goalKeywords()->update([
'dictionary_campaign_external_id' => $external_id,
]); ]);
} }
......
...@@ -39,7 +39,7 @@ class CheckCampaignsChanges extends DirectRequest ...@@ -39,7 +39,7 @@ class CheckCampaignsChanges extends DirectRequest
$data['updated_children'] = Carbon::now(); $data['updated_children'] = Carbon::now();
} }
$external_id = $campaign_data['CampaignId']; $external_id = (string)$campaign_data['CampaignId'];
if ($this->getToken()->isMain()) { if ($this->getToken()->isMain()) {
......
...@@ -74,6 +74,8 @@ class CheckChanges extends DirectRequest ...@@ -74,6 +74,8 @@ class CheckChanges extends DirectRequest
if (isset($response['result']['Modified']['AdGroupIds'])) { if (isset($response['result']['Modified']['AdGroupIds'])) {
foreach ($response['result']['Modified']['AdGroupIds'] as $ad_group_id) { foreach ($response['result']['Modified']['AdGroupIds'] as $ad_group_id) {
$ad_group_id = (string)$ad_group_id;
if ($this->getToken()->isMain()) { if ($this->getToken()->isMain()) {
$adGroup = AdGroup::where('external_id', $ad_group_id)->first(); $adGroup = AdGroup::where('external_id', $ad_group_id)->first();
......
...@@ -62,10 +62,12 @@ class GetAdGroups extends DirectRequest ...@@ -62,10 +62,12 @@ class GetAdGroups extends DirectRequest
} }
foreach ($response['result']['AdGroups'] as $ad_group) { foreach ($response['result']['AdGroups'] as $ad_group) {
if (isset($external_ids[$ad_group['CampaignId']])) { $external_id = (string)$ad_group['CampaignId'];
if (isset($external_ids[$external_id])) {
continue; continue;
} }
$external_ids[$ad_group['CampaignId']] = true; $external_ids[$external_id] = true;
} }
if (!count($external_ids)) { if (!count($external_ids)) {
...@@ -84,18 +86,22 @@ class GetAdGroups extends DirectRequest ...@@ -84,18 +86,22 @@ class GetAdGroups extends DirectRequest
foreach ($response['result']['AdGroups'] as $ad_group) { foreach ($response['result']['AdGroups'] as $ad_group) {
$campaign = $campaigns->firstWhere('external_id', $ad_group['CampaignId']); $external_id = (string)$ad_group['CampaignId'];
$campaign = $campaigns->firstWhere('external_id', $external_id);
if (!$campaign) if (!$campaign)
continue; continue;
$external_id = $ad_group['Id']; $external_id = (string)$ad_group['Id'];
if ($this->getToken()->isMain()) {
$data = [ $data = [
'campaign_id' => $campaign->getKey(), 'campaign_id' => $campaign->getKey(),
'external_id' => $external_id, 'external_id' => $external_id,
'campaign_external_id' => $ad_group['CampaignId'], 'campaign_external_id' => $campaign->external_id,
'name' => $ad_group['Name'], 'name' => $ad_group['Name'],
'region_ids' => $ad_group['RegionIds'], 'region_ids' => $ad_group['RegionIds'],
'negative_keywords' => $ad_group['NegativeKeywords'], 'negative_keywords' => $ad_group['NegativeKeywords'],
...@@ -116,24 +122,31 @@ class GetAdGroups extends DirectRequest ...@@ -116,24 +122,31 @@ class GetAdGroups extends DirectRequest
'updated_self' => null, 'updated_self' => null,
]; ];
if ($this->getToken()->isMain()) {
AdGroup::updateOrCreate([ AdGroup::updateOrCreate([
'external_id' => $external_id 'external_id' => $external_id,
'campaign_external_id' => $campaign->external_id,
], $data); ], $data);
$campaign->update([
'groups_loaded_at' => Carbon::now(),
]);
} else { } else {
$goalAdGroup = GoalAdGroup::find($external_id); $goalAdGroup = GoalAdGroup::firstWhere('external_id', $external_id);
if (!$goalAdGroup) if (!$goalAdGroup)
continue; continue;
$goalAdGroup->update( $data = [
$goalAdGroup::copyPropertyFromMain($data) 'external_updated_at' => Carbon::now(),
); ];
if ($campaign->updated) {
$data['updated_need'] = Carbon::now();
} }
$campaign->update([ $goalAdGroup->update($data);
'groups_loaded_at' => Carbon::now(), }
]);
} }
......
...@@ -50,7 +50,7 @@ class GetCampaigns extends DirectRequest ...@@ -50,7 +50,7 @@ class GetCampaigns extends DirectRequest
foreach ($response['result']['Campaigns'] as $campaign_data) { foreach ($response['result']['Campaigns'] as $campaign_data) {
$external_id = $campaign_data['Id']; $external_id = (string)$campaign_data['Id'];
$data = [ $data = [
'external_id' => $external_id, 'external_id' => $external_id,
......
<?php
namespace App\Service\Requests\Direct;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\AdGroup;
use App\Models\Campaigns;
use App\Models\Keyword;
use App\Models\Pivots\DictionaryCampaign;
use App\Models\Pivots\GoalAdGroup;
use App\Models\Pivots\GoalKeyword;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class GetKeywords extends DirectRequest
{
protected $max_count = -1;
protected $max_count_CampaignIds = 10;
protected $max_count_AdGroupIds = 1000;
protected $max_count_Ids = 10000;
function call($params = null)
{
$this->requestPrepare($params);
$process = new ProcessCallLimitedAPI($this);
dispatch($process)->onQueue('limits');
}
public function getObjectsCount()
{
$params = $this->getParams();
if (isset($params['SelectionCriteria']['CampaignIds'])) {
return count($params['SelectionCriteria']['CampaignIds']);
}
if (isset($params['SelectionCriteria']['AdGroupIds'])) {
return count($params['SelectionCriteria']['AdGroupIds']);
}
if (isset($params['SelectionCriteria']['Ids'])) {
return count($params['SelectionCriteria']['Ids']);
}
return -1;
}
public function slice($maxObjects): ?APIRequest
{
$params = $this->getParams();
if (isset($params['SelectionCriteria']['CampaignIds'])) {
return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'CampaignIds']);
}
if (isset($params['SelectionCriteria']['AdGroupIds'])) {
return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'AdGroupIds']);
}
if (isset($params['SelectionCriteria']['Ids'])) {
return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'Ids']);
}
return null;
}
function handle($response)
{
DB::beginTransaction();
try {
$external_ids = [];
if (!isset($response['result']['Keywords'])) {
return;
}
foreach ($response['result']['Keywords'] as $keyword) {
$adGroupId = (string)$keyword['AdGroupId'];
if (isset($external_ids[$adGroupId])) {
continue;
}
$external_ids[$adGroupId] = true;
}
if (!count($external_ids)) {
return;
}
if ($this->getToken()->isMain()) {
$ad_groups = AdGroup::whereIn('external_id', array_keys($external_ids))
->get()
->keyBy('external_id');
} else {
$ad_groups = GoalAdGroup::whereIn('external_id', array_keys($external_ids))
->get()
->keyBy('external_id');
}
foreach ($response['result']['Keywords'] as $keyword) {
$ad_group = $ad_groups->firstWhere('external_id', $keyword['AdGroupId']);
if (!$ad_group)
continue;
$external_id = (string)$keyword['Id'];
if ($this->getToken()->isMain()) {
$data = [
'external_id' => $external_id,
'campaign_external_id' => $ad_group->campaign->external_id,
'ad_group_external_id' => $ad_group->external_id,
'ad_group_id' => $ad_group->getKey(),
'campaign_id' => $ad_group->campaign->getKey(),
'keyword' => $keyword['Keyword'],
'user_param_1' => $keyword['UserParam1'],
'user_param_2' => $keyword['UserParam2'],
'bid' => $keyword['Bid'],
'context_bid' => $keyword['ContextBid'],
'state' => $keyword['State'],
'status' => $keyword['Status'],
'serving_status' => $keyword['ServingStatus'],
];
Keyword::updateOrCreate([
'external_id' => $external_id
], $data);
$ad_group->update([
'keywords_loaded_at' => Carbon::now(),
]);
} else {
$goalKeyword = GoalKeyword::firstWhere('external_id', $external_id);
if (!$goalKeyword)
continue;
$data = [
'external_updated_at' => Carbon::now(),
];
if ($goalKeyword->dictionaryCampaign->updated) {
$data['updated_need'] = Carbon::now();
}
$goalKeyword->update($data);
}
}
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
Log::debug($e);
throw $e;
}
}
private function requestPrepare($filter)
{
$this->setService('Keywords');
$this->setMethod('get');
$params = [
"FieldNames" => [
"Id", "Keyword", "AdGroupId", "CampaignId",
"UserParam1", "UserParam2", "Bid",
"ContextBid", "State", "Status", "ServingStatus",
],
];
if (isset($filter['CampaignIds'])) {
$this->max_count = $this->max_count_CampaignIds;
$params['SelectionCriteria'] = [
'CampaignIds' => $filter['CampaignIds'],
];
}
if (isset($filter['AdGroupIds'])) {
$this->max_count = $this->max_count_AdGroupIds;
$params['SelectionCriteria'] = [
'AdGroupIds' => $filter['AdGroupIds'],
];
}
if (isset($filter['Ids'])) {
$this->max_count = $this->max_count_Ids;
$params['SelectionCriteria'] = [
'Ids' => $filter['Ids'],
];
}
$this->setParams($params);
}
}
...@@ -34,7 +34,7 @@ class ResumeCampaigns extends DirectRequest ...@@ -34,7 +34,7 @@ class ResumeCampaigns extends DirectRequest
{ {
try { try {
foreach ($response['result']['ResumeResults'] as $resume_result) { foreach ($response['result']['ResumeResults'] as $resume_result) {
$external_id = $resume_result['Id'] ?? ''; $external_id = (string)$resume_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("resumeCampaigns, empty Id"); Log::debug("resumeCampaigns, empty Id");
......
...@@ -35,7 +35,7 @@ class SuspendCampaigns extends DirectRequest ...@@ -35,7 +35,7 @@ class SuspendCampaigns extends DirectRequest
{ {
try { try {
foreach ($response['result']['SuspendResults'] as $suspend_result) { foreach ($response['result']['SuspendResults'] as $suspend_result) {
$external_id = $suspend_result['Id'] ?? ''; $external_id = (string)$suspend_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("SuspendCampaigns, empty Id"); Log::debug("SuspendCampaigns, empty Id");
......
...@@ -48,7 +48,7 @@ class UpdateAdGroups extends DirectRequest ...@@ -48,7 +48,7 @@ class UpdateAdGroups extends DirectRequest
} }
foreach ($response['result']['UpdateResults'] as $key => $update_result) { foreach ($response['result']['UpdateResults'] as $key => $update_result) {
$external_id = $update_result['Id'] ?? ''; $external_id =(string) $update_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("AddAdGroup, empty Id"); Log::debug("AddAdGroup, empty Id");
...@@ -70,10 +70,15 @@ class UpdateAdGroups extends DirectRequest ...@@ -70,10 +70,15 @@ class UpdateAdGroups extends DirectRequest
} }
} }
public function putParams($params)
{
$this->goalAdGroups = $params['goalAdGroups'];
}
private function requestPrepare($params) private function requestPrepare($params)
{ {
$this->setService('AdGroups'); $this->setService('AdGroups');
$this->setMethod('add'); $this->setMethod('update');
$this->putParams($params); $this->putParams($params);
......
...@@ -39,7 +39,7 @@ class UpdateCampaigns extends DirectRequest ...@@ -39,7 +39,7 @@ class UpdateCampaigns extends DirectRequest
{ {
try { try {
foreach ($response['result']['UpdateResults'] as $key => $add_result) { foreach ($response['result']['UpdateResults'] as $key => $add_result) {
$external_id = $add_result['Id'] ?? ''; $external_id = (string)$add_result['Id'] ?? '';
if (!$external_id) { if (!$external_id) {
Log::debug("AddCampaigns, empty Id"); Log::debug("AddCampaigns, empty Id");
......
...@@ -58,6 +58,7 @@ class CreateAdGroupsTable extends Migration ...@@ -58,6 +58,7 @@ class CreateAdGroupsTable extends Migration
])->nullable(); ])->nullable();
$table->json('restricted_region_ids')->nullable(); $table->json('restricted_region_ids')->nullable();
$table->timestamp('updated_self')->nullable(); $table->timestamp('updated_self')->nullable();
$table->timestamp('keywords_loaded_at')->nullable();
$table->timestamps(); $table->timestamps();
......
...@@ -16,7 +16,7 @@ class CreateGoalAdGroupsTable extends Migration ...@@ -16,7 +16,7 @@ class CreateGoalAdGroupsTable extends Migration
Schema::create('goal_ad_groups', function (Blueprint $table) { Schema::create('goal_ad_groups', function (Blueprint $table) {
$table->id(); $table->id();
$table->bigInteger('external_id')->nullable(); $table->bigInteger('external_id')->nullable();
$table->bigInteger('campaign_external_id')->nullable(); $table->bigInteger('dictionary_campaign_external_id')->nullable();
$table->bigInteger('ad_group_id')->unsigned(); $table->bigInteger('ad_group_id')->unsigned();
$table->bigInteger('dictionary_campaign_id')->unsigned(); $table->bigInteger('dictionary_campaign_id')->unsigned();
$table->string('name', 255)->nullable(); $table->string('name', 255)->nullable();
...@@ -26,6 +26,7 @@ class CreateGoalAdGroupsTable extends Migration ...@@ -26,6 +26,7 @@ class CreateGoalAdGroupsTable extends Migration
$table->timestamp('updated_need')->nullable(); $table->timestamp('updated_need')->nullable();
$table->timestamp('updated_self')->nullable(); $table->timestamp('updated_self')->nullable();
$table->timestamps(); $table->timestamps();
$table->timestamps();
$table->foreign('dictionary_campaign_id')->references('id')->on('dictionary_campaigns') $table->foreign('dictionary_campaign_id')->references('id')->on('dictionary_campaigns')
...@@ -42,6 +43,6 @@ class CreateGoalAdGroupsTable extends Migration ...@@ -42,6 +43,6 @@ class CreateGoalAdGroupsTable extends Migration
*/ */
public function down() public function down()
{ {
Schema::dropIfExists('dictionary_campaigns'); Schema::dropIfExists('goal_ad_groups');
} }
} }
<?php
use App\Models\Keyword;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateKeywordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('keywords', function (Blueprint $table) {
$table->id();
$table->bigInteger('external_id');
$table->bigInteger('ad_group_external_id');
$table->bigInteger('campaign_external_id');
$table->bigInteger('ad_group_id')->unsigned();
$table->bigInteger('campaign_id')->unsigned();
$table->text('keyword')->nullable();
$table->string('user_param_1', 255)->nullable();
$table->string('user_param_2', 255)->nullable();
$table->bigInteger('bid')->nullable();
$table->bigInteger('context_bid')->nullable();
$table->enum('state', [
Keyword::STATE_OFF,
Keyword::STATE_ON,
Keyword::STATE_SUSPENDED,
])->nullable();
$table->enum('status', [
Keyword::STATUS_ACCEPTED,
Keyword::STATUS_DRAFT,
Keyword::STATUS_REJECTED,
Keyword::STATUS_UNKNOWN,
])->nullable();
$table->enum('serving_status', [
Keyword::SERVING_STATUS_ELIGIBLE,
Keyword::SERVING_STATUS_RARELY_SERVED,
])->nullable();
$table->timestamp('updated_self')->nullable();
$table->timestamps();
$table->foreign('ad_group_id')->references('id')->on('ad_groups')
->cascadeOnDelete();
$table->foreign('campaign_id')->references('id')->on('campaigns')
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('keywords');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGoalKeywordsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('goal_keywords', function (Blueprint $table) {
$table->id();
$table->bigInteger('external_id')->nullable();
$table->bigInteger('dictionary_campaign_external_id')->nullable();
$table->bigInteger('goal_ad_group_external_id')->nullable();
$table->bigInteger('dictionary_campaign_id')->unsigned();
$table->bigInteger('goal_ad_group_id')->unsigned();
$table->bigInteger('keyword_id')->unsigned();
$table->timestamp('external_upload_at')->nullable();
$table->timestamp('external_updated_at')->nullable();
$table->timestamp('updated_need')->nullable();
$table->timestamps();
$table->foreign('dictionary_campaign_id')->references('id')->on('dictionary_campaigns')
->cascadeOnDelete();
$table->foreign('goal_ad_group_id')->references('id')->on('goal_ad_groups')
->cascadeOnDelete();
$table->foreign('keyword_id')->references('id')->on('keywords')
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('goal_keywords');
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!