AdvertisementsArchive.php 2.47 KB
<?php

namespace App\Console\Commands;

use App\Models\Advertisement;
use App\Models\Pivots\GoalAdvertisement;
use App\Models\Tokens;
use App\Service\Requests\Direct\ArchiveAds;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * 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()
    {
        $token = Tokens::allowedLimit()->firstWhere('type', '!=', Tokens::MAIN);

        if ($token) {
            $this->sendRequest($token, Advertisement::forNotArchived()->needArchived()->forNotReserveArchive()->get());
        }

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

        foreach ($tokens as $token) {
            $this->sendRequest($token, $token->dictionaryCampaignsEnabledForExternalSynchronized->pluck('goalAdvertisementsForNeedArchivedForNotReserveArchiveForNotArchived')->collapse());
        }

        return 0;
    }

    private function sendRequest($token, $ads)
    {
        /* @var $ads Advertisement[]|GoalAdvertisement[] */
        if (!$ads->count()) {
            return;
        }

        foreach (array_chunk($ads->pluck('external_id')->toArray(), 100) as $items) {
            if ($token->isMain()) {
                Advertisement::whereIn('external_id', $items)
                    ->update([
                        'reserve_archive_at' => Carbon::now(),
                    ]);
            } else {
                GoalAdvertisement::whereIn('external_id', $items)
                    ->update([
                        'reserve_archive_at' => Carbon::now(),
                    ]);
            }
        }

        $request = new ArchiveAds();
        $request->setToken($token)
            ->call([
                'ids' => $ads->pluck('external_id')->toArray(),
            ]);
    }

}