AdGroupsLoadUpdated.php 2.53 KB
<?php

namespace App\Console\Commands;

use App\Models\AdGroup;
use App\Models\Tokens;
use App\Service\API\API;
use App\Service\Requests\APIRequest;
use Illuminate\Console\Command;

class AdGroupsLoadUpdated extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'adgroups:loadUpdated';

    /**
     * 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()
    {
        $adGroups = AdGroup::has('campaignForEnabledForManaged')->forUpdatedSelf()->get();
        if (!$adGroups->count()) {
            return;
        }

        $token = Tokens::where('type', Tokens::MAIN)->first();
        if (!$token) {
            throw new \Exception('Не найден токен блин');
        }

        $ids = $adGroups->pluck('external_id')->all();

        $factory = APIRequest::getInstance(API::YANDEX);
        $factory->setToken($token);

        $factory->getRequest('AdGroups', 'get')->call([
            'Ids' => $ids,
        ]);

        $factory = APIRequest::getInstance(API::YANDEX);
        $factory->setToken($token);

        $factory->getRequest('Keywords', 'get')->call([
            'AdGroupIds' => $ids,
        ]);

        $tokens = Tokens::has('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf')
            ->with('dictionaryCampaignsEnabledForExternalSynchronized.groupsForExternalForUpdatedSelf')
            ->where('type', '!=', Tokens::MAIN)
            ->get();

        foreach ($tokens as $token) {
            $factory = APIRequest::getInstance(API::YANDEX);
            $factory->setToken($token);

            $ids = $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('groupsForExternalForUpdatedSelf')
                ->collapse()
                ->pluck('external_id')
                ->all();

            $factory->getRequest('AdGroups', 'get')->call([
                'Ids' => $ids,
            ]);

            $factory = APIRequest::getInstance(API::YANDEX);
            $factory->setToken($token);

            $factory->getRequest('Keywords', 'get')->call([
                'AdGroupIds' => $ids,
            ]);
        }

        return 0;
    }
}