UpdateAds.php 8.15 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\Advertisement;
use App\Models\Pivots\GoalAdvertisement;
use App\Models\Variable;
use App\Service\Contract\APIRequest;
use App\Service\DirectResponseHelper;
use App\Service\Requests\DirectRequest;
use App\Service\StrReplaceByVariables;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class UpdateAds extends DirectRequest
{
    protected $max_count = 1000;

    protected $timestamp;

    public function call($params = null)
    {
        $this->requestPrepare($params);
        $process = new ProcessCallLimitedAPI($this);
        dispatch($process)->onQueue('limits');
    }

    public function getObjectsCount()
    {
        return count($this->getParams()['Ads']);
    }

    public function slice($maxObjects): ?APIRequest
    {
        return $this->sliceByKey($maxObjects, 'Ads');;
    }

    public function handle($response)
    {
        if (!isset($response['result']['UpdateResults'])) {
            return;
        }

        foreach (DirectResponseHelper::getExternalIdsChunkByResult($response['result']['UpdateResults']) as $external_ids) {
            GoalAdvertisement::whereIn('external_id', $external_ids)
                ->update([
                    'updated_need' => null,
                    'reserve_update_at' => null,
                    'updated_at' => Carbon::now(),
                ]);
        }

        foreach ($response['result']['UpdateResults'] as $key => $update_result) {

            if (isset($update_result['Id'])) {
                continue;
            }

            $data = $this->getParams()['Ads'][$key];

            $external_id = $data['Id'];

            if (isset($update_result['Errors'][0]['Details']) && $update_result['Errors'][0]['Details'] === 'You cannot update an archived ad') {
                GoalAdvertisement::whereExternalId($external_id)
                    ->update([
                        'deleted_need' => Carbon::now(),
                        'archived_need' => null,
                        'reserve_archive_at' => null,
                    ]);
                continue;
            } elseif (isset($update_result['Errors'][0]['Details']) && $update_result['Errors'][0]['Details'] === 'Ad not found') {

                $model = GoalAdvertisement::whereExternalId($external_id)->first();

                if ($model) {
                    $model->goalAdGroup()->delete();
                    $model->delete();
                }
                GoalAdvertisement::whereExternalId($external_id)
                    ->delete();
                continue;
            } elseif (isset($update_result['Errors']) && count($update_result['Errors'])) {
                $model = GoalAdvertisement::whereExternalId($external_id)->first();

                if ($model) {
                    $model->errors()->create([
                        'token_id' => $this->getToken()->getKey(),
                        'service' => $this->getService(),
                        'method' => $this->getMethod(),
                        'params' => $data,
                        'errors' => $update_result['Errors'],
                    ]);
                }
            } else {
                Log::debug("UpdateAds, empty Id, token_id {$this->getToken()->getKey()}");
                Log::debug($update_result);
                Log::debug($data);
            }

            GoalAdvertisement::withTrashed()->whereExternalId($external_id)
                ->update([
                    'reserve_update_at' => null,
                ]);

        }

        $this->getToken()->update([
            'check_changes_ad_group' => Carbon::now()->addSeconds(5),
        ]);
    }

    public function failed()
    {
        GoalAdvertisement::whereIn('external_id', array_column($this->getParams()['Ads'], 'Id'))
            ->update([
                'reserve_update_at' => null,
            ]);
    }

    private function requestPrepare($params)
    {
        $this->setService('Ads');
        $this->setMethod('update');

        $variables = Variable::all();

        $lists = [];

        $this->setParams([
            'Ads' => $params['goalAds']->map(function ($goalAdvertisement) use ($variables, &$lists) {

                /* @var $goalAdvertisement GoalAdvertisement|Advertisement|\stdClass */

                if (!isset($lists[$goalAdvertisement->dictionary_campaign_id])) {
                    $list = Variable::getListVariablesByDictionaryCampaign($goalAdvertisement->dictionary_campaign_id, $variables);
                    $lists[$goalAdvertisement->dictionary_campaign_id] = $list;
                } else {
                    $list = $lists[$goalAdvertisement->dictionary_campaign_id];
                }

                $data = [
                    'Id' => $goalAdvertisement->external_id,
                    'TextAd' => [
                        'Title' => StrReplaceByVariables::getInstance($goalAdvertisement->title, $list)->get(),
                        'Text' => StrReplaceByVariables::getInstance($goalAdvertisement->text, $list)->get(),
                    ],
                ];

                if ($goalAdvertisement->age_label) {
                    $data['TextAd']['AgeLabel'] = $goalAdvertisement->age_label;
                }

                if ($goalAdvertisement->title2) {
                    $data['TextAd']['Title2'] = StrReplaceByVariables::getInstance($goalAdvertisement->title2, $list)->get();
                }

                if ($goalAdvertisement->href) {
                    $data['TextAd']['Href'] = StrReplaceByVariables::getInstance($goalAdvertisement->href, $list)->get();
                }

                if ($goalAdvertisement->display_url_path) {
                    $data['TextAd']['DisplayUrlPath'] = StrReplaceByVariables::getInstance($goalAdvertisement->display_url_path, $list)->get();
                }

                if ($goalAdvertisement->goal_v_card_external_id) {
                    $data['TextAd']['VCardId'] = $goalAdvertisement->goal_v_card_external_id;
                }

                if ($goalAdvertisement->ad_image_hash) {
                    $data['TextAd']['AdImageHash'] = $goalAdvertisement->ad_image_hash;
                }

                if ($goalAdvertisement->goal_sitelink_external_id) {
                    $data['TextAd']['SitelinkSetId'] = $goalAdvertisement->goal_sitelink_external_id;
                }

                if ($ad_extensions = array_filter(@json_decode($goalAdvertisement->ad_extensions, true), function ($item) {
                    return $item['AdExtensionId'];
                })) {
                    $data['TextAd']['CalloutSetting'] = [
                        'AdExtensions' => $ad_extensions,
                    ];
                }

                if ($video_extension = @json_decode($goalAdvertisement->video_extension, true)) {
                    $data['TextAd']['VideoExtension'] = [
                        'CreativeId' => $video_extension['CreativeId'],
                    ];
                }

                if ($price_extension = @json_decode($goalAdvertisement->price_extension, true)) {
                    $data['TextAd']['PriceExtension'] = [
                        'Price' => $price_extension['Price'],
                        'PriceQualifier' => $price_extension['PriceQualifier'],
                        'PriceCurrency' => $price_extension['PriceCurrency'],
                    ];

                    if (isset($price_extension['OldPrice']) && !is_null($price_extension['OldPrice'])) {
                        $data['TextAd']['PriceExtension']['OldPrice'] = $price_extension['OldPrice'];
                    }
                }

                if ($goalAdvertisement->turbo_page_id) {
                    $data['TextAd']['TurboPageId'] = $goalAdvertisement->turbo_page_id;
                }

                if ($goalAdvertisement->business_id) {
                    $data['TextAd']['BusinessId'] = $goalAdvertisement->business_id;
                }

                if ($goalAdvertisement->prefer_v_card_over_business) {
                    $data['TextAd']['PreferVCardOverBusiness'] = $goalAdvertisement->prefer_v_card_over_business ? 'YES' : 'NO';
                }

                return $data;
            })->toArray(),
        ]);
    }

}