UpdateKeywords.php 4.33 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Keyword;
use App\Models\Pivots\GoalKeyword;
use App\Models\Variable;
use App\Service\Contract\APIRequest;
use App\Service\DirectResponseHelper;
use App\Service\Requests\DirectRequest;
use App\Service\StrReplaceByVariables;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class UpdateKeywords extends DirectRequest
{
    protected $max_count = 1000;

    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()['Keywords']);
    }

    public function slice($maxObjects): ?APIRequest
    {
        return $this->sliceByKey($maxObjects, 'Keywords');
    }

    public function handle($response)
    {
        if (!isset($response['result']['UpdateResults'])) {
            return;
        }

        foreach (DirectResponseHelper::getExternalIdsChunkByResult($response['result']['UpdateResults']) as $external_ids) {
            GoalKeyword::whereIn('external_id', $external_ids)
                ->update([
                    'updated_need' => null,
                    'reserve_update_at' => null,
                    'updated_at' => Carbon::now(),
                ]);
        }

        foreach ($response['result']['UpdateResults'] as $key => $update_result) {

            if (isset($update_result['Id'])) {
                continue;
            }

            $data = $this->getParams()['Keywords'][$key];

            $external_id = $data['Id'];

            if (isset($data['Errors'][0]['Details']) && $data['Errors'][0]['Details'] === 'Keyword not found') {

                GoalKeyword::whereExternalId($external_id)->delete();

            } elseif (isset($update_result['Errors']) && count($update_result['Errors'])) {
                $goalKeyword = GoalKeyword::whereExternalId($external_id)->first();

                if ($goalKeyword) {
                    $goalKeyword->errors()->create([
                        'token_id' => $this->getToken()->getKey(),
                        'service' => $this->getService(),
                        'method' => $this->getMethod(),
                        'params' => $data,
                        'errors' => $update_result['Errors'],
                    ]);
                }
            } else {
                Log::debug("UpdateKeywords, empty Id, token_id {$this->getToken()->getKey()}");
                Log::debug($update_result);
                Log::debug($data);
            }

            GoalKeyword::whereExternalId($external_id)
                ->update([
                    'reserve_update_at' => null,
                ]);

        }
    }

    public function failed()
    {
        GoalKeyword::whereIn('external_id', array_column($this->getParams()['Keywords'], 'Id'))
            ->update([
                'reserve_update_at' => null,
            ]);
    }

    private function requestPrepare($params)
    {
        $this->setService('Keywords');
        $this->setMethod('update');

        $variables = Variable::all();

        $lists = [];

        $this->setParams([
            'Keywords' => $params['goalKeywords']->map(function ($goalKeyword) use ($variables, &$lists) {

                /* @var $goalKeyword GoalKeyword|Keyword|\stdClass */

                if (!isset($lists[$goalKeyword->dictionary_campaign_id])) {
                    $list = Variable::getListVariablesByDictionaryCampaign($goalKeyword->dictionary_campaign_id, $variables);
                    $lists[$goalKeyword->dictionary_campaign_id] = $list;
                } else {
                    $list = $lists[$goalKeyword->dictionary_campaign_id];
                }
                $data = [
                    'Id' => $goalKeyword->external_id,
                    'Keyword' => StrReplaceByVariables::getInstance($goalKeyword->keyword, $list)->get(),
                ];

                if ($goalKeyword->user_param_1) {
                    $data['UserParam1'] = $goalKeyword->user_param_1;
                }

                if ($goalKeyword->user_param_2) {
                    $data['UserParam2'] = $goalKeyword->user_param_2;
                }

                return $data;
            })->toArray(),
        ]);
    }

}