AdvertisementsDelete.php 2.13 KB
<?php

namespace App\Console\Commands;

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

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

    /**
     * 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::has('dictionaryCampaignsEnabledForExternalSynchronized.goalAdvertisementsForNeedDeletedForNotReserveDelete')
            ->where('type', '!=', Tokens::MAIN)
            ->get();

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

        return 0;
    }

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

        $ids = $ads->pluck('external_id')->toArray();

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

        $request = new DeleteAds();
        $request->setToken($token)
            ->call([
                'ids' => $ids,
            ]);
    }

}