AddAds.php 6.41 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)
    {
        try {
            if (!isset($response['result']['AddResults'])) {
                return;
            }

            foreach ($response['result']['AddResults'] as $key => $add_result) {
                if (!isset($add_result['Id'])) {
                    Log::debug("AddAds, empty Id");
                    Log::debug($add_result);
                    Log::debug($this->getParams()['Ads'][$key]);
                    continue;
                }

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

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

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

            }
        } catch (\Exception $e) {
            Log::debug($e);
            throw $e;
        }
    }

    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->v_card_id) {
                    $data['TextAd']['VCardId'] = $goalAdvertisement->v_card_id;
                }

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

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

                if ($ad_extensions = @json_decode($goalAdvertisement->ad_extensions, true)) {
                    $data['TextAd']['AdExtensionIds'] = array_map(function ($ad_extension) {
                        return $ad_extension['AdExtensionId'];
                    }, $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(),
        ]);
    }

}