Edit file File name : Customer.php Content :<?php namespace App; use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Notifications\Notifiable; use File; class Customer extends Model { use Notifiable; protected $table = 'customers'; protected $primaryKey = 'customer_id'; protected $guarded = ['customer_id']; protected $email = ""; /** * The "booted" method of the model. * * @return void */ protected static function boot() { parent::boot(); static::retrieved(function($model){ if(!$model->info){ $model->email = ""; }else{ $model->email = config('app.email_debug')? config('app.email_to_test'): $model->info->email; } }); // Funções para criação de usuário que exija email devem ser declaradas no created de informations, // Pois o e-mail fica na tabela de informaions, e o registro dela é criado após o de usuário static::created(function ($model) { /* * Veja em Informations */ // Manda notificação para a equiepe if($model->team_id != "") NotifyUser::create([ "team_id" => $model->team_id, "notify_text" => "+1 lead cadastrado na sua equipe <br> ".date('H:i'), "shoot" => date('Y-m-d H:i:s'), "notify_style" => "high" ]); }); static::updated(function ($model) { // Gatilho de email: Pagamento confirmado if($model->wasChanged('stage_id') and $model->stage_id == 4 and $model->getOriginal('stage_id') == 3){ //$old_stage = $model->getOriginal('stage_id'); EmailTigger::shoot('pagamento_ok', $model); } // Gatilho de e-mail: Troca de assistente if($model->wasChanged('assistent_id')){ //$old_stage = $model->getOriginal('stage_id'); //$new_stage = $model->stage_id; //File::append( // storage_path('logs/test.log'), // "stage alterado. \n De:$old_stage \nPara: $new_stage \n\n\n" //); File::append( storage_path('logs/test.log'), "Diparado gatilho assistente_troca \n\n" ); EmailTigger::shoot('assistente_troca', $model); } if ($model->embracon_id && $model->stage_id == 3) { try { Http::withToken(env('EMBRACON_RETORNO_TOKEN')) ->withHeaders(['accept' => 'application/json']) ->put( env('EMBRACON_RETORNO_URL') . "/{$model->embracon_id}", [ 'tags' => ['venda' => true] ] ); } catch (Exception $e) { Log::error('Erro ao enviar retorno para api da embracon'); } } }); } public function info() { return $this->hasOne('App\Information', 'customer_id'); } public function contrato() { return $this->hasOne('App\Contract', 'customer_id'); } public function timeline() { return $this->hasMany('App\Timeline', 'customer_id')->orderBy('created_at', 'desc'); } public function website() { return $this->belongsTo('App\Website'); } public function brand() { return $this->belongsTo('App\Brand', 'brand_id'); } public function produto() { return $this->belongsTo('App\Produto', "produto_id"); } public function assistent() { return $this->belongsTo('App\User', "assistent_id"); } public function team() { return $this->belongsTo('App\Team', "team_id"); } public static function stageTitle($stage_id){ switch ($stage_id) { case 1: return "Novo"; break; case 2: return "Negociando"; break; case 3: return "Vendido (Aguardando confirmação)"; break; case 4: //return "Vendido (Aguardando financeiro)"; return "Vendido"; break; case 5: return "Vendido"; break; case 6: return "Em atendimento"; break; case 7: return "Lixeira"; break; case 8: return "Cobrança"; break; case 9: return "Remarketing"; break; case 10: return "Remanejado"; break; default: return "Não definido"; break; } } public static function listRemarketingByAssistent($user, $page = 0, $limit = 100){ $customers = DB::select('SELECT customers.customer_id as customer_id, customers.brand_id as brand_id, customers.stage_id as stage_id, informations.nome as nome, atendimentos.note as event, teams.team as team, users.name as assistent, customers.opened as opened, atendimentos.created_at as ultimo_atendimento FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id INNER JOIN atendimentos ON atendimentos.atendimento_id = customers.atendimento_id INNER JOIN teams ON teams.team_id = customers.team_id INNER JOIN users ON users.id = customers.assistent_id WHERE customers.stage_id <> 7 AND customers.stage_id <> 9 AND customers.assistent_id = :assistent_id AND (customers.n_atendimentos > 1 OR (customers.n_atendimentos = 1 AND customers.opened = 2)) LIMIT :limit OFFSET :offset', ['assistent_id' => $user, 'limit' => $limit, 'offset' => ($page*$limit)]); //print_r($customers[0]); $remarketing = view('customers.components.listRemarketing', ["customers" => $customers, "listAssistent" => false]); return $remarketing; } public static function countRemarketingByAssistent($user){ $remarketingList = DB::select('SELECT count(customers.customer_id) AS count FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id INNER JOIN atendimentos ON atendimentos.atendimento_id = customers.atendimento_id INNER JOIN teams ON teams.team_id = customers.team_id INNER JOIN users ON users.id = customers.assistent_id WHERE customers.stage_id <> 7 AND customers.stage_id <> 9 AND customers.assistent_id = :assistent_id AND (customers.n_atendimentos > 1 OR (customers.n_atendimentos = 1 AND customers.opened = 2)) AND customers.opened = 2', ['assistent_id' => $user->id]); return $remarketingList[0]->count; } public static function listRemarketingByTeam($team, $page = 0, $limit = 100){ return DB::select('SELECT customers.customer_id as customer_id, customers.brand_id as brand_id, informations.nome as nome, atendimentos.note as event, teams.team as team, users.name as assistent, atendimentos.updated_at as ultimo_atendimento, atendimentos.motivo_finalizacao as motivo_finalizacao FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id INNER JOIN atendimentos ON atendimentos.atendimento_id = customers.atendimento_id INNER JOIN teams ON teams.team_id = customers.team_id LEFT JOIN users ON users.id = customers.assistent_id WHERE customers.stage_id <> 7 AND customers.team_id = :team_id AND customers.stage_id = 9 AND atendimentos.status <> 1 AND customers.opened = 1 ORDER BY atendimentos.updated_at ASC LIMIT :limit OFFSET :offset', ['team_id' => $team, 'limit' => $limit, 'offset' => ($page*$limit)]); } public static function countRemarketingByTeam($team){ $remarketingList = DB::select('SELECT count(customers.customer_id) AS count FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id INNER JOIN atendimentos ON atendimentos.atendimento_id = customers.atendimento_id INNER JOIN teams ON teams.team_id = customers.team_id LEFT JOIN users ON users.id = customers.assistent_id WHERE customers.stage_id <> 7 AND customers.team_id = :team_id AND customers.stage_id = 9 AND atendimentos.status <> 1 AND customers.opened = 1 ', ['team_id' => $team]); return $remarketingList[0]->count; } // Direciona o Lead para um novo atendente public function redirectCustomer($assistent){ if(!$this->canRedirect()) return false; //if($assistent->is_blocked()) return false; $atendimento = Atendimento::where("atendimento_id", $this->atendimento_id)->first(); if($atendimento? $atendimento->status == 1 : false){ $atendimento->end(3, 'Finalizado para remanejar'); } $remarketing = ($this->n_atendimentos >= 1); $this->assistent_id = $assistent->id; $this->opened = 2; $this->stage_id = 10; $this->save(); //$timeline = new Timeline; //$timeline->customer_id = $this->customer_id; /* ** Metrics está usando a mensagem a baixo para identificar leads de remarketing ** Caso necessário alterar a mensagem deve ser alterada a forma como a Metics calcula os leads de remarketing */ //$timeline->event = "O Gerente ".Auth::user()->name." designou para ".($remarketing?"remarketing com ":"")."o assistente ".$assistent->name."."; //$timeline->categoria_id = 5; //$timeline->save(); /* ** Metrics está usando a mensagem a baixo para identificar leads de remarketing ** Caso necessário alterar a mensagem deve ser alterada a forma como a Metics calcula os leads de remarketing */ $timeline_event = "O Gerente ".Auth::user()->name." designou para ".($remarketing?"remarketing com ":"")."o assistente ".$assistent->name."."; $timeline = new Timeline; $timeline->newTimeline($this->customer_id, $timeline_event, 5); return TRUE; } public function getInfo(){ $info = Information::where('customer_id', $this->customer_id)->first(); // Caso não encontre registro, cria um mensagem de erro no lugar do nome if(!$info){ Information::create([ 'customer_id' => $this->customer_id, 'nome' => "[ERRO NO CADASTRO DO CLIENTE]", ]); $info = Information::where('customer_id', $this->customer_id)->first(); } return $info; } // Verifica se o cliente pode ser redirecionado public function canRedirect(){ //Impede redirecionamento para clientes novos if($this->n_atendimentos == 0 ) return false; $contract = Contract::where("customer_id", $this->customer_id)->where('status', "<>", "0")->first(); //$atendimento = Atendimento::where("atendimento_id", $this->atendimento_id)->first(); if($contract) return false; //if($atendimento? $atendimento->status == 1 : false) return false; if(Auth::user()->hasRole("Master") OR (Auth::user()->hasRole("Gerente") && Auth::user()->sector_id == 3 && Auth::user()->team_id == $this->team_id)) return true; return false; } // Verificações de rotina public static function rotina(){ //Atualizar clientes em negociação a mais de 24 horas atualizações e sem tarefas agendadas $updateCustomersRemarketing = DB::select('SELECT * FROM customers INNER JOIN informations ON informations.customer_id = customers.customer_id WHERE customers.stage_id = 2 AND customers.updated_at < :limitUpdated AND customers.atendimento_id NOT IN (SELECT atendimento_id FROM schedules WHERE schedules.atendimento_id = customers.atendimento_id AND schedules.date > :limitSchedulesDate)', ['limitUpdated' => date("Y-m-d H:i:s", strtotime('-1 day')), 'limitSchedulesDate' => date("Y-m-d H:i:s", strtotime('-2 day'))]); return $updateCustomersRemarketing; } // Verificações de rotina public static function rotinaUp(){ $list = self::rotina(); foreach ($list as $value) { $customer = Customer::find($value->customer_id); $atendimento = Atendimento::find($customer->atendimento_id); if($atendimento) $atendimento->end(3, 'Finalizado por Inatividade'); } return self::rotina(); } public static function getListByFilters($args, $paginate = true){ // Se o Usuário for do Setor 1 - Administrativo if(Auth::user()->sector_id == 1) { // Se o Usuário for Master if(Auth::user()->hasRole('Master')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Gerente } elseif(Auth::user()->hasRole('Gerente')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Assistente } elseif(Auth::user()->hasRole('Assistente')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); } // Se o Usuário for do Setor 2 - T.I. } else if(Auth::user()->sector_id == 2) { // Se o Usuário for Master if(Auth::user()->hasRole('Master')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Gerente } elseif(Auth::user()->hasRole('Gerente')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Assistente } elseif(Auth::user()->hasRole('Assistente')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); } // Se o Usuário for do Setor 3 - Vendas } else if(Auth::user()->sector_id == 3) { // Se o Usuário for Master if(Auth::user()->hasRole('Master')) { //$customers = DB::table('view_base_customers'); //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Gerente } elseif(Auth::user()->hasRole('Gerente')) { //$customers = DB::table('view_base_customers')->where('team_id', Auth::user()->team_id); $customers = ViewBaseCustomer::where('team_id', Auth::user()->team_id); // Se o Usuário for Assistente } elseif(Auth::user()->hasRole('Assistente')) { /*$customers = DB::table('view_base_customers') ->where('assistent_id', Auth::user()->id) ->whereIn('stage_id', [1, 2, 3, 10]);*/ $customers = ViewBaseCustomer::where('assistent_id', Auth::user()->id) //->whereIn('stage_id', [1, 2, 3, 7, 10]); ->whereIn('stage_id', [1, 2, 3, 10]); } // Se o Usuário for do Setor 4 - SAC } else if(Auth::user()->sector_id == 4) { // Se o Usuário for Master if(Auth::user()->hasRole('Master')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Gerente } elseif(Auth::user()->hasRole('Gerente')) { //$customers = DB::table('view_base_customers'); $customers = ViewBaseCustomer::where([['customer_id','>','0']]); // Se o Usuário for Assistente } elseif(Auth::user()->hasRole('Assistente')) { //$customers = DB::table('view_base_customers')->where('team_id', Auth::user()->team_id); $customers = ViewBaseCustomer::where('team_id', Auth::user()->team_id); } } // Remove clientes excluidos da listagem if($args->filtro_stage != 7) $customers->where('stage_id', '<>', '7'); // if ($args->filtro_nome) { $customers->where('nome', 'like', '%'.$args->filtro_nome.'%'); } if ($args->filtro_cpf) { $customers->where('cpf', 'like', '%'.$args->filtro_cpf.'%'); } if ($args->filtro_produto) { $customers->where('produto', 'like', '%'.$args->filtro_produto.'%'); } if ($args->filtro_phone) { $customers->where('concat_telefone', 'like', '%'.$args->filtro_phone.'%'); } if ($args->filtro_id) { $customers->where('customer_id', $args->filtro_id); } if ($args->filtro_contrato) { $customers->where('contrato', 'like', '%'.$args->filtro_contrato.'%'); } if ($args->filtro_assistent) { $customers->where('assistent_id', $args->filtro_assistent); } if ($args->filtro_website) { $customers->where('website_id', $args->filtro_website); } if ($args->filtro_stage) { $customers->where('stage_id', $args->filtro_stage); } if ($args->filtro_equipe) { $customers->where('team_id', $args->filtro_equipe); } if ($args->filtro_marca) { $customers->where('brand_id', $args->filtro_marca); } if ($args->filtro_sector) { $customers->where('sector_id', $args->filtro_sector); } if ($args->filtro_data) { $search = $args->filtro_data; $search = str_replace("/","-",$search); // 02/20/2021 00:00:00-02/26/2021 00:00:00 $data = explode(' ~ ',$search); // data[0] {02/20/2021 00:00:00} data[1] {02/26/2021 00:00:00} $search1 = date("Y-m-d H:i:s", strtotime($data[0])); $search2 = date("Y-m-d H:i:s", strtotime($data[1])); $customers->whereBetween('created_at', [$search1, $search2]); } if ($args->filtro_alt) { $search = $args->filtro_alt; $search = str_replace("/","-",$search); // 02/20/2021 00:00:00-02/26/2021 00:00:00 $data = explode(' ~ ',$search); // data[0] {02/20/2021 00:00:00} data[1] {02/26/2021 00:00:00} $search1 = date("Y-m-d H:i:s", strtotime($data[0])); $search2 = date("Y-m-d H:i:s", strtotime($data[1])); $customers->whereBetween('data_event', [$search1, $search2]); } if ($args->filtro_cob) { $customers->where('cob_id', $args->filtro_cob); } $orderbyfield = ""; $orderbyorder = ""; if($args->orderbyfield AND $args->orderbyorder){ $customers->orderBy($args->orderbyfield, $args->orderbyorder); $orderbyfield = $args->orderbyfield; $orderbyorder = $args->orderbyorder; } $quantidade = 25; if($args->limit) $quantidade = $args->limit; if($paginate) $customers = $customers->paginate($quantidade); else $customers = $customers->get(); return $customers; } public function getHashNoSendLink(){ $hash = hash('md5', $this->customer_id.$this->email); return $hash; } // Gera link com hash para cliente solicitar que pare de enviar e-mails public function getNoSendLink(){ //Gera link $hash = $this->getHashNoSendLink(); $customer = $this->customer_id; $link = route('emailTemplate.noSendMore', [$customer, $hash]); //Substitui o dominio pelo externo para o cliente conseguir acessar $link = str_replace(config('app.url'), config('app.public_url'), $link); return $link; } public function setMailer($optional_brand_id){ //Define nome para o mailer da marca $optional_brand = Brand::find($optional_brand_id); //Usar marca opcional if($optional_brand? $optional_brand->MAIL_HOST and $optional_brand->MAIL_PORT :false){ $mailer = 'smtp-brand-'.$optional_brand_id; $customer_brand = $optional_brand; // Usar marca do cliente }else{ $mailer = 'smtp-brand-'.$this->brand_id; $customer_brand = $this->brand; } //Caso as configurações do mailer ainda não tiver sido definidas insere elas no sistema if($customer_brand?$customer_brand->MAIL_HOST == NULL and $customer_brand->MAIL_PORT == NULL:TRUE){ $mailer = 'smtp'; config([ "mail.mailers.smtp.from.address" => config("mail.from.address"), "mail.mailers.smtp.from.name" => config("mail.from.name") ]); } elseif(!config("mail.mailers.$mailer.transport")) config([ "mail.mailers.$mailer.transport" => "smtp", "mail.mailers.$mailer.host" => $customer_brand->MAIL_HOST, "mail.mailers.$mailer.port" => $customer_brand->MAIL_PORT, "mail.mailers.$mailer.encryption" => $customer_brand->MAIL_ENCRYPTION, "mail.mailers.$mailer.username" => $customer_brand->MAIL_USERNAME, "mail.mailers.$mailer.password" => $customer_brand->MAIL_PASSWORD, "mail.mailers.$mailer.timeout" => NULL, "mail.mailers.$mailer.auth_mode" => NULL, "mail.mailers.$mailer.from.address" => $customer_brand->MAIL_FROM_ADDRESS, "mail.mailers.$mailer.from.name" => $customer_brand->MAIL_FROM_NAME, ]); return $mailer; } }Save