VCardsDelete.php 2.23 KB
<?php

namespace App\Console\Commands;

use App\Models\VCard;
use App\Models\Pivots\GoalVCard;
use App\Models\Tokens;
use App\Service\Requests\Direct\DeleteAds;
use App\Service\Requests\Direct\DeleteVCards;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

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

        return 0;
    }

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

        foreach (array_chunk($ads->pluck('external_id')->toArray(), 1000) as $items) {
            if ($token->isMain()) {
                VCard::whereIn('external_id', $items)
                    ->update([
                        'reserve_delete_at' => Carbon::now(),
                    ]);
            } else {
                GoalVCard::whereIn('external_id', $items)
                    ->update([
                        'reserve_delete_at' => Carbon::now(),
                    ]);
            }
        }

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

}