Commit 2c3b3cef by Vladislav

#19499 Загрузка модификаторов ставок

1 parent 4e1c013a
...@@ -49,12 +49,6 @@ class AdvertisementsAdd extends Command ...@@ -49,12 +49,6 @@ class AdvertisementsAdd extends Command
foreach ($tokens as $token) { foreach ($tokens as $token) {
$token->load([
'dictionaryCampaignsEnabledForExternalSynchronized' => function (HasManyThrough $query) {
return $query->has('goalAdvertisementsForNotExternal.advertisement');
},
]);
$factory = APIRequest::getInstance(API::YANDEX); $factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token); $factory->setToken($token);
......
<?php
namespace App\Console\Commands;
use App\Models\Tokens;
use App\Service\API\API;
use App\Service\Requests\APIRequest;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
class BidModifiersAdd extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'didModifiers:add';
/**
* 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
*/
public function handle()
{
$tokens = Tokens::whereHas('dictionaryCampaignsEnabledForExternalSynchronized.goalBidModifiers.bidModifier')
->where('type', '!=', Tokens::MAIN)
->get();
foreach ($tokens as $token) {
$factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token);
$goalAds = DB::table('goal_bid_modifiers')
->join('bid_modifiers', 'goal_bid_modifiers.bid_modifier_id', '=', 'bid_modifiers.id')
->whereNull('bid_modifiers.deleted_at')
->whereNull('goal_bid_modifiers.external_id')
->where(function (Builder $query) {
$query->whereNull('goal_bid_modifiers.goal_ad_group_id')
->orWhere(function (Builder $query) {
$query->whereNotNull('goal_bid_modifiers.goal_ad_group_id')
->whereNotNull('goal_bid_modifiers.goal_ad_group_external_id');
});
})
->whereNotNull('goal_bid_modifiers.dictionary_campaign_external_id')
->whereIn('goal_bid_modifiers.dictionary_campaign_id', $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('id'))
->select([
'goal_bid_modifiers.id as id',
'goal_bid_modifiers.dictionary_campaign_id as dictionary_campaign_id',
'goal_bid_modifiers.goal_ad_group_external_id as goal_ad_group_external_id',
'bid_modifiers.mobile_adjustment as mobile_adjustment',
'bid_modifiers.desktop_adjustment as desktop_adjustment',
'bid_modifiers.demographics_adjustment as demographics_adjustment',
'bid_modifiers.retargeting_adjustment as retargeting_adjustment',
])
->get();
$factory->getRequest('Ads', 'add')
->call([
'goalAds' => $goalAds,
]);
}
return 0;
}
}
...@@ -54,6 +54,7 @@ class CampaignsFirstLoad extends Command ...@@ -54,6 +54,7 @@ class CampaignsFirstLoad extends Command
Artisan::call(CampaignsLoadGroups::class); Artisan::call(CampaignsLoadGroups::class);
Artisan::call(AdGroupsLoadKeywords::class); Artisan::call(AdGroupsLoadKeywords::class);
Artisan::call(CampaignsLoadAds::class); Artisan::call(CampaignsLoadAds::class);
Artisan::call(CampaignsLoadBidModifiers::class);
return 0; return 0;
} }
......
<?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 CampaignsLoadBidModifiers extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'campaigns:loadBidModifiers';
/**
* 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::forManaged()->forEnabled()->get();
if (!$campaigns->count()) {
return;
}
$token = Tokens::where('type', Tokens::MAIN)->first();
if (!$token) {
throw new \Exception('Не найден токен блин');
}
foreach ($campaigns->pluck('external_id')->chunk(10)->toArray() as $campaign_ids) {
$factory = APIRequest::getInstance(API::YANDEX);
$factory->setToken($token);
$factory->getRequest('BidModifiers', 'get')
->call([
'CampaignIds' => $campaign_ids,
]);
}
return 0;
}
}
...@@ -101,8 +101,8 @@ class DictionaryCampaignsSyncByCampaign extends Command ...@@ -101,8 +101,8 @@ class DictionaryCampaignsSyncByCampaign extends Command
foreach ($cities as $city){ foreach ($cities as $city){
//грузиим РК которых по какой то причне нет в целевых. //грузиим РК которых по какой то причне нет в целевых.
DB::insert(" DB::insert("
INSERT INTO dictionary_campaigns(campaign_id, dictionary_id, name, negative_keywords, excluded_sites) INSERT INTO dictionary_campaigns(campaign_id, dictionary_id, name, negative_keywords, excluded_sites, created_at, updated_at)
SELECT c.id, {$city->id}, c.name, c.negative_keywords, c.excluded_sites SELECT c.id, {$city->id}, c.name, c.negative_keywords, c.excluded_sites, now(), now()
FROM campaigns c FROM campaigns c
LEFT JOIN dictionary_campaigns dc on c.id = dc.campaign_id AND dc.dictionary_id={$city->id} LEFT JOIN dictionary_campaigns dc on c.id = dc.campaign_id AND dc.dictionary_id={$city->id}
WHERE dc.campaign_id is null AND c.manage=1 WHERE dc.campaign_id is null AND c.manage=1
...@@ -111,8 +111,8 @@ class DictionaryCampaignsSyncByCampaign extends Command ...@@ -111,8 +111,8 @@ class DictionaryCampaignsSyncByCampaign extends Command
//грузим группы которых по какой то причне нет в целевых. //грузим группы которых по какой то причне нет в целевых.
DB::insert(" DB::insert("
INSERT INTO goal_ad_groups(ad_group_id, dictionary_campaign_external_id, dictionary_campaign_id, name, negative_keywords) INSERT INTO goal_ad_groups(ad_group_id, dictionary_campaign_external_id, dictionary_campaign_id, name, negative_keywords, created_at, updated_at)
SELECT a.id, dc.external_id, dc.id, a.name, a.negative_keywords SELECT a.id, dc.external_id, dc.id, a.name, a.negative_keywords, now(), now()
FROM ad_groups a FROM ad_groups a
INNER JOIN campaigns c on a.campaign_id = c.id INNER JOIN campaigns c on a.campaign_id = c.id
INNER JOIN dictionary_campaigns dc on c.id = dc.campaign_id INNER JOIN dictionary_campaigns dc on c.id = dc.campaign_id
...@@ -123,8 +123,8 @@ class DictionaryCampaignsSyncByCampaign extends Command ...@@ -123,8 +123,8 @@ class DictionaryCampaignsSyncByCampaign extends Command
//грузим ключевые фразы которых по какой то причне нет в целевых. //грузим ключевые фразы которых по какой то причне нет в целевых.
DB::insert(" DB::insert("
INSERT INTO goal_keywords(dictionary_campaign_external_id, goal_ad_group_external_id, dictionary_campaign_id, INSERT INTO goal_keywords(dictionary_campaign_external_id, goal_ad_group_external_id, dictionary_campaign_id,
goal_ad_group_id, keyword_id) goal_ad_group_id, keyword_id, created_at, updated_at)
SELECT gag.dictionary_campaign_id, gag.external_id, gag.dictionary_campaign_id, gag.id, k.id SELECT gag.dictionary_campaign_id, gag.external_id, gag.dictionary_campaign_id, gag.id, k.id, now(), now()
FROM keywords k FROM keywords k
INNER JOIN ad_groups ag on k.ad_group_id = ag.id INNER JOIN ad_groups ag on k.ad_group_id = ag.id
INNER JOIN goal_ad_groups gag on ag.id = gag.ad_group_id INNER JOIN goal_ad_groups gag on ag.id = gag.ad_group_id
...@@ -132,11 +132,11 @@ class DictionaryCampaignsSyncByCampaign extends Command ...@@ -132,11 +132,11 @@ class DictionaryCampaignsSyncByCampaign extends Command
WHERE gk.keyword_id is null WHERE gk.keyword_id is null
"); ");
//грузим ключевые фразы которых по какой то причне нет в целевых. //грузим объявления которых по какой то причне нет в целевых.
DB::insert(" DB::insert("
INSERT INTO goal_advertisements(dictionary_campaign_external_id, goal_ad_group_external_id, dictionary_campaign_id, INSERT INTO goal_advertisements(dictionary_campaign_external_id, goal_ad_group_external_id, dictionary_campaign_id,
goal_ad_group_id, advertisement_id) goal_ad_group_id, advertisement_id, created_at, updated_at)
SELECT gag.dictionary_campaign_id, gag.external_id, gag.dictionary_campaign_id, gag.id, ad.id SELECT gag.dictionary_campaign_id, gag.external_id, gag.dictionary_campaign_id, gag.id, ad.id, now(), now()
FROM advertisements ad FROM advertisements ad
INNER JOIN ad_groups ag on ad.ad_group_id = ag.id INNER JOIN ad_groups ag on ad.ad_group_id = ag.id
INNER JOIN goal_ad_groups gag on ag.id = gag.ad_group_id INNER JOIN goal_ad_groups gag on ag.id = gag.ad_group_id
...@@ -144,6 +144,18 @@ class DictionaryCampaignsSyncByCampaign extends Command ...@@ -144,6 +144,18 @@ class DictionaryCampaignsSyncByCampaign extends Command
WHERE gad.advertisement_id is null WHERE gad.advertisement_id is null
"); ");
//грузим объявления которых по какой то причне нет в целевых.
DB::insert("
INSERT INTO goal_bid_modifiers(dictionary_campaign_external_id, goal_ad_group_external_id, dictionary_campaign_id,
goal_ad_group_id, bid_modifier_id, created_at, updated_at)
SELECT gag.dictionary_campaign_id, gag.external_id, gag.dictionary_campaign_id, gag.id, ad.id, now(), now()
FROM advertisements ad
INNER JOIN ad_groups ag on ad.ad_group_id = ag.id
INNER JOIN goal_ad_groups gag on ag.id = gag.ad_group_id
LEFT JOIN goal_bid_modifiers gbm on ad.id = gbm.bid_modifier_id AND gbm.goal_ad_group_id=gag.id
WHERE gbm.bid_modifier_id is null
");
DictionaryCampaign::needSynced()->update([ DictionaryCampaign::needSynced()->update([
'synced_need' => null, 'synced_need' => null,
]); ]);
......
...@@ -24,7 +24,6 @@ use App\Console\Commands\KeywordsDelete; ...@@ -24,7 +24,6 @@ use App\Console\Commands\KeywordsDelete;
use App\Console\Commands\KeywordsUpdate; use App\Console\Commands\KeywordsUpdate;
use App\Console\Commands\RefreshLimits; use App\Console\Commands\RefreshLimits;
use Illuminate\Console\Scheduling\Schedule; use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel; use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel class Kernel extends ConsoleKernel
...@@ -71,8 +70,8 @@ class Kernel extends ConsoleKernel ...@@ -71,8 +70,8 @@ class Kernel extends ConsoleKernel
$schedule->command(KeywordsDelete::class)->hourlyAt(40); $schedule->command(KeywordsDelete::class)->hourlyAt(40);
$schedule->command(AdvertisementsLoadUpdated::class)->hourlyAt(40); $schedule->command(AdvertisementsLoadUpdated::class)->hourlyAt(40);
$schedule->command(AdvertisementsAdd::class)->hourlyAt(50); // $schedule->command(AdvertisementsAdd::class)->hourlyAt(50);
$schedule->command(AdvertisementsUpdate::class)->hourlyAt(50); // $schedule->command(AdvertisementsUpdate::class)->hourlyAt(50);
$schedule->call(function () { $schedule->call(function () {
$items = new \FilesystemIterator(config('clockwork.storage_files_path')); $items = new \FilesystemIterator(config('clockwork.storage_files_path'));
......
<?php
namespace App\Models;
use App\Models\Pivots\GoalBidModifier;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Collection;
class BidModifier extends Model
{
use SoftDeletes;
const LEVEL_CAMPAIGN = 'CAMPAIGN';
const LEVEL_AD_GROUP = 'AD_GROUP';
const TYPE_MOBILE_ADJUSTMENT = 'MOBILE_ADJUSTMENT';
const TYPE_DESKTOP_ADJUSTMENT = 'DESKTOP_ADJUSTMENT';
const TYPE_DEMOGRAPHICS_ADJUSTMENT = 'DEMOGRAPHICS_ADJUSTMENT';
const TYPE_RETARGETING_ADJUSTMENT = 'RETARGETING_ADJUSTMENT';
const TYPE_REGIONAL_ADJUSTMENT = 'REGIONAL_ADJUSTMENT';
const TYPE_VIDEO_ADJUSTMENT = 'VIDEO_ADJUSTMENT';
const TYPE_SMART_AD_ADJUSTMENT = 'SMART_AD_ADJUSTMENT';
protected $fillable = [
'external_id',
'campaign_external_id',
'ad_group_external_id',
'campaign_id',
'ad_group_id',
'level',
'type',
'mobile_adjustment',
'desktop_adjustment',
'demographics_adjustment',
'retargeting_adjustment',
'updated_self',
];
protected $casts = [
'mobile_adjustment' => 'json',
'desktop_adjustment' => 'json',
'demographics_adjustment' => 'json',
'retargeting_adjustment' => 'json',
'updated_self' => 'datetime',
];
/**
* @param Builder $query
* @return Builder
*/
public function scopeForUpdatedSelf($query)
{
return $query->whereNotNull("{$query->getModel()->getTable()}.updated_self");
}
public function groups()
{
return $this->hasMany(AdGroup::class, 'ad_group_id');
}
public function campaign()
{
return $this->belongsTo(Campaigns::class, 'campaign_id');
}
public function campaignForEnabledForManaged()
{
return $this->campaign()->forEnabled()->forManaged();
}
public function goalBidModifiers()
{
return $this->hasMany(GoalBidModifier::class, 'bid_modifier_id');
}
}
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
namespace App\Models\Pivots; namespace App\Models\Pivots;
use App\Models\BidModifier;
use App\Models\Campaigns; use App\Models\Campaigns;
use App\Models\Dictionary; use App\Models\Dictionary;
use App\Models\Variable; use App\Models\Variable;
...@@ -448,4 +449,14 @@ class DictionaryCampaign extends Pivot ...@@ -448,4 +449,14 @@ class DictionaryCampaign extends Pivot
return $this->goalAdvertisements()->needUpdated(); return $this->goalAdvertisements()->needUpdated();
} }
public function goalBidModifiers()
{
return $this->hasMany(BidModifier::class, 'dictionary_campaign_id');
}
public function goalBidModifiersForNotExternal()
{
return $this->goalAdvertisements()->forNotExternal();
}
} }
<?php
namespace App\Models\Pivots;
use App\Models\BidModifier;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* App\Models\Pivots\BidModifiers
*
* @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 $bid_modifier_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 BidModifier $bidModifier
* @method static Builder|BidModifiers forExternal()
* @method static Builder|BidModifiers forNotExternal()
* @method static Builder|BidModifiers needUpdated()
* @method static Builder|BidModifiers newModelQuery()
* @method static Builder|BidModifiers newQuery()
* @method static Builder|BidModifiers query()
* @method static Builder|BidModifiers whereCreatedAt($value)
* @method static Builder|BidModifiers whereDictionaryCampaignExternalId($value)
* @method static Builder|BidModifiers whereDictionaryCampaignId($value)
* @method static Builder|BidModifiers whereExternalId($value)
* @method static Builder|BidModifiers whereExternalUpdatedAt($value)
* @method static Builder|BidModifiers whereExternalUploadAt($value)
* @method static Builder|BidModifiers whereGoalAdGroupExternalId($value)
* @method static Builder|BidModifiers whereGoalAdGroupId($value)
* @method static Builder|BidModifiers whereId($value)
* @method static Builder|BidModifiers whereBidModifierId($value)
* @method static Builder|BidModifiers whereUpdatedAt($value)
* @method static Builder|BidModifiers whereUpdatedNeed($value)
* @mixin \Eloquent
*/
class GoalBidModifier extends Pivot
{
use SoftDeletes;
const LEVEL_CAMPAIGN = 'CAMPAIGN';
const LEVEL_AD_GROUP = 'AD_GROUP';
const TYPE_MOBILE_ADJUSTMENT = 'MOBILE_ADJUSTMENT';
const TYPE_DESKTOP_ADJUSTMENT = 'DESKTOP_ADJUSTMENT';
const TYPE_DEMOGRAPHICS_ADJUSTMENT = 'DEMOGRAPHICS_ADJUSTMENT';
const TYPE_RETARGETING_ADJUSTMENT = 'RETARGETING_ADJUSTMENT';
const TYPE_REGIONAL_ADJUSTMENT = 'REGIONAL_ADJUSTMENT';
const TYPE_VIDEO_ADJUSTMENT = 'VIDEO_ADJUSTMENT';
const TYPE_SMART_AD_ADJUSTMENT = 'SMART_AD_ADJUSTMENT';
protected $table = 'goal_bid_modifiers';
protected $fillable = [
'external_id',
'goal_ad_group_external_id',
'dictionary_campaign_external_id',
'goal_ad_group_id',
'dictionary_campaign_id',
'bid_modifier_id',
'level',
'type',
'mobile_adjustment',
'desktop_adjustment',
'demographics_adjustment',
'retargeting_adjustment',
'external_upload_at',
'external_updated_at',
'updated_need',
];
protected $casts = [
'mobile_adjustment' => 'json',
'desktop_adjustment' => 'json',
'demographics_adjustment' => 'json',
'retargeting_adjustment' => 'json',
'external_upload_at' => 'datetime',
'external_updated_at' => 'datetime',
'updated_need' => 'datetime',
];
public $incrementing = true;
static public function getWithPivot()
{
return [
'id',
'external_id',
'goal_ad_group_external_id',
'dictionary_campaign_external_id',
'goal_ad_group_id',
'dictionary_campaign_id',
'bid_modifier_id',
'level',
'type',
'mobile_adjustment',
'desktop_adjustment',
'demographics_adjustment',
'retargeting_adjustment',
'external_upload_at',
'external_updated_at',
'updated_need',
];
}
/**
* @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 bidModifier()
{
return $this->belongsTo(BidModifier::class, 'bid_modifier_id');
}
public function dictionaryCampaign()
{
return $this->belongsTo(DictionaryCampaign::class, 'dictionary_campaign_id');
}
}
...@@ -53,8 +53,8 @@ class AddAds extends DirectRequest ...@@ -53,8 +53,8 @@ class AddAds extends DirectRequest
try { try {
\Log::debug($response); \Log::debug($response);
if (isset($response['result']['Errors'])) { if (isset($response['result']['Errors'])) {
// Log::debug($response['Errors']); Log::debug($response['Errors']);
// Log::debug($this->getParams()); Log::debug($this->getParams());
} }
if (!isset($response['result']['AddResults'])) { if (!isset($response['result']['AddResults'])) {
......
<?php
namespace App\Service\Requests\Direct;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\BidModifier;
use App\Models\Pivots\GoalBidModifier;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;
class AddBidModifiers extends DirectRequest
{
protected $max_count = 1000;
protected $timestamp;
/* @var Collection|GoalBidModifier[]|BidModifier[]|\stdClass[] */
protected $goalBidModifiers;
public function call($params = null)
{
$this->requestPrepare($params);
$process = new ProcessCallLimitedAPI($this);
dispatch($process)->onQueue('limits');
}
public function getObjectsCount()
{
return count($this->getParams()['BidModifiers']);
}
public function slice($maxObjects): ?APIRequest
{
$splinter = $this->sliceByKey($maxObjects, 'BidModifiers');
$splinter->putParams([
'goalBidModifiers' => $this->goalBidModifiers->slice($maxObjects)->values(),
]);
$this->putParams([
'goalBidModifiers' => $this->goalBidModifiers->slice(0, $maxObjects),
]);
return $splinter;
}
public function handle($response)
{
try {
\Log::debug($response);
if (isset($response['result']['Errors'])) {
Log::debug($response['Errors']);
Log::debug($this->getParams());
}
if (!isset($response['result']['AddResults'])) {
return;
}
foreach ($response['result']['AddResults'] as $key => $add_result) {
if (!isset($add_result['Id'])) {
Log::debug("AddBidModifiers, empty Id");
Log::debug($add_result);
Log::debug($this->getParams());
continue;
}
$external_id = (string)$add_result['Id'];
/* @var $goalAd GoalBidModifier|BidModifier|\stdClass */
$goalAd = $this->goalBidModifiers->get($key);
GoalBidModifier::whereId($goalAd->id)
->update([
'external_id' => $external_id,
'external_upload_at' => Carbon::now(),
]);
}
} catch (\Exception $e) {
Log::debug($e);
throw $e;
}
}
public function putParams($params)
{
$this->goalBidModifiers = $params['goalBidModifiers'];
}
private function requestPrepare($params)
{
$this->setService('BidModifiers');
$this->setMethod('add');
$this->putParams($params);
$this->setParams([
'BidModifiers' => $this->goalBidModifiers->map(function ($goalBidModifier) {
/* @var $goalBidModifier GoalBidModifier|BidModifier|\stdClass */
$data = [
'CampaignId' => $goalBidModifier->dictionary_campaign_external_id,
];
if ($goalBidModifier->goal_ad_group_external_id) {
$data['AdGroupId'] = $goalBidModifier->goal_ad_group_external_id;
}
if ($mobile_adjustment = @json_decode($goalBidModifier->mobile_adjustment)) {
$data['MobileAdjustment'] = $mobile_adjustment;
}
if ($desktop_adjustment = @json_decode($goalBidModifier->desktop_adjustment)) {
$data['DesktopAdjustment'] = $desktop_adjustment;
}
if ($demographics_adjustment = @json_decode($goalBidModifier->demographics_adjustment)) {
$data['DemographicsAdjustments'] = $demographics_adjustment;
}
if ($retargeting_adjustment = @json_decode($goalBidModifier->retargeting_adjustment)) {
$data['RetargetingAdjustments'] = $retargeting_adjustment;
}
return $data;
})->toArray(),
]);
}
}
...@@ -117,7 +117,7 @@ class AddCampaigns extends DirectRequest ...@@ -117,7 +117,7 @@ class AddCampaigns extends DirectRequest
$list = Variable::getListVariablesByDictionaryCampaign($dictionaryCampaign->getKey(), $variables); $list = Variable::getListVariablesByDictionaryCampaign($dictionaryCampaign->getKey(), $variables);
$data = [ $data = [
'Name' => StrReplaceByVariables::getInstance($dictionaryCampaign->name, $list)->get(), 'Name' => StrReplaceByVariables::getInstance($dictionaryCampaign->campaign->name, $list)->get(),
'StartDate' => Carbon::now()->format('Y-m-d'), 'StartDate' => Carbon::now()->format('Y-m-d'),
'TextCampaign' => [ 'TextCampaign' => [
'BiddingStrategy' => $dictionaryCampaign->campaign->bidding_strategy, 'BiddingStrategy' => $dictionaryCampaign->campaign->bidding_strategy,
...@@ -132,11 +132,11 @@ class AddCampaigns extends DirectRequest ...@@ -132,11 +132,11 @@ class AddCampaigns extends DirectRequest
$data['DailyBudget'] = $dictionaryCampaign->campaign->daily_budget; $data['DailyBudget'] = $dictionaryCampaign->campaign->daily_budget;
} }
if ($dictionaryCampaign->negative_keywords && count($dictionaryCampaign->negative_keywords)) { if ($dictionaryCampaign->campaign->negative_keywords && count($dictionaryCampaign->campaign->negative_keywords)) {
$data['NegativeKeywords'] = [ $data['NegativeKeywords'] = [
'Items' => array_map(function ($value) use ($list) { 'Items' => array_map(function ($value) use ($list) {
return StrReplaceByVariables::getInstance($value, $list)->get(); return StrReplaceByVariables::getInstance($value, $list)->get();
}, $dictionaryCampaign->negative_keywords), }, $dictionaryCampaign->campaign->negative_keywords),
]; ];
} }
...@@ -146,11 +146,11 @@ class AddCampaigns extends DirectRequest ...@@ -146,11 +146,11 @@ class AddCampaigns extends DirectRequest
]; ];
} }
if ($dictionaryCampaign->excluded_sites && count($dictionaryCampaign->excluded_sites)) { if ($dictionaryCampaign->campaign->excluded_sites && count($dictionaryCampaign->campaign->excluded_sites)) {
$data['ExcludedSites'] = [ $data['ExcludedSites'] = [
'Items' => array_map(function ($value) use ($list) { 'Items' => array_map(function ($value) use ($list) {
return StrReplaceByVariables::getInstance($value, $list)->get(); return StrReplaceByVariables::getInstance($value, $list)->get();
}, $dictionaryCampaign->excluded_sites), }, $dictionaryCampaign->campaign->excluded_sites),
]; ];
} }
......
...@@ -77,7 +77,7 @@ class GetAds extends DirectRequest ...@@ -77,7 +77,7 @@ class GetAds extends DirectRequest
->get() ->get()
->keyBy('external_id'); ->keyBy('external_id');
} else { } else {
// //
} }
foreach ($response['result']['Ads'] as $ad) { foreach ($response['result']['Ads'] as $ad) {
...@@ -111,7 +111,7 @@ class GetAds extends DirectRequest ...@@ -111,7 +111,7 @@ class GetAds extends DirectRequest
]; ];
if (isset($ad['TextAd'])) { if (isset($ad['TextAd'])) {
$data = array_merge($data,[ $data = array_merge($data, [
'title' => $ad['TextAd']['Title'], 'title' => $ad['TextAd']['Title'],
'title2' => $ad['TextAd']['Title2'], 'title2' => $ad['TextAd']['Title2'],
'text' => $ad['TextAd']['Text'], 'text' => $ad['TextAd']['Text'],
...@@ -193,22 +193,16 @@ class GetAds extends DirectRequest ...@@ -193,22 +193,16 @@ class GetAds extends DirectRequest
], ],
]; ];
if (isset($filter['CampaignIds'])) { if (isset($filter['CampaignIds'])) {
$params['SelectionCriteria'] = [ $params['SelectionCriteria']['CampaignIds'] = $filter['CampaignIds'];
'CampaignIds' => $filter['CampaignIds'],
];
} }
if (isset($filter['AdGroupIds'])) { if (isset($filter['AdGroupIds'])) {
$params['SelectionCriteria'] = [ $params['SelectionCriteria']['AdGroupIds'] = $filter['AdGroupIds'];
'AdGroupIds' => $filter['AdGroupIds'],
];
} }
if (isset($filter['Ids'])) { if (isset($filter['Ids'])) {
$this->max_count = $this->max_count_Ids; $this->max_count = $this->max_count_Ids;
$params['SelectionCriteria'] = [ $params['SelectionCriteria']['Ids'] = $filter['Ids'];
'Ids' => $filter['Ids'],
];
} }
$this->setParams($params); $this->setParams($params);
} }
......
<?php
namespace App\Service\Requests\Direct;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\AdGroup;
use App\Models\Advertisement;
use App\Models\BidModifier;
use App\Models\Campaigns;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
class GetBidModifiers 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 -1;
}
if (isset($params['SelectionCriteria']['AdGroupIds'])) {
return -1;
}
if (isset($params['SelectionCriteria']['Ids'])) {
return count($params['SelectionCriteria']['Ids']);
}
return -1;
}
public function slice($maxObjects): ?APIRequest
{
$params = $this->getParams();
if (isset($params['SelectionCriteria']['Ids'])) {
return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'Ids']);
}
return null;
}
function handle($response)
{
try {
if (!isset($response['result']['BidModifiers'])) {
return;
}
$campaigns_external_ids = [];
$ad_groups_external_ids = [];
foreach ($response['result']['BidModifiers'] as $ad) {
$campaignId = (string)$ad['CampaignId'];
$adGroupId = (string)$ad['AdGroupId'];
if (!isset($campaigns_external_ids[$campaignId])) {
$campaigns_external_ids[$campaignId] = true;
}
if (!isset($ad_groups_external_ids[$adGroupId])) {
$ad_groups_external_ids[$adGroupId] = true;
}
}
if (!count($campaigns_external_ids)) {
return;
}
if ($this->getToken()->isMain()) {
$campaigns = Campaigns::whereIn('external_id', array_keys($campaigns_external_ids))
->get()
->keyBy('external_id');
$adGroups = AdGroup::whereIn('external_id', array_keys($campaigns_external_ids))
->get()
->keyBy('external_id');
} else {
//
}
foreach ($response['result']['BidModifiers'] as $bid_modifier) {
/* @var $campaign Campaigns|null */
$campaign = $campaigns->get((string)$bid_modifier['CampaignId']);
if (!$campaign)
continue;
/* @var $adGroup AdGroup|null */
$adGroup = $adGroups->get((string)$bid_modifier['AdGroupId']);
$external_id = (string)$bid_modifier['Id'];
if ($this->getToken()->isMain()) {
$data = [
'external_id' => $external_id,
'campaign_external_id' => $campaign->external_id,
'ad_group_external_id' => $adGroup ? $adGroup->external_id : null,
'campaign_id' => $campaign->getKey(),
'ad_group_id' => $adGroup ? $adGroup->getKey() : null,
'level' => $bid_modifier['Status'],
'type' => $bid_modifier['State'],
'mobile_adjustment' => $bid_modifier['MobileAdjustment'],
'desktop_adjustment' => $bid_modifier['DesktopAdjustment'],
'demographics_adjustment' => $bid_modifier['DemographicsAdjustment'],
'retargeting_adjustment' => $bid_modifier['RetargetingAdjustment'],
'updated_self' => null,
];
$bid_modifier = BidModifier::updateOrCreate([
'external_id' => $external_id
], $data);
if ($bid_modifier->wasRecentlyCreated) {
$campaign_ids_synced_need[$bid_modifier->campaign_id] = true;
} elseif ($bid_modifier->wasChanged(['campaign_id'])) {
$campaign_ids_synced_need[$bid_modifier->campaign_id] = true;
} elseif ($bid_modifier->wasChanged($bid_modifier::getPropertiesWatch()->toArray())) {
$bid_modifier->goalBidModifiers()->has('dictionaryCampaign')->forExternal()->update([
'updated_need' => Carbon::now(),
]);
}
} else {
//
}
}
} catch (\Exception $e) {
Log::debug($e);
throw $e;
}
}
private function requestPrepare($filter)
{
$this->setService('BidModifiers');
$this->setMethod('get');
$params = [
"SelectionCriteria" => [
"Types" => [
BidModifier::TYPE_MOBILE_ADJUSTMENT,
BidModifier::TYPE_DESKTOP_ADJUSTMENT,
BidModifier::TYPE_DEMOGRAPHICS_ADJUSTMENT,
BidModifier::TYPE_RETARGETING_ADJUSTMENT,
],
],
"FieldNames" => [
"Id", "CampaignId", "AdGroupId", "Level", "Type",
],
"MobileAdjustmentFieldNames" => [
"BidModifier", "OperatingSystemType",
],
"DesktopAdjustmentFieldNames" => [
"BidModifier",
],
"DemographicsAdjustmentFieldNames" => [
"Gender", "Age", "BidModifier", "Enabled",
],
"RetargetingAdjustmentFieldNames" => [
"RetargetingConditionId", "BidModifier", "Accessible", "Enabled",
],
];
if (isset($filter['CampaignIds'])) {
$params['SelectionCriteria']['CampaignIds'] = $filter['CampaignIds'];
}
if (isset($filter['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);
}
}
...@@ -94,8 +94,8 @@ class UpdateAdGroups extends DirectRequest ...@@ -94,8 +94,8 @@ class UpdateAdGroups extends DirectRequest
$list = Variable::getListVariablesByDictionaryCampaign($goalAdGroup->dictionary_campaign_id, $variables); $list = Variable::getListVariablesByDictionaryCampaign($goalAdGroup->dictionary_campaign_id, $variables);
$data = [ $data = [
'Id' => $goalAdGroup->external_id, 'Id' => $goalAdGroup->group->external_id,
'Name' => StrReplaceByVariables::getInstance($goalAdGroup->name, $list)->get(), 'Name' => StrReplaceByVariables::getInstance($goalAdGroup->group->name, $list)->get(),
'RegionIds' => $goalAdGroup->group->region_ids, 'RegionIds' => $goalAdGroup->group->region_ids,
]; ];
...@@ -115,11 +115,11 @@ class UpdateAdGroups extends DirectRequest ...@@ -115,11 +115,11 @@ class UpdateAdGroups extends DirectRequest
$data['SmartAdGroup'] = $goalAdGroup->group->smart_ad_group; $data['SmartAdGroup'] = $goalAdGroup->group->smart_ad_group;
} }
if ($goalAdGroup->negative_keywords && count($goalAdGroup->negative_keywords)) { if ($goalAdGroup->group->negative_keywords && count($goalAdGroup->group->negative_keywords)) {
$data['NegativeKeywords'] = [ $data['NegativeKeywords'] = [
'Items' => array_map(function ($value) use ($list) { 'Items' => array_map(function ($value) use ($list) {
return StrReplaceByVariables::getInstance($value, $list)->get(); return StrReplaceByVariables::getInstance($value, $list)->get();
}, $goalAdGroup->negative_keywords), }, $goalAdGroup->group->negative_keywords),
]; ];
} }
......
...@@ -84,7 +84,7 @@ class UpdateCampaigns extends DirectRequest ...@@ -84,7 +84,7 @@ class UpdateCampaigns extends DirectRequest
$data = [ $data = [
'Id' => $dictionaryCampaign->external_id, 'Id' => $dictionaryCampaign->external_id,
'Name' => StrReplaceByVariables::getInstance($dictionaryCampaign->name, $list)->get(), 'Name' => StrReplaceByVariables::getInstance($dictionaryCampaign->campaign->name, $list)->get(),
'TextCampaign' => [ 'TextCampaign' => [
'BiddingStrategy' => $dictionaryCampaign->campaign->bidding_strategy, 'BiddingStrategy' => $dictionaryCampaign->campaign->bidding_strategy,
], ],
...@@ -98,11 +98,11 @@ class UpdateCampaigns extends DirectRequest ...@@ -98,11 +98,11 @@ class UpdateCampaigns extends DirectRequest
$data['DailyBudget'] = $dictionaryCampaign->campaign->daily_budget; $data['DailyBudget'] = $dictionaryCampaign->campaign->daily_budget;
} }
if ($dictionaryCampaign->negative_keywords && count($dictionaryCampaign->negative_keywords)) { if ($dictionaryCampaign->campaign->negative_keywords && count($dictionaryCampaign->campaign->negative_keywords)) {
$data['NegativeKeywords'] = [ $data['NegativeKeywords'] = [
'Items' => array_map(function ($value) use ($list) { 'Items' => array_map(function ($value) use ($list) {
return StrReplaceByVariables::getInstance($value, $list)->get(); return StrReplaceByVariables::getInstance($value, $list)->get();
}, $dictionaryCampaign->negative_keywords), }, $dictionaryCampaign->campaign->negative_keywords),
]; ];
} }
...@@ -112,11 +112,11 @@ class UpdateCampaigns extends DirectRequest ...@@ -112,11 +112,11 @@ class UpdateCampaigns extends DirectRequest
]; ];
} }
if ($dictionaryCampaign->excluded_sites && count($dictionaryCampaign->excluded_sites)) { if ($dictionaryCampaign->campaign->excluded_sites && count($dictionaryCampaign->campaign->excluded_sites)) {
$data['ExcludedSites'] = [ $data['ExcludedSites'] = [
'Items' => array_map(function ($value) use ($list) { 'Items' => array_map(function ($value) use ($list) {
return StrReplaceByVariables::getInstance($value, $list)->get(); return StrReplaceByVariables::getInstance($value, $list)->get();
}, $dictionaryCampaign->excluded_sites), }, $dictionaryCampaign->campaign->excluded_sites),
]; ];
} }
......
<?php
use App\Models\BidModifier;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBidModifiersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bid_modifiers', function (Blueprint $table) {
$table->id();
$table->bigInteger('external_id')->nullable();
$table->bigInteger('campaign_external_id')->nullable();
$table->bigInteger('ad_group_external_id')->nullable();
$table->bigInteger('campaign_id')->unsigned();
$table->bigInteger('ad_group_id')->unsigned()->nullable();
$table->enum('level', [
BidModifier::LEVEL_CAMPAIGN,
BidModifier::LEVEL_AD_GROUP,
])->nullable();
$table->enum('type', [
BidModifier::TYPE_MOBILE_ADJUSTMENT,
BidModifier::TYPE_DESKTOP_ADJUSTMENT,
BidModifier::TYPE_DEMOGRAPHICS_ADJUSTMENT,
BidModifier::TYPE_RETARGETING_ADJUSTMENT,
BidModifier::TYPE_REGIONAL_ADJUSTMENT,
BidModifier::TYPE_VIDEO_ADJUSTMENT,
BidModifier::TYPE_SMART_AD_ADJUSTMENT,
])->nullable();
$table->json('mobile_adjustment')->nullable();
$table->json('desktop_adjustment')->nullable();
$table->json('demographics_adjustment')->nullable();
$table->json('retargeting_adjustment')->nullable();
$table->timestamp('updated_self')->nullable();
$table->softDeletes();
$table->timestamps();
$table->foreign('campaign_id')->references('id')->on('campaigns')
->cascadeOnDelete();
$table->foreign('ad_group_id')->references('id')->on('ad_groups')
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bid_modifiers');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGoalBidModifiersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('goal_bid_modifiers', 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()->nullable();
$table->bigInteger('bid_modifier_id')->unsigned();
$table->timestamp('external_upload_at')->nullable();
$table->timestamp('external_updated_at')->nullable();
$table->timestamp('updated_need')->nullable();
$table->softDeletes();
$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('bid_modifier_id')->references('id')->on('bid_modifiers')
->cascadeOnDelete();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('goal_bid_modifiers');
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!