GetAds.php 8.74 KB
<?php

namespace App\Service\Requests\Direct;

use App\Jobs\ProcessCallLimitedAPI;
use App\Models\AdExtension;
use App\Models\AdGroup;
use App\Models\Advertisement;
use App\Service\Contract\APIRequest;
use App\Service\Requests\DirectRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class GetAds extends DirectRequest
{
    protected $max_count = -1;
    protected $max_count_CampaignIds = 10;
    protected $max_count_AdGroupIds = 1000;
    protected $max_count_Ids = 10000;

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

    public function getObjectsCount()
    {
        $params = $this->getParams();
        if (isset($params['SelectionCriteria']['CampaignIds'])) {
            return -1;
        }
        if (isset($params['SelectionCriteria']['AdGroupIds'])) {
            return -1;
        }
        if (isset($params['SelectionCriteria']['Ids'])) {
            return count($params['SelectionCriteria']['Ids']);
        }
        return -1;
    }

    public function slice($maxObjects): ?APIRequest
    {
        $params = $this->getParams();

        if (isset($params['SelectionCriteria']['Ids'])) {
            return $this->sliceByKey($maxObjects, ['SelectionCriteria', 'Ids']);
        }

        return null;
    }

    function handle($response)
    {
        $external_ids = [];

        if (!isset($response['result']['Ads'])) {
            return;
        }

        foreach ($response['result']['Ads'] as $ad) {
            $adGroupId = (string)$ad['AdGroupId'];

            if (isset($external_ids[$adGroupId])) {
                continue;
            }
            $external_ids[$adGroupId] = true;
        }

        if (!count($external_ids)) {
            return;
        }

        if ($this->getToken()->isMain()) {
            $ad_groups = AdGroup::whereIn('external_id', array_keys($external_ids))
                ->get()
                ->keyBy('external_id');
        } else {
            //
        }

        foreach ($response['result']['Ads'] as $ad) {

            $ad_group = $ad_groups->get((string)$ad['AdGroupId']);

            if (!$ad_group || !$ad_group->campaign)
                continue;


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

            if ($this->getToken()->isMain()) {

                $ad_extensions = collect();

                $data = [
                    'external_id' => $external_id,
                    'campaign_external_id' => $ad_group->campaign->external_id,
                    'ad_group_external_id' => $ad_group->external_id,
                    'ad_group_id' => $ad_group->getKey(),
                    'campaign_id' => $ad_group->campaign->getKey(),

                    'status' => $ad['Status'],
                    'state' => $ad['State'],
                    'status_clarification' => $ad['StatusClarification'],
                    'ad_categories' => $ad['AdCategories']['Items'] ?? [],
                    'age_label' => $ad['AgeLabel'],
                    'type' => $ad['Type'],
                    'sub_type' => $ad['Subtype'],

                    'updated_self' => null,
                ];

                if (isset($ad['TextAd'])) {
                    $data = array_merge($data, [
                        'title' => $ad['TextAd']['Title'],
                        'title2' => $ad['TextAd']['Title2'],
                        'text' => $ad['TextAd']['Text'],
                        'href' => $ad['TextAd']['Href'],
                        'mobile' => $ad['TextAd']['Mobile'] === 'YES',
                        'display_domain' => $ad['TextAd']['DisplayDomain'],
                        'display_url_path' => $ad['TextAd']['DisplayUrlPath'],
                        'v_card_external_id' => $ad['TextAd']['VCardId'],
                        'ad_image_hash' => $ad['TextAd']['AdImageHash'],
                        'sitelink_external_id' => $ad['TextAd']['SitelinkSetId'],
                        'display_url_path_moderation' => $ad['TextAd']['DisplayUrlPathModeration'],
                        'v_card_moderation' => $ad['TextAd']['VCardModeration'],
                        'site_links_moderation' => $ad['TextAd']['SitelinksModeration'],
                        'ad_image_moderation' => $ad['TextAd']['AdImageModeration'],
                        'video_extension' => $ad['TextAd']['VideoExtension'],
                        'price_extension' => $ad['TextAd']['PriceExtension'],
                        'turbo_page_id' => $ad['TextAd']['TurboPageId'],
                        'turbo_page_moderation' => $ad['TextAd']['TurboPageModeration'],
                        'business_id' => $ad['TextAd']['BusinessId'],
                        'prefer_v_card_over_business' => isset($ad['TextAd']['PreferVCardOverBusiness']) ? $ad['TextAd']['PreferVCardOverBusiness'] === 'YES' : null,
                    ]);

                    $ad_extensions_array = [];

                    foreach ($ad['TextAd']['AdExtensions'] as $ad_extensions_data) {

                        $ad_extension_external_id = (string)$ad_extensions_data['AdExtensionId'];

                        $ad_extension = AdExtension::firstWhere('external_id', $ad_extension_external_id);

                        if (!$ad_extension) {
                            $ad_extensions_array[] = $ad_extensions_data;
                            continue;
                        }

                        $ad_extensions->push($ad_extension);

                    }

                    $data['ad_extensions'] = $ad_extensions_array;
                }

                $advertisement = Advertisement::updateOrCreate([
                    'external_id' => $external_id
                ], $data);

                if ($advertisement->state === Advertisement::STATE_ARCHIVED) {
                    $advertisement->goalAdvertisements()
                        ->notNeedArchived()
                        ->update([
                            'archived_need' => Carbon::now(),
                        ]);
                }

                $adExtensions_sync = $advertisement->adExtensions()->sync($ad_extensions->pluck('id'));

                if ($advertisement->wasRecentlyCreated) {
                    $campaign_ids_synced_need[$advertisement->campaign_id] = true;
                } elseif ($advertisement->wasChanged(['campaign_id'])) {
                    $campaign_ids_synced_need[$advertisement->campaign_id] = true;
                } elseif (
                    $advertisement->wasChanged($advertisement::getPropertiesWatch()->toArray())
                    ||
                    !empty($adExtensions_sync['attached'])
                    ||
                    !empty($adExtensions_sync['detached'])
                    ||
                    !empty($adExtensions_sync['updated'])
                ) {
                    $advertisement->goalAdvertisements()->has('dictionaryCampaign')->forExternal()->update([
                        'updated_need' => Carbon::now(),
                    ]);
                }


            } else {
                //
            }

        }
    }

    private function requestPrepare($filter)
    {
        $this->setService('Ads');
        $this->setMethod('get');
        $params = [
            "SelectionCriteria" => [
                "Types" => [
                    "TEXT_AD",
                ],
            ],
            "FieldNames" => [
                "AdCategories", "AgeLabel", "AdGroupId",
                "CampaignId", "Id", "State", "Status",
                "StatusClarification", "Type", "Subtype",
            ],
            "TextAdFieldNames" => [
                "AdImageHash", "DisplayDomain", "Href",
                "SitelinkSetId", "Text", "Title",
                "Title2", "Mobile", "VCardId",
                "DisplayUrlPath", "AdImageModeration",
                "SitelinksModeration", "VCardModeration",
                "AdExtensions", "DisplayUrlPathModeration",
                "VideoExtension", "TurboPageId",
                "TurboPageModeration", "BusinessId",
                "PreferVCardOverBusiness",
            ],
            "TextAdPriceExtensionFieldNames" => [
                "Price", "OldPrice", "PriceCurrency", "PriceQualifier",
            ],
        ];

        if (isset($filter['States'])) {
            $params['SelectionCriteria']['States'] = $filter['States'];
        }

        if (isset($filter['CampaignIds'])) {
            $params['SelectionCriteria']['CampaignIds'] = $filter['CampaignIds'];
        }
        if (isset($filter['AdGroupIds'])) {
            $params['SelectionCriteria']['AdGroupIds'] = $filter['AdGroupIds'];
        }
        if (isset($filter['Ids'])) {

            $this->max_count = $this->max_count_Ids;

            $params['SelectionCriteria']['Ids'] = $filter['Ids'];
        }
        $this->setParams($params);
    }
}