Commit e7bcf03d by Vladislav

Исправление, оптимизация

1 parent 1af60eed
...@@ -62,8 +62,6 @@ class AdvertisementsDelete extends Command ...@@ -62,8 +62,6 @@ class AdvertisementsDelete extends Command
$ids = $ads->pluck('external_id')->toArray(); $ids = $ads->pluck('external_id')->toArray();
dd($ids);
foreach (array_chunk($ids, 1000) as $items) { foreach (array_chunk($ids, 1000) as $items) {
if ($token->isMain()) { if ($token->isMain()) {
Advertisement::whereIn('external_id', $items) Advertisement::whereIn('external_id', $items)
......
...@@ -44,11 +44,11 @@ class VCardsDelete extends Command ...@@ -44,11 +44,11 @@ class VCardsDelete extends Command
*/ */
public function handle() public function handle()
{ {
$tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronized.goalVCardsForNeedDeleteForNotReserveDelete') $tokens = Tokens::where('type', '!=', Tokens::MAIN)
->where('type', '!=', Tokens::MAIN)
->get(); ->get();
foreach ($tokens as $token) { foreach ($tokens as $token) {
$token->load('dictionaryCampaignsEnabledForExternalSynchronized.goalVCardsForNeedDeleteForNotReserveDelete');
$this->sendRequest( $this->sendRequest(
$token, $token,
$token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('goalVCardsForNeedDeleteForNotReserveDelete')->collapse() $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('goalVCardsForNeedDeleteForNotReserveDelete')->collapse()
......
...@@ -39,6 +39,7 @@ class ProcessCallAPI implements ShouldQueue ...@@ -39,6 +39,7 @@ class ProcessCallAPI implements ShouldQueue
* Execute the job. * Execute the job.
* *
* @return void * @return void
* @throws \Throwable
*/ */
public function handle() public function handle()
{ {
...@@ -58,7 +59,11 @@ class ProcessCallAPI implements ShouldQueue ...@@ -58,7 +59,11 @@ class ProcessCallAPI implements ShouldQueue
$maxObjects = $limits->countObjectsLimitReserve($this->api, $limit); $maxObjects = $limits->countObjectsLimitReserve($this->api, $limit);
} }
if ($maxObjects && $maxObjects !== $limits::NAN && $this->api->getObjectsCount() > $maxObjects) { if (
($maxObjects && $maxObjects !== $limits::NAN && $this->api->getObjectsCount() > $maxObjects)
||
(($maxObjects = $this->api->getMaxCount()) && $maxObjects !== $limits::NAN && $this->api->getObjectsCount() > $maxObjects)
) {
//те на которые не хватило баллов помещаем в очередь //те на которые не хватило баллов помещаем в очередь
if ($apiR = $this->api->slice($maxObjects)) { if ($apiR = $this->api->slice($maxObjects)) {
dispatch(new ProcessCallLimitedAPI($apiR))->onQueue('limits'); dispatch(new ProcessCallLimitedAPI($apiR))->onQueue('limits');
...@@ -71,12 +76,20 @@ class ProcessCallAPI implements ShouldQueue ...@@ -71,12 +76,20 @@ class ProcessCallAPI implements ShouldQueue
$handler->handle($response); $handler->handle($response);
} catch (\Exception $e) { } catch (\Exception $e) {
//TODO: надо отдельно выделить ошибки вызовов, за которые списываются баллы
//https://yandex.ru/dev/direct/doc/dg/concepts/errors.html
//Log::debug($this->api->getParams());
Log::debug(''); Log::debug('');
Log::debug("Exception in ProcessCallAPI, удаляем резервирование баллов. token_id {$this->api->getToken()->getKey()}, объектов {$this->api->getObjectsCount()} {$this->api->getService()} {$this->api->getMethod()}"); Log::debug("Exception in ProcessCallAPI, удаляем резервирование баллов. token_id {$this->api->getToken()->getKey()}, объектов {$this->api->getObjectsCount()} {$this->api->getService()} {$this->api->getMethod()}");
$limits->removeRezerv($this->limitId);
if (isset($response)) {
$headerLimit = new HeaderLimits($response->headers());
}
try {
$limits->removeRezerv($this->limitId, $headerLimit ?? null);
} catch (\Throwable $e) {
Log::error($e);
}
throw $e; throw $e;
} }
} }
......
...@@ -51,7 +51,7 @@ class ProcessCallLimitedAPI implements ShouldQueue//, ShouldBeUnique ...@@ -51,7 +51,7 @@ class ProcessCallLimitedAPI implements ShouldQueue//, ShouldBeUnique
try{ try{
//резервируем на это количетсво //резервируем на это количетсво
$limit = $limits->getSpent($objects, $this->api); $limit = $limits->getSpent($objects, $this->api);
Log::debug("Резервируем баллы {$limit}, token_id {$this->api->getToken()->getKey()}, на объекты {$objects} {$this->api->getService()} {$this->api->getMethod()}"); Log::debug("Резервируем баллы {$limit}, token_id {$this->api->getToken()->getKey()}, на объекты {$this->api->getObjectsCount()} {$this->api->getService()} {$this->api->getMethod()}");
$limitId = $limits->doRezerv($this->api, $objects); $limitId = $limits->doRezerv($this->api, $objects);
}catch(\Exception $e){ }catch(\Exception $e){
......
...@@ -535,15 +535,11 @@ class DictionaryCampaign extends Pivot ...@@ -535,15 +535,11 @@ class DictionaryCampaign extends Pivot
public function goalVCardsForNeedDeleteForNotReserveDelete() public function goalVCardsForNeedDeleteForNotReserveDelete()
{ {
return $this->goalVCards()->whereNotExists(function (\Illuminate\Database\Query\Builder $query) { return $this->goalVCards()->leftJoin('goal_advertisements', 'goal_v_cards.id', '=', 'goal_advertisements.goal_v_card_id')
$query->select(DB::raw(1)) ->where(function (\Illuminate\Database\Eloquent\Builder $query) {
->from('goal_advertisements') $query->whereNotNull('goal_advertisements.archive_at')
->whereColumn('goal_v_cards.id', 'goal_advertisements.goal_v_card_id') ->orWhereNotNull('goal_advertisements.deleted_at')
->where(function (\Illuminate\Database\Query\Builder $query) { ->orWhereNull('goal_advertisements.id');
$query->whereNull('goal_advertisements.archive_at')
->whereNull('goal_advertisements.deleted_at');
});
return $query;
})->forExternal()->forNotReserveDelete(); })->forExternal()->forNotReserveDelete();
} }
......
...@@ -63,7 +63,7 @@ class GoalVCard extends Pivot ...@@ -63,7 +63,7 @@ class GoalVCard extends Pivot
*/ */
public function scopeForExternal($query) public function scopeForExternal($query)
{ {
return $query->whereNotNull('external_id'); return $query->whereNotNull("{$this->getTable()}.external_id");
} }
/** /**
...@@ -108,7 +108,7 @@ class GoalVCard extends Pivot ...@@ -108,7 +108,7 @@ class GoalVCard extends Pivot
*/ */
public function scopeForNotReserveDelete($query) public function scopeForNotReserveDelete($query)
{ {
return $query->whereNull('reserve_delete_at'); return $query->whereNull("{$this->getTable()}.reserve_delete_at");
} }
public function vCard() public function vCard()
......
...@@ -154,13 +154,26 @@ class Limits implements \App\Service\Contract\Limits { ...@@ -154,13 +154,26 @@ class Limits implements \App\Service\Contract\Limits {
return $rezerv->id; return $rezerv->id;
} }
function removeRezerv(int $id) /**
* @var $id integer
* @var $headerLimits HeaderLimits|null
*
* @throws \Exception|\Throwable
*/
function removeRezerv(int $id, HeaderLimits $headerLimits = null)
{ {
DB::beginTransaction(); DB::beginTransaction();
try{ try{
$limit = \App\Models\Limits::findOrFail($id); $limit = \App\Models\Limits::findOrFail($id);
if ($headerLimits) {
$this->token->limit = $headerLimits->getCurrentLimit();
} else {
$this->token->limit += $limit->spent; $this->token->limit += $limit->spent;
}
$this->token->save(); $this->token->save();
$limit->delete(); $limit->delete();
DB::commit(); DB::commit();
......
...@@ -40,31 +40,23 @@ class DeleteKeywords extends DirectRequest ...@@ -40,31 +40,23 @@ class DeleteKeywords extends DirectRequest
$delete_results = $response['result']['DeleteResults']; $delete_results = $response['result']['DeleteResults'];
foreach (array_chunk(array_column(array_filter($delete_results, function ($delete_result) { foreach (array_chunk($this->getDeleteExternalIds($delete_results), 1000) as $external_ids) {
return isset($delete_result['Id']); GoalKeyword::whereIn('external_id', $external_ids)->delete();
}), 'Id'), 1000) as $external_ids) {
GoalKeyword::whereExternalId($external_ids)->delete();
} }
foreach ($delete_results as $key => $delete_result) { foreach ($delete_results as $key => $delete_result) {
if (isset($delete_result['Id'])) { if (isset($delete_result['Id']) || $this->isExistErrorKeywordNotFound($delete_result)) {
continue; continue;
} }
$external_id = $this->getParams()['SelectionCriteria']['Ids'][$key]; $external_id = $this->getParams()['SelectionCriteria']['Ids'][$key];
if (isset($delete_result['Errors'][0]['Details']) && $delete_result['Errors'][0]['Details'] === 'Keyword not found') { if (isset($delete_result['Errors']) && count($delete_result['Errors'])) {
//объекта по какой то причине нет $model = GoalKeyword::whereExternalId($external_id)->first();
GoalKeyword::where('external_id', $external_id)->delete();
continue;
} elseif (isset($delete_result['Errors']) && count($delete_result['Errors'])) {
$goalKeyword = GoalKeyword::whereExternalId($external_id)->first();
if ($goalKeyword) { if ($model) {
$goalKeyword->errors()->create([ $model->errors()->create([
'token_id' => $this->getToken()->getKey(), 'token_id' => $this->getToken()->getKey(),
'service' => $this->getService(), 'service' => $this->getService(),
'method' => $this->getMethod(), 'method' => $this->getMethod(),
...@@ -107,4 +99,21 @@ class DeleteKeywords extends DirectRequest ...@@ -107,4 +99,21 @@ class DeleteKeywords extends DirectRequest
$this->setParams($params); $this->setParams($params);
} }
private function getDeleteExternalIds(array $data)
{
$delete_external_ids = [];
return array_merge(array_column(array_filter($data, function ($delete_result, $key) use (&$delete_external_ids) {
if (!isset($delete_result['Id']) && $this->isExistErrorKeywordNotFound($delete_result)) {
$delete_external_ids[] = $this->getParams()['SelectionCriteria']['Ids'][$key];
}
return isset($delete_result['Id']);
}, ARRAY_FILTER_USE_BOTH), 'Id'), $delete_external_ids);
}
private function isExistErrorKeywordNotFound(array $data)
{
return isset($data['Errors'][0]['Details']) && $data['Errors'][0]['Details'] === 'Keyword not found';
}
} }
...@@ -11,7 +11,7 @@ use Illuminate\Support\Facades\Log; ...@@ -11,7 +11,7 @@ use Illuminate\Support\Facades\Log;
class DeleteVCards extends DirectRequest class DeleteVCards extends DirectRequest
{ {
protected $max_count = 10000; protected $max_count = 1000;
protected $timestamp; protected $timestamp;
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!