AdGroupsAdd.php 2.12 KB
<?php

namespace App\Console\Commands;

use App\Models\Pivots\GoalAdGroup;
use App\Models\Tokens;
use App\Service\Requests\Direct\AddAdGroups;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AdGroupsAdd extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'adgroups: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.groupsForNotExternalForNotReserveCreate.group')
            ->where('type', '!=', Tokens::MAIN)
            ->get();

        foreach ($tokens as $token) {
            $token->load([
                'dictionaryCampaignsEnabledForExternalSynchronized.groupsForNotExternalForNotReserveCreate' => function (HasMany $query) {
                    return $query->has('group');
                },
                'dictionaryCampaignsEnabledForExternalSynchronized.groupsForNotExternalForNotReserveCreate.group',
            ]);

            $goalAdGroups = $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('groupsForNotExternalForNotReserveCreate')
                ->collapse();

            foreach (array_chunk($goalAdGroups->pluck('id')->toArray(), 1000) as $items) {
                GoalAdGroup::whereIn('id', $items)
                    ->update([
                        'reserve_create_at' => Carbon::now(),
                    ]);
            }

            $factory = new AddAdGroups();
            $factory->setToken($token)
                ->call([
                    'goalAdGroups' => $goalAdGroups,
                ]);
        }

        return 0;
    }
}