Commit a9b8de18 by Vladislav

#20794 Сделать чтобы в целевых РК оставалась одна карточка

1 parent 3ee91de8
<?php
namespace App\Console\Commands;
use App\Models\Tokens;
use App\Service\Requests\Direct\DeleteAdGroups;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AdGroupsDelete extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'adgroups:delete';
/**
* 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()
{
foreach (Tokens::where('type', '!=', Tokens::MAIN)->get() as $token) {
$result = DB::select("SELECT gag.external_id
FROM goal_ad_groups gag
INNER JOIN ad_groups ag ON gag.ad_group_id = ag.id
INNER JOIN dictionary_campaigns c ON c.id = gag.dictionary_campaign_id
INNER JOIN dictionaries d ON d.id = c.dictionary_id
WHERE gag.external_id is not null
AND ag.deleted_at is not null
AND d.token_id=" . $token->id);
$ids = [];
foreach ($result as $item) {
$ids[] = $item->external_id;
}
if (!count($ids)) {
continue;
}
$request = new DeleteAdGroups();
$request->setToken($token)
->call([
'ids' => $ids
]);
}
return 0;
}
}
......@@ -41,7 +41,7 @@ class CampaignsLoadGroups extends Command
*/
public function handle()
{
$campaigns = Campaigns::forManaged()->forEnabled()->forGroupsLoadable()->get();
$campaigns = Campaigns::forManaged()->forEnabled()->get();
if (!$campaigns->count()) {
return 0;
......
......@@ -5,6 +5,7 @@ namespace App\Console;
use App\Console\Commands\AdExtensionsAdd;
use App\Console\Commands\AdExtensionsLoad;
use App\Console\Commands\AdGroupsAdd;
use App\Console\Commands\AdGroupsDelete;
use App\Console\Commands\AdGroupsLoadUpdated;
use App\Console\Commands\AdGroupsUpdate;
use App\Console\Commands\AdImagesAdd;
......@@ -110,6 +111,7 @@ class Kernel extends ConsoleKernel
$schedule->command(RetargetinglistsUpdate::class)->hourlyAt(35);
$schedule->command(AdGroupsAdd::class)->hourlyAt(35);
$schedule->command(AdGroupsUpdate::class)->hourlyAt(35);
$schedule->command(AdGroupsDelete::class)->hourlyAt(35);
$schedule->command(BidModifiersDelete::class)->hourlyAt(30);
......
......@@ -127,6 +127,8 @@ class AdGroup extends Model
'updated_self',
'keywords_loaded_at',
'bid_modifiers_loaded_at',
'updated_at',
'deleted_at',
];
protected $casts = [
......
......@@ -66,6 +66,9 @@ class AddCampaigns extends DirectRequest
Log::debug($add_result);
Log::debug($this->getParams()['Campaigns'][$key]);
DictionaryCampaign::whereExternalId($dictionaryCampaign->external_id)->update([
'reserve_create_at' => null,
]);
$dictionaryCampaign->update([
'reserve_create_at' => null,
]);
......@@ -75,8 +78,7 @@ class AddCampaigns extends DirectRequest
$external_id = (string)$add_result['Id'];
$dictionaryCampaign->update([
'external_id' => $external_id,
DictionaryCampaign::whereExternalId($external_id)->update([
'external_upload_at' => Carbon::now(),
'reserve_create_at' => null,
]);
......
<?php
namespace App\Service\Requests\Direct;
use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Pivots\GoalAdGroup;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Illuminate\Support\Facades\Log;
class DeleteAdGroups extends DirectRequest
{
protected $max_count = 10000;
protected $timestamp;
public function call($params = null)
{
$this->requestPrepare($params);
$process = new ProcessCallLimitedAPI($this);
dispatch($process)->onQueue('limits');
}
public function getObjectsCount()
{
return count($this->getParams()['SelectionCriteria']['Ids']);
}
public function slice($maxObjects): ?APIRequest
{
return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'Ids']);
}
public function handle($response)
{
try {
if (!isset($response['result']['DeleteResults'])) {
return;
}
foreach ($response['result']['DeleteResults'] as $key => $delete_result) {
if (!isset($delete_result['Id'])) {
Log::debug("DeleteAdGroups, empty Id");
Log::debug($delete_result);
Log::debug($this->getParams()['SelectionCriteria']['Ids'][$key]);
if ($delete_result['Errors'][0]['Code'] == 8800){
if ($external_id = $this->getParams()['SelectionCriteria']['Ids'][$key]){
GoalAdGroup::where('external_id', $external_id)->delete();
}
}
continue;
}
$external_id = (string)$delete_result['Id'];
GoalAdGroup::where('external_id', $external_id)->delete();
}
} catch (\Exception $e) {
Log::debug($e);
throw $e;
}
}
private function requestPrepare($params)
{
$this->setService('AdGroups');
$this->setMethod('delete');
$params = [
'SelectionCriteria' => [
'Ids' => $params['ids'],
],
];
$this->setParams($params);
}
}
......@@ -80,6 +80,7 @@ class GetAdGroups extends DirectRequest
}
$campaign_ids_synced_need = [];
$now = Carbon::now();
foreach ($response['result']['AdGroups'] as $ad_group) {
......@@ -117,6 +118,8 @@ class GetAdGroups extends DirectRequest
'serving_status' => $ad_group['ServingStatus'],
'restricted_region_ids' => $ad_group['RestrictedRegionIds'],
'updated_self' => null,
'updated_at' => $now,
'deleted_at' => null,
];
$negative_keyword_shared_set_external_ids_array = [];
......@@ -138,15 +141,15 @@ class GetAdGroups extends DirectRequest
$data['negative_keyword_shared_set_external_ids'] = $negative_keyword_shared_set_external_ids_array;
$ad_group = AdGroup::updateOrCreate([
'external_id' => $external_id,
], $data);
$negativeKeywordSharedSets_sync = $ad_group->negativeKeywordSharedSets()->sync($negative_keyword_shared_sets->pluck('id'));
$ad_group = AdGroup::where('external_id', $external_id)->withTrashed()->first();
if ($ad_group->wasRecentlyCreated) {
if ($ad_group) {
$ad_group->update($data);
$campaign_ids_synced_need[$ad_group->campaign_id] = true;
} elseif ($ad_group->wasChanged(['campaign_id'])) {
} else {
$ad_group = AdGroup::create($data);
if ($ad_group->wasChanged(['campaign_id'])) {
$campaign_ids_synced_need[$ad_group->campaign_id] = true;
} elseif (
$ad_group->wasChanged($ad_group::getPropertiesWatch()->toArray())
......@@ -162,22 +165,32 @@ class GetAdGroups extends DirectRequest
]);
}
} /*else {
$goalAdGroup = GoalAdGroup::firstWhere('external_id', $external_id);
}
if (!$goalAdGroup)
continue;
$negativeKeywordSharedSets_sync = $ad_group->negativeKeywordSharedSets()->sync($negative_keyword_shared_sets->pluck('id'));
$data = [
'external_updated_at' => Carbon::now(),
];
if (
!empty($this->getParams()['SelectionCriteria']['CampaignIds'])
&&
!isset($response['result']['LimitedBy'])
) {
$campaign_ids = $this->getParams()['SelectionCriteria']['CampaignIds'];
DB::update("UPDATE ad_groups ag
INNER JOIN campaigns ca ON ag.campaign_id = ca.id
SET ag.deleted_at = CURRENT_TIMESTAMP
WHERE ca.groups_loaded_at IS NOT NULL
AND ag.updated_at <= ca.groups_loaded_at
AND ag.deleted_at is null
AND ca.external_id in (" . implode(", ", $campaign_ids) . ")");
if ($campaign->updated) {
$data['updated_need'] = Carbon::now();
Campaigns::whereIn('external_id', $campaign_ids)
->update([
'groups_loaded_at' => Carbon::now(),
]);
}
$goalAdGroup->update($data);
}*/
}
}
......
......@@ -125,7 +125,7 @@ class GetKeywords extends DirectRequest
'deleted_at' => null //не забыть убрать признак удаления, если вдруг опять пришла удаленная ранее фраза
];
$keyword_data = Keyword::where('external_id', $external_id)->withTrashed()->get()->first();
$keyword_data = Keyword::where('external_id', $external_id)->withTrashed()->first();
if ($keyword_data){
if (!$keyword_data->equals($data)){
Log::debug($keyword_data);
......@@ -178,7 +178,8 @@ class GetKeywords extends DirectRequest
$sql = "UPDATE keywords k
INNER JOIN ad_groups ag ON k.ad_group_id=ag.id
SET k.deleted_at = {$now->getValue()}
WHERE k.updated_at<=ag.keywords_loaded_at
WHERE ag.keywords_loaded_at IS NOT NULL
AND k.updated_at<=ag.keywords_loaded_at
AND k.deleted_at is null
AND ag.external_id in (" . implode(", ", $ag_groups) . ")";
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!