AddAds.php 9.25 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\Requests\DirectRequest;
use App\Service\StrReplaceByVariables;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;

class AddAds extends DirectRequest
{
    protected $max_count = 1000;

    protected $timestamp;
    /* @var Collection|GoalAdvertisement[]|Advertisement[]|\stdClass[] */
    protected $goalAds;

    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
    {
        $splinter = $this->sliceByKey($maxObjects, 'Ads');

        $splinter->putParams([
            'goalAds' => $this->goalAds->slice($maxObjects)->values(),
        ]);

        $this->putParams([
            'goalAds' => $this->goalAds->slice(0, $maxObjects),
        ]);

        return $splinter;
    }

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

        foreach ($response['result']['AddResults'] as $key => $add_result) {

            /* @var $goalAd GoalAdvertisement|Advertisement|\stdClass */
            $goalAd = $this->goalAds->get($key);

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

            if (!isset($add_result['Id'])) {

                if (
                    isset($add_result['Errors'][0]['Code'])
                    &&
                    $add_result['Errors'][0]['Code'] == 8800
                    &&
                    isset($add_result['Errors'][0]['Details'])
                    &&
                    $add_result['Errors'][0]['Details'] === 'Ad group not found'
                ) {

                    if ($this->getToken()->isMain()) {
                        Advertisement::where('id', $goalAd->id)
                            ->forceDelete();
                    } else {
                        $model = GoalAdvertisement::with('goalAdGroup')->firstWhere('id', $goalAd->id);

                        if ($model) {
                            if ($model->goalAdGroup) {
                                $model->goalAdGroup->delete();
                            }
                            $model->forceDelete();
                        }
                    }

                    continue;

                } elseif (
                    isset($add_result['Errors'][0]['Code'])
                    &&
                    $add_result['Errors'][0]['Code'] == 8800
                    &&
                    isset($add_result['Errors'][0]['Details'])
                    &&
                    $add_result['Errors'][0]['Details'] === 'vCard not found'
                ) {

                    if ($this->getToken()->isMain()) {
                        Advertisement::where('id', $goalAd->id)
                            ->forceDelete();
                    } else {
                        $model = GoalAdvertisement::with('goalAdGroup')->firstWhere('id', $goalAd->id);

                        if ($model) {
                            if ($model->goalVCard) {
                                $model->goalVCard->delete();
                            }
                            $model->forceDelete();
                        }
                    }

                    continue;

                } elseif (isset($add_result['Errors']) && count($add_result['Errors'])) {
                    $goalAd->errors()->create([
                        'token_id' => $this->getToken()->getKey(),
                        'service' => $this->getService(),
                        'method' => $this->getMethod(),
                        'params' => $data,
                        'errors' => $add_result['Errors'],
                    ]);

                    GoalAdvertisement::whereId($goalAd->id)
                        ->update([
                            'reserve_create_at' => null,
                        ]);

                    continue;

                }

                Log::debug("AddAds, empty Id, token_id {$this->getToken()->getKey()}");
                Log::debug($add_result);
                Log::debug($data);

                GoalAdvertisement::whereId($goalAd->id)
                    ->update([
                        'reserve_create_at' => null,
                    ]);

                continue;
            }

            $external_id = (string)$add_result['Id'];

            GoalAdvertisement::whereId($goalAd->id)
                ->update([
                    'external_id' => $external_id,
                    'external_upload_at' => Carbon::now(),
                    'reserve_create_at' => null,
                ]);

        }
    }

    public function failed()
    {
        GoalAdvertisement::whereIn('id', $this->goalAds->pluck('id')->toArray())
            ->update([
                'reserve_create_at' => null,
            ]);
    }

    public function putParams($params)
    {
        $this->goalAds = $params['goalAds'];
    }

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

        $this->putParams($params);

        $variables = Variable::all();

        $lists = [];

        $this->setParams([
            'Ads' => $this->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 = [
                    'AdGroupId' => $goalAdvertisement->goal_ad_group_external_id,
                    'TextAd' => [
                        'Title' => StrReplaceByVariables::getInstance($goalAdvertisement->title, $list)->get(),
                        'Text' => StrReplaceByVariables::getInstance($goalAdvertisement->text, $list)->get(),
                        'Mobile' => $goalAdvertisement->mobile ? 'YES' : 'NO',
                    ],
                ];

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

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

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

                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_extension_ids = array_filter(@json_decode($goalAdvertisement->ad_extension_ids, true))) {
                    $data['TextAd']['AdExtensionIds'] = $ad_extension_ids;
                }

                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(),
        ]);
    }

}