AdGroupsDelete.php 2.89 KB
<?php

namespace App\Console\Commands;

use App\Models\Pivots\GoalAdGroup;
use App\Models\Tokens;
use App\Service\Requests\Direct\DeleteAdGroups;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class AdGroupsDelete extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'adgroups: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.7
     *
     * @return int
     */
    public function handle()
    {
        foreach (Tokens::where('type', '!=', Tokens::MAIN)->get() as $token) {
            $result = DB::select("SELECT gag.external_id
                FROM goal_ad_groups gag
                INNER JOIN ad_groups ag ON gag.ad_group_id = ag.id
                INNER JOIN dictionary_campaigns c ON c.id = gag.dictionary_campaign_id
                INNER JOIN dictionaries d ON d.id = c.dictionary_id
                WHERE gag.external_id is not null
                    AND ag.deleted_at is not null
                    AND gag.deleted_at is null
                    AND d.token_id=" . $token->id . "
                    AND NOT EXISTS (
                        SELECT 1 FROM goal_advertisements as ga
                        WHERE gag.id = ga.goal_ad_group_id
                            AND ga.deleted_at is null
                            AND ga.external_id is not null
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM goal_keywords as gk
                        WHERE gag.id = gk.goal_ad_group_id
                            AND gk.external_id is not null
                    )
                    AND NOT EXISTS (
                        SELECT 1 FROM goal_audience_targets as gat
                        WHERE gag.id = gat.goal_ad_group_id
                            AND gat.deleted_at is null
                            AND gat.external_id is not null
                    )
            ");
            $ids = [];

            foreach ($result as $item) {
                $ids[] = $item->external_id;
            }

            if (!count($ids)) {
                continue;
            }

            foreach (array_chunk($ids, 100) as $items) {
                GoalAdGroup::whereIn('external_id', $items)
                    ->update([
                        'reserve_delete_at' => Carbon::now(),
                    ]);
            }

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

        return 0;
    }
}