✏️ 正在编辑: CallcenterBase.php
路径:
/srv/systems_dir/yuppiecred-bkp/application/models/DbTable/CallcenterBase.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php class Model_DbTable_CallcenterBase extends Core_DbTable { protected $_primary = 'id'; protected $_name = 'tb_callcenter_base'; protected $_referenceMap = array( 'Campanha' => array( 'columns' => array( 'campanha_id' ), 'refTableClass' => 'Model_DbTable_CallcenterCampanha', 'refColumns' => array( 'id' ) ), 'Usuario' => array( 'columns' => array( 'usuario_ultimo_atendimento' ), 'refTableClass' => 'Model_DbTable_Usuario', 'refColumns' => array( 'id' ) ), ); public function insert(array $data) { $this->closeConnection(); $data['cpf'] = String_Refatorar::formatarCpf($data['cpf']); if( empty($data['cpf']) ){ return null; // throw new Core_Exception("CPF não pode estar vazio."); } if ( !is_null($dados = $this->fetchRow("cpf = '{$data['cpf']}'"))){ return $dados['id']; } return parent::insert($data); } public function update(array $data, $where) { $this->closeConnection(); //evitar o duplicate entry, tendo em vista que CPF é chave única if( isset($data['cpf']) ){ unset($data['cpf']); } if (in_array(Yuppie_Auth::getIdentity()->grupo, ["Callcenter", "Corretor"])) { $data['data_ultimo_atendimento'] = date('Y-m-d H:i:s'); } if (Yuppie_Auth::getIdentity()->grupo == "Callcenter") { $data['usuario_ultimo_atendimento'] = !empty($data['usuario_ultimo_atendimento']) ? $data['usuario_ultimo_atendimento'] : Yuppie_Auth::getIdentity()->id; } return parent::update($data, $where); } /** * Coloca o cliente para atendimento novamente, ou seja, limpa o status * @params $clienteId */ public function resetAtendimentoCliente($clienteId) { if( $clienteId > 0 ){ $data = array( 'data_ultimo_atendimento' => NULL, 'usuario_ultimo_atendimento' => NULL, 'status_atendimento' => NULL, 'agendado_para' => NULL, 'hora_agendada' => NULL, 'agenda_notificada' => 0, 'telefone_chamada' => NULL ); $where = "id = $clienteId"; $result = parent::update($data, $where); //grava alteracao no log if( $result > 0 ){ $log = new Model_DbTable_Log(); $log->save($this, $data, $where, $this->_primary[1]); } return $result; } return null; } /** * Altera o status do cliente e insere data e hora agendadas * @param $clienteId * @param $data * @param $hora * @param $status */ public function agendarAtendimentoCliente($clienteId, $data, $hora, $status, $usuarioUltimoAtendimento = null) { if (empty($clienteId) || empty($data) || empty($hora) || empty($status)) { return null; } if (empty($usuarioUltimoAtendimento)) { $usuarioUltimoAtendimento = Yuppie_Auth::getIdentity()->id; } $dataUpdate = [ 'agendado_para' => $data, 'hora_agendada' => $hora, 'status_atendimento' => $status, 'usuario_ultimo_atendimento' => $usuarioUltimoAtendimento, 'agenda_notificada' => 0 ]; $where = "id = $clienteId"; $result = parent::update($dataUpdate, $where); //grava alteracao no log if ($result > 0) { $log = new Model_DbTable_Log(); $log->save($this, $dataUpdate, $where, $this->_primary[1]); } return $result; } public function agendaNotificada($id){ $data = array("agenda_notificada" => 1); $where = "id = $id"; $update = parent::update($data, $where); if($update){ $log = new Model_DbTable_Log(); $log->save($this, $data, $where, $this->_primary[1]); } return $update; } /** * @deprecated */ public function getCronJob($id, $data, $hora){ //cria nova tarefa no cron para notificar o agendamento $min = date("i", strtotime($hora)); $h = date("H", strtotime($hora)); $d = date("d", strtotime($data)); $m = date("m", strtotime($data)); $y = date("Y", strtotime($data)); $a = new Zend_Controller_Request_Http(); $server = $a->getServer(); if(isset($server['HTTP_ORIGIN'])){ $uri = ltrim($server['REQUEST_URI'], '/'); $sistema = substr($uri, 0, strpos($uri, '/')); $baseUrl = $server['HTTP_ORIGIN']; $url = "$baseUrl/$sistema/public/cron/notificar-agenda/id/$id/data/$data/hora/$hora"; //tratamento para quem está num subdomínio if( $sistema == 'public' ){ $url = "$baseUrl/public/cron/notificar-agenda/id/$id/data/$data/hora/$hora"; } } else { $url = "{$server['REQUEST_SCHEME']}://{$server['HTTP_HOST']}{$server['REQUEST_URI']}"; } return "$min $h $d $m $y $url"; } public function rankingVendas() { $dtInicial = Zend_Date::now()->setDay(1)->get('dd/MM/yyyy'); $dtFinal = Zend_Date::now()->get('dd/MM/yyyy'); $fields['data_emissao_de'] = $dtInicial; $fields['data_emissao_a'] = $dtFinal; $select = $this->getAdapter()->select()->from(array( 'contratos' => 'tb_contratos' ), array( 'valor_producao' => 'SUM(base_comissao_valor)' )) ->joinInner(array( 'usuarios' => "tb_usuarios" ), 'usuarios.corretor_id = contratos.corretor_id AND usuarios.corretor_id > 0 AND usuarios.excluido <> 1', array( 'usuario' => 'usuarios.login' )) ->joinInner(array('grupos' => 'tb_grupos_usuarios'), 'grupos.id = usuarios.grupo_id', array('')) ->joinInner(array( 'corretores' => 'tb_corretores' ), 'usuarios.corretor_id = corretores.id', array( 'corretor' => 'corretores.nome' )) ->where('contratos.excluido <> 1 AND contratos.tipo_registro = 1 AND corretores.excluido <> 1') ->where("grupos.nome LIKE 'Callcenter'") ->order('valor_producao DESC') ->group("contratos.corretor_id"); $select->where("contratos.data_emissao >= STR_TO_DATE('" . $fields['data_emissao_de'] . "', '%d/%m/%Y')"); $select->where("contratos.data_emissao <= STR_TO_DATE('" . $fields['data_emissao_a'] . "', '%d/%m/%Y')"); return $this->getAdapter()->fetchAll($select); } public function getAniversariantesDoDia($count = null, $offset = null) { $data = Zend_Date::now(); $where = "MONTH(data_nascimento) = " . $data->get('MM'); // se hoje for sexta-feira, pega aniversariantes do fim de semana também if( $data->get(Zend_Date::WEEKDAY_DIGIT) == 5 ){ $where .= " AND DAY(data_nascimento) >= " . $data->get('dd'); $data->addDay(2); $where .= " AND DAY(data_nascimento) <= " . $data->get('dd'); } else { $where .= " AND DAY(data_nascimento) = " . $data->get('dd'); } $select = $this->select(); $select->from($this, array("id", "nome", "data_nascimento", "uf")); $select->where($where) ->order("nome ASC"); return $this->fetchAll($select); } public function getColsTable() { $filtros = array('nome', 'cpf', 'data_nascimento'); $data = array(); $cols = $this->info(Zend_Db_Table_Abstract::METADATA); foreach ( $filtros as $f ) { array_push($data, $cols[$f]); } return $cols; } public function localizaMargem($cpfCliente, $margemMinima) { $where = "cpf_cliente = '" . $cpfCliente . "' AND margem_livre >= '" . $margemMinima . "'"; $dbBeneficio = new Model_DbTable_CallcenterBeneficio(); if( $dbBeneficio->fetchRow($where) != null ){ return true; } return false; } /** * * @param type $fields * @param int $acao 1= ativar 2= desativar * @param int $limit quantidade para ativação * @return type */ public function ativarClientes($fields, $acao = 1, $limit = null) { $select = $this->filtrarClientes($fields, ['base.id'], 'sql'); if ($limit) { $select->limit($limit); } $select->order('base.status_atendimento'); $ids = $select->getAdapter()->fetchCol($select); if(count($ids) > 0){ $where = "id IN (" . implode(",", $ids) . ")"; return $this->update(['ativo' => $acao == 1 ? 1 : 0], $where); } } public function ativarClientesOportunidades($fields, $acao = 1, $limit = null) { $params = [ 'campanha_id' => $fields['campanha_id'], 'telefone' => $fields['telefone'], 'validar_idade_de' => $fields['validar_idade_de'], 'validar_idade_a' => $fields['validar_idade_a'], 'especies_invalidas' => $fields['especies_invalidas'], ]; $select = $this->filtrarClientes($params, ['base.id'], 'sql'); $whereOr = []; if (!empty( $fields['margem_consignado_de'])) { $margem = String_Refatorar::parseStringToFloat($fields['margem_consignado_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $whereOr[] = "(beneficios.margem_livre >= {$margem} AND " . "beneficios.cessado = 0 AND " . "beneficios.bloq_emp = 0)"; } } if (!empty( $fields['margem_cartao_de'])) { $margem = String_Refatorar::parseStringToFloat($fields['margem_cartao_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $whereOr[] = "(beneficios.margem_cartao >= {$margem} AND " . "beneficios.cessado = 0 AND " . "beneficios.bloq_emp = 0)"; } } if( !empty( $fields['valor_parcela_de'] )){ $valorParcela = String_Refatorar::parseStringToFloat($fields['valor_parcela_de']); if( $valorParcela > 0 ){ if( !array_key_exists('emprestimos', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner( array('emprestimos' => 'tb_callcenter_emprestimos_clientes'), "emprestimos.base_cliente_id = base.id", array()); } $whereOr[] = "(emprestimos.valor_parcela >= $valorParcela)"; } } if (count($whereOr) > 1) { $select->where(implode(" OR ", $whereOr)); } else { $select->where(current($whereOr)); } if ($limit) { $select->limit($limit); } $select->order('base.status_atendimento'); $ids = $select->getAdapter()->fetchCol($select); if(count($ids) > 0){ $where = "id IN (" . implode(",", $ids) . ")"; return $this->update(['ativo' => $acao == 1 ? 1 : 0], $where); } } public function filtrarClientes($fields, $columns = array('cpf'), $return = "stm") { if( empty($fields['campanha_id']) ){ throw new Core_Exception('É necessário informar o id da campanha'); } $select = $this->getAdapter()->select()->from(array('base' => $this->_name), $columns) ->joinLeft('tb_tipos', "tb_tipos.descricao = base.status_atendimento and desativar_cliente_callcenter <> 1", array()) ->where("base.obito = 0 OR base.obito IS NULL"); if( !empty($fields['campanha_id']) ){ if( is_array($fields['campanha_id']) ){ $fields['campanha_id'] = array_filter($fields['campanha_id']); $select->where("base.campanha_id IN ('" . implode("', '", $fields['campanha_id']) . "')"); }else{ $select->where("base.campanha_id = {$fields['campanha_id']}"); } } if(!empty($fields['cartao']) || !empty($fields['banco_emp'])){ $select->joinInner( array('emprestimos' => 'tb_callcenter_emprestimos_clientes'), "emprestimos.base_cliente_id = base.id", array()); if(isset($fields['banco_emp']) && $fields['banco_emp'] > 0){ $select->where("emprestimos.banco IN (?)", $fields['banco_emp']); } } if(!empty($fields['data_higienizacao_de']) && empty($fields['data_higienizacao_a']) || empty($fields['data_higienizacao_de']) && !empty($fields['data_higienizacao_a']) ){ throw new Core_Exception('Ao filtrar por data, os dois campos devem estar preenchidos.'); }elseif( !empty($fields['data_higienizacao_de']) && !empty($fields['data_higienizacao_a'])){ $dataDe = new Zend_Date($fields['data_higienizacao_de']); $dataA = new Zend_Date($fields['data_higienizacao_a']); $dataA->subDay(60); if ($dataDe->isEarlier($dataA)) { throw new Core_Exception('O filtro de datas deve estar entre um periodo de 60 dias.'); } $select->where("base.data_higienizacao >= STR_TO_DATE(?, '%d/%m/%Y')", $fields['data_higienizacao_de']); $select->where("base.data_higienizacao <= STR_TO_DATE(?, '%d/%m/%Y')", $fields['data_higienizacao_a']); } if(!empty( $fields['margem'])){ $fields['margem_consignado_de'] = $fields['margem']; } if(!empty( $fields['margem_consignado_de'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_consignado_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_livre >= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if(!empty( $fields['margem_consignado_a'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_consignado_a']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_livre <= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if(!empty($fields['margem_cartao'])){ $fields['margem_cartao_de'] = $fields['margem_cartao']; } if(!empty( $fields['margem_cartao_de'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_cartao_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_cartao >= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if(!empty( $fields['margem_cartao_a'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_cartao_a']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_cartao <= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if(!empty($fields['saque_complementar'])){ $fields['saque_compelmentar_de'] = $fields['saque_complementar']; } if(!empty( $fields['saque_complementar_de'])){ $margem = String_Refatorar::parseStringToFloat($fields['saque_complementar_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.saque_complementar >= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if(!empty( $fields['saque_complementar_a'])){ $margem = String_Refatorar::parseStringToFloat($fields['saque_complementar_a']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.saque_complementar <= {$margem}") ->where("beneficios.cessado = 0") ->where("beneficios.bloq_emp = 0"); } } if( !empty($fields['parcelas_pagas']) ){ if( !array_key_exists('emprestimos', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner( array('emprestimos' => 'tb_callcenter_emprestimos_clientes'), "emprestimos.base_cliente_id = base.id", array()); } $select->where("emprestimos.parcelas_pagas >= {$fields['parcelas_pagas']}"); } if( !empty( $fields['valor_parcela'] )){ $fields['valor_parcela_de'] = $fields['valor_parcela']; } if( !empty( $fields['valor_parcela_de'] )){ $valorParcela = String_Refatorar::parseStringToFloat($fields['valor_parcela_de']); if( $valorParcela > 0 ){ if( !array_key_exists('emprestimos', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner( array('emprestimos' => 'tb_callcenter_emprestimos_clientes'), "emprestimos.base_cliente_id = base.id", array()); } $select->where("emprestimos.valor_parcela >= $valorParcela"); } } if( !empty( $fields['valor_parcela_a'] )){ $valorParcela = String_Refatorar::parseStringToFloat($fields['valor_parcela_a']); if( $valorParcela > 0 ){ if( !array_key_exists('emprestimos', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner( array('emprestimos' => 'tb_callcenter_emprestimos_clientes'), "emprestimos.base_cliente_id = base.id", array()); } $select->where("emprestimos.valor_parcela <= $valorParcela"); } } if(!empty($fields['validar_idade_de'])){ $select->where("DATE_FORMAT(FROM_DAYS(DATEDIFF(now(), base.data_nascimento)), '%y') >= ?", $fields['validar_idade_de']); } if(!empty($fields['validar_idade_a'])){ $select->where("DATE_FORMAT(FROM_DAYS(DATEDIFF(now(), base.data_nascimento)), '%y') <= ?", $fields['validar_idade_a']); } if(!empty($fields['higienizados'])){ if($fields['higienizados'] == 1){ $select->where("data_higienizacao IS NOT NULL"); } if($fields['higienizados'] == -1){ $select->where("data_higienizacao IS NULL"); } } if(isset($fields['telefone'])){ $select->joinLeft( ['telefones' => 'tb_callcenter_telefones'], "telefones.cliente_id = base.id AND telefones.excluido <> 1", []); if($fields['telefone'] == 1){ $select->where("telefones.id is not null"); } if($fields['telefone'] == -1){ $select->where("telefones.id is null"); } } $fields['data_final'] = $fields['data_final'] ?? $fields['data_final_atendimento'] ?? null; if( isset($fields['data_final']) && $fields['data_final'] ){ $dtFinal = new Zend_Date($fields['data_final'], 'dd/MM/yyyy'); if( !array_key_exists('atendimentos', $select->getPart(Zend_Db_Select::FROM)) ){ $maxAtendimento = $this->getAdapter()->select()->from(array('tb_callcenter_atendimentos'), array('ultimo_atendimento' => 'max(data_atendimento)', 'cliente_id')) ->group('cliente_id'); $select->joinLeft(array('atendimentos' => $maxAtendimento), 'atendimentos.cliente_id = base.id'); } $select->where("(atendimentos.ultimo_atendimento <= '" . $dtFinal->get('yyyy-MM-dd') . "')"); } if( !empty($fields['orgao']) ){ $select->where("base.orgao LIKE '%" . $fields['orgao'] . "%'"); } if( !empty($fields['especie']) ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(['beneficios' => 'tb_callcenter_beneficios'],'base.cpf = beneficios.cpf_cliente', ['especie']); } $select->where("beneficios.especie IN (?)", $fields['especie']); } if( !empty($fields['especies_invalidas']) ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(['beneficios' => 'tb_callcenter_beneficios'],'base.cpf = beneficios.cpf_cliente', ['especie']); } $select->where("beneficios.especie NOT IN (?)", $fields['especies_invalidas']); } if( !empty($fields['uf']) ){ $select->where("(base.uf = '{$fields['uf']}')"); } if( !empty($fields['cidade']) ){ $select->where("(base.cidade = '{$fields['cidade']}')"); } if( !empty($fields['bairro']) ){ $select->where("(base.bairro = '{$fields['bairro']}')"); } if( !empty($fields['usuario_ultimo_atendimento']) ){ $select->where("(base.usuario_ultimo_atendimento = '{$fields['usuario_ultimo_atendimento']}')"); } //status diferente de if( isset($fields['status_diferente_de']) && array_filter($fields['status_diferente_de'])){ $fields['status_diferente_de'][]= 'EM ATENDIMENTO'; if( in_array("SEM_STATUS", $fields['status_diferente_de']) ){ $select->where("(status_atendimento IS NOT NULL)"); $select->where("(status_atendimento NOT IN ('" . implode("', '", $fields['status_diferente_de']) . "'))"); }else{ $select->where("(status_atendimento NOT IN ('" . implode("', '", $fields['status_diferente_de']) . "')" . " OR status_atendimento IS NULL)"); } } if (isset($fields['status_atendimento']) && $fields['status_atendimento']) { $select->where('(base.status_atendimento IN (?) OR base.status_atendimento is null)', $fields['status_atendimento']); } if( array_key_exists('opcao_ura_reversa', $fields) && $fields['opcao_ura_reversa'] != '#' ){ if( !array_key_exists('telefones', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(['telefones' => 'tb_callcenter_telefones'],'base.id = telefones.cliente_id AND telefones.excluido<>1', []); } $select->where("telefones.opcao_ura_reversa = ?", $fields['opcao_ura_reversa']); } if(!empty( $fields['margem_bens_duraveis'])){ $fields['margem_bens_duraveis_de'] = $fields['margem_bens_duraveis']; } if(!empty($fields['margem_bens_duraveis_de'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_bens_duraveis_de']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_bens_duraveis >= {$margem}"); } } if(!empty( $fields['margem_bens_duraveis_a'])){ $margem = String_Refatorar::parseStringToFloat($fields['margem_bens_duraveis_a']); if( $margem > 0 ){ if( !array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('beneficios' => 'tb_callcenter_beneficios'), 'base.cpf = beneficios.cpf_cliente', array()); } $select->where("beneficios.margem_bens_duraveis <= {$margem}"); } } if( !empty($fields['ativo']) ){ if( $fields['ativo'] == 1 ){ $select->where("base.ativo = 1"); }else{ $select->where("base.ativo = 0"); } } $select = $this->addWhereDate($select, 'data_ultima_higienizacao', $fields); $select = $this->addWhereDate($select, 'data_higienizacao_telefones', $fields); if (!empty($fields['salario_de'])) { $salario = String_Refatorar::parseStringToFloat($fields['salario_de']); $this->getJoinBeneficios($select); $select->where("beneficios.mr >= {$salario}"); } if (!empty($fields['salario_a'])) { $salario = String_Refatorar::parseStringToFloat($fields['salario_a']); $this->getJoinBeneficios($select); $select->where("beneficios.mr <= {$salario}"); } if (!empty($fields['emprestimos_de']) || !empty($fields['emprestimos_a'])) { $subquery = (new Model_DbTable_CallcenterEmprestimoCliente())->sqlQuantidadeEmprestimos(); $select->join(['emprestimos' => $subquery], "emprestimos.cpf = base.cpf", ['emprestimos.quantidade_emprestimos']); } if (!empty($fields['emprestimos_de'])) { $select->where("emprestimos.quantidade_emprestimos >= {$fields['emprestimos_de']}"); } if (!empty($fields['emprestimos_a'])) { $select->where("emprestimos.quantidade_emprestimos <= {$fields['emprestimos_a']}"); } if (!empty($fields['fgts_ativo'])) { if( !array_key_exists('fgts', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinLeft(['fgts' => 'tb_callcenter_fgts'], 'base.id = fgts.base_id', []); } if ($fields['fgts_ativo'] == 1) { $select->where("fgts.id IS NOT NULL AND fgts.valor > 0"); } else { $select->where("fgts.id IS NULL OR fgts.valor = 0"); } } if (!empty($fields['status_fgts'])) { if( !array_key_exists('fgts', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinLeft(['fgts' => 'tb_callcenter_fgts'], 'base.id = fgts.base_id', []); } $select->where("fgts.descricao_erro = ?", $fields['status_fgts']); } if (!empty( $fields['fgts_de'])) { $saldoFgts = String_Refatorar::parseStringToFloat($fields['fgts_de']); if ($saldoFgts > 0) { if( !array_key_exists('fgts', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('fgts' => 'tb_callcenter_fgts'), 'base.id = fgts.base_id', []); } $select->having("sum(fgts.valor) > '{$saldoFgts}'"); } } if(!empty( $fields['fgts_a'])){ $saldoFgts = String_Refatorar::parseStringToFloat($fields['fgts_a']); if ($saldoFgts > 0) { if( !array_key_exists('fgts', $select->getPart(Zend_Db_Select::FROM)) ){ $select->joinInner(array('fgts' => 'tb_callcenter_fgts'), 'base.id = fgts.base_id', []); } $select->having("sum(fgts.valor) <= '{$saldoFgts}'"); } } $select->group("base.cpf"); if( $return == "stm" ){ return $this->getAdapter()->query($select); } return $select; } public function getClientesAtendimento($where) { $select = $this->select()->setIntegrityCheck(false) ->from(array("base" => $this->_name), array('base.*')) ->joinLeft(array("atendimentos" => "tb_callcenter_atendimentos"), "(base.id = atendimentos.cliente_id AND atendimentos.id > 0)", array('data_ultimo_historico' => 'MAX(data_atendimento)')) ->group("base.id") ->limit(30); if( is_array($where) ){ foreach ( $where as $cond => $value ) { if( is_numeric($cond) ){ $select->where($value); } else { $select->where($cond, $value); } } }else{ $select->where($where); } $select->order("data_ultimo_historico ASC"); return $this->getAdapter()->fetchAll($select); } public function selectCallcenterBaseTelefones(int $campanhaId, int $limit = 50000) : Zend_Db_Select { $select = $this->getAdapter()->select() ->from(['base' => $this->_name], '') ->join(['telefones' => 'tb_callcenter_telefones'], 'base.id = telefones.cliente_id', '') ->where('base.campanha_id = ?', $campanhaId) ->where('telefones.excluido = 0') ->where('base.ativo = 1'); if ($limit) { $select = $select->limit($limit); } return $select; } public function selectAndamentoCampanhaDiscador(int $campanhaId) : Array { $table = $this->selectCallcenterBaseTelefones($campanhaId) ->columns([ 'clientes_atendidos' => 'SUM(if(discador_status is not null, 1, 0))', 'clientes_total' => 'COUNT(telefones.id)' ]); return $this->getAdapter()->fetchRow($table); } public function selectTelefonesNaoEnviadosDiscador(int $campanhaId) : Array { $select = $this->selectCallcenterBaseTelefones($campanhaId) ->where('telefones.discador_status is null') ->where('telefones.excluido = 0') ->where('telefones.nao_perturbe = 0') ->where('telefones.discador_descartar = 0') ->where('base.ativo = 1') ->where("base.status_atendimento IS NULL OR base.status_atendimento = ''") ->order(['telefones.cliente_id', 'telefones.id']) ->columns([ 'telefone_id' => 'telefones.id', 'contato_id' => 'telefones.cliente_id', 'numero' => 'telefones.fone' ]); return $this->getAdapter()->fetchAll($select); } public function selectNumerosEnviados(int $campanhaId, int $ultimoId = 0, int $limit = 50) { $select = $this->selectCallcenterBaseTelefones($campanhaId, $limit) ->where('telefones.discador_status is not null') ->columns([ 'cliente_id' => 'base.id', 'cliente_cpf' => 'base.cpf', 'cliente' => 'base.nome', 'numero' => 'telefones.fone', 'discador_status' => 'telefones.discador_status', 'telefone_id' => 'telefones.id', ]) ->order('telefones.id ASC'); if ($ultimoId > 0) { $select->where('telefones.id > ?', $ultimoId); } if ($limit) { $select->limit($limit); } return $this->getAdapter()->fetchAll($select); } public function selectTelefonesParaConsultarDiscador(int $campanhaId, int $limit = 1000) : Array { $select = $this->getAdapter()->select() ->from(['base' => $this->_name], [ 'chamada_id' => 'telefone.discador_chamada_id', 'telefone_id' => 'telefone.id' ]) ->join(['telefone' => 'tb_callcenter_telefones'], 'base.id = telefone.cliente_id', '') ->where('base.campanha_id = ?', $campanhaId) ->where('telefone.excluido = 0') ->where('telefone.discador_status is not null') ->where('telefone.discador_status not in ("desligada", "indisponivel")') ->limit($limit); return $this->getAdapter()->fetchAll($select); } public function selectUsuarioPorId($baseId) { $select = $this->select() ->from($this->_name, '*') ->where("$this->_name.id = ?", $baseId); return $this->getAdapter()->fetchRow($select)['nome']; } public function selectAtendimentosParaResetar($parametros) { $select = $this->select() ->from(['b' => $this->_name], 'b.id') ->group('b.id'); if (isset($parametros['campanha_id']) && $parametros['campanha_id']) { $select->where('b.campanha_id IN (?)', $parametros['campanha_id']); } if (isset($parametros['status_atendimento']) && $parametros['status_atendimento']) { $select->where('(b.status_atendimento IN (?) OR b.status_atendimento is null)', $parametros['status_atendimento']); } if (isset($parametros['uf']) && $parametros['uf']) { $select->where('b.uf = ?', $parametros['uf']); } if (isset($parametros['cidade']) && $parametros['cidade']) { $select->where('b.cidade = ?', $parametros['cidade']); } if (isset($parametros['data_final']) && $parametros['data_final']) { $dtFinal = new Zend_Date($parametros['data_final'], 'dd/MM/yyyy'); $select->where('b.data_ultimo_atendimento < ?', $dtFinal->get('yyyy-MM-dd')); } if (isset($parametros['usuario_carteirizacao']) && $parametros['usuario_carteirizacao'] > 0) { $select->where('b.usuario_carteirizacao = ?', $parametros['usuario_carteirizacao']); } if(!empty($parametros['data_higienizacao_de']) && empty($parametros['data_higienizacao_a']) || empty($parametros['data_higienizacao_de']) && !empty($parametros['data_higienizacao_a']) ){ throw new Core_Exception('Ao filtrar por data, os dois campos devem estar preenchidos.'); }elseif( !empty($parametros['data_higienizacao_de']) && !empty($parametros['data_higienizacao_a'])){ $dataDe = new Zend_Date($parametros['data_higienizacao_de']); $dataA = new Zend_Date($parametros['data_higienizacao_a']); $dataA->subDay(60); if ($dataDe->isEarlier($dataA)) { throw new Core_Exception('O filtro de datas deve estar entre um periodo de 60 dias.'); } $select->where("b.data_higienizacao >= STR_TO_DATE(?, '%d/%m/%Y')", $parametros['data_higienizacao_de']); $select->where("b.data_higienizacao <= STR_TO_DATE(?, '%d/%m/%Y')", $parametros['data_higienizacao_a']); } if( array_key_exists('opcao_ura_reversa', $parametros) && $parametros['opcao_ura_reversa'] != '#' ){ $select->joinInner(['t' => 'tb_callcenter_telefones'],'b.id = t.cliente_id', []); $select->where("t.opcao_ura_reversa = ?", $parametros['opcao_ura_reversa']); } $clientes = $this->getAdapter()->fetchCol($select, 'id'); if (count($clientes) > 0) { return implode($clientes, ','); } return null; } public function findPhonesToInsert($clientId) { if( empty($clientId) ){ return []; } $phones = (new Model_DbTable_CallcenterTelefone())->fetchAll([ "cliente_id = ?" => $clientId, "discador_descartar <> 1" ]); if( empty($phones) ){ return []; } $phoneToInsert = []; $phoneToInsert['celular'] = $phones[0]['fone'] ?? null; $phoneToInsert['fone'] = $phones[1]['fone'] ?? null; $phoneToInsert['telefone_comercial'] = $phones[2]['fone'] ?? null; $phoneToInsert['fax'] = $phones[3]['fone'] ?? null; return $phoneToInsert; } /** * @param Zend_Db_Select $select * @param string $name * @param array $fields * @return Zend_Db_Select * @throws Zend_Date_Exception */ private function addWhereDate(Zend_Db_Select $select, string $name, array $fields): Zend_Db_Select { if (!empty($fields[$name])) { $select->where( 'base.' . $name . ' <= ? OR ' . $name . ' IS NULL', (new Zend_Date($fields[$name]))->get('YYYY-MM-dd') ); } return $select; } /** * @param int $campanha * @param bool $atendidos * @return Zend_Db_Select */ public function sqlCountBase(int $campanha, bool $atendidos = false): Zend_Db_Select { $alias = $atendidos ? 'clientes_atendidos' : 'clientes'; $sql = $this->getAdapter() ->select() ->from(['cb' => $this->_name], [ "count(DISTINCT id) as $alias", 'campanha_id', ]) ->where('cb.ativo = ?', 1) ->where('cb.campanha_id = ?', $campanha); if ($atendidos) { $sql->where('(cb.status_atendimento IS NOT NULL OR cb.telefone_chamada IS NOT NULL)'); } return $sql->group('cb.campanha_id'); } /** * @param Zend_Db_Select $select * @throws Zend_Db_Select_Exception */ public function getJoinBeneficios(Zend_Db_Select $select): void { if (!array_key_exists('beneficios', $select->getPart(Zend_Db_Select::FROM))) { $select->joinInner(['beneficios' => 'tb_callcenter_beneficios'], 'base.cpf = beneficios.cpf_cliente', []); } } /** * @param int $campanhaId * @return array * @throws Zend_Db_Select_Exception */ public function getBaseBeneficios(int $campanhaId) { $select = $this->getAdapter()->select() ->from(['base' => $this->_name], ['cpf_cliente' => 'cpf']) ->columns(['beneficios.beneficio as matricula']) ->where('campanha_id = ?', $campanhaId) ->where('ativo = 0'); $this->getJoinBeneficios($select); return $this->getAdapter()->fetchAll($select); } public function findAgendamentos(bool $desconsiderarNotificados = false, int $intervalo = 30) { $select = $this->getAdapter()->select() ->from(['b' => 'tb_callcenter_base'], [ 'id', 'nome', 'cpf', 'agendado_para', 'hora_agendada', 'usuario_ultimo_atendimento' ]); $select->where("agendado_para = ?", date('Y-m-d')) ->where("hora_agendada <= ?", Zend_Date::now()->addMinute($intervalo)->get('HH:mm')) ->where("hora_agendada > ?", Zend_Date::now()->get('HH:mm')) ->where("usuario_ultimo_atendimento = ?", (int)Yuppie_Auth::getIdentity()->id) ->where("ativo = ?", 1); if (!$desconsiderarNotificados) { $select->where("agenda_notificada = ?", 0); } $select->order("hora_agendada"); return $this->getAdapter()->fetchAll($select); } public function getLeads($fields) { $dataInicial = new Zend_Date($fields['data_simulacao_de']); $dataFinal = new Zend_Date($fields['data_simulacao_a']); $select = $this->getAdapter()->select() ->from(['b' => 'tb_callcenter_base'], []) ->joinInner(['s' => 'tb_simulacao_aberta'], 'b.id = s.cliente_id and s.excluido <> 1', []) ->joinLeft(['fgts' => 'tb_callcenter_fgts'], 'b.id = fgts.base_id', []) ->joinLeft(['c' => 'tb_clientes'], 'b.cpf = c.cpf and c.excluido <> 1', []) ->joinLeft(['con' => 'tb_contratos'], 'c.id = con.cliente_id and con.excluido <> 1 and con.tipo_registro = 1', []) ->where("s.data_simulacao >= ?" , $dataInicial->get('yyyy-MM-dd') . ' 00:00:00') ->where("s.data_simulacao <= ?" , $dataFinal->get('yyyy-MM-dd') . ' 23:59:59') ; return $select; } public function leadsPeriodo($fields) { $leads = $this->getLeads($fields); $leads->group("DATE_FORMAT(b.data_cadastro, '%Y-%m-%d')") ->order('b.data_cadastro desc') ->columns(['DATA' => "DATE_FORMAT(b.data_cadastro, '%d/%m/%Y')", 'QTD' => 'count(distinct b.id)']) ; return $this->getAdapter()->fetchAll($leads); } public function leadsXuf($fields) { $leads = $this->getLeads($fields); $leads->where('c.uf is not null')->group('c.uf') ->order('QTD desc') ->columns(['UF' => 'c.uf', 'QTD' => 'count(distinct b.id)']) ; return $this->getAdapter()->fetchAll($leads); } public function leadsXsexo($fields) { $leads = $this->getLeads($fields); $leads->where('c.sexo is not null')->group('c.sexo') ->columns(['SEXO' => 'c.sexo', 'QTD' => 'count(distinct b.id)']); return $this->getAdapter()->fetchAll($leads); } public function leadsFaixaEtaria($fields) { $selectTemp = $this->getLeads($fields); $leads = $selectTemp->where('c.data_nascimento is not null')->order('idade asc') ->columns(['idade' => 'TIMESTAMPDIFF(YEAR, c.data_nascimento, NOW())']); return $this->getAdapter()->fetchAll($leads); } public function leadsFaixaRenda($fields) { $selectTemp = $this->getLeads($fields); $leads = $selectTemp->group('b.id')->columns(['c.renda']); return $this->getAdapter()->fetchAll($leads); } public function leadsTicketMedioSaldo($fields) { $selectTemp = $this->getLeads($fields); $leads = $selectTemp->where('fgts.valor > 0')->columns([ 'valor_medio'=> 'AVG(distinct fgts.valor)', 'qtd' => 'count(distinct b.id)', ]); return $this->getAdapter()->fetchRow($leads); } public function leadsTicketMedioContrato($fields) { $selectTemp = $this->getLeads($fields); $leads = $selectTemp->where('con.id > 0')->columns([ 'valor_medio'=> 'AVG(distinct con.valor_liquido)', 'qtd' => 'count(distinct con.id)', ]) ; return $this->getAdapter()->fetchRow($leads); } public function getLeadsFunil($fields, $etapa = null) { $select = $this->getLeads($fields); $select->columns(['qtd' => 'count(distinct b.id)']); if ($etapa == 2) { $select->where("(fgts.descricao_erro is null or fgts.descricao_erro like '%não possui saldo%' " . "or fgts.descricao_erro like '%precisa aderir a modalidade%' " . "or fgts.descricao_erro like '%libere o banco%' " . "or fgts.descricao_erro like '%cadastrais na conta%') AND fgts.id > 0"); } if ($etapa == 3) { $select->where('fgts.valor > 0 AND fgts.id > 0'); } if ($etapa == 4) { $select->columns(['qtd' => 'count(distinct con.id)']) ->where('con.id > 0'); } return $this->getAdapter()->fetchRow($select); } public function leadsOrigem($fields) { $selectTemp = $this->getLeads($fields); $leads = $selectTemp->joinLeft(['cor' => 'tb_corretores'], 'cor.id = s.corretor_id', []) ->order('qtd desc')->group('origem') ->columns([ 'origem' => 'if (cor.id > 0 , cor.nome, if (s.utm_campaign is null or s.utm_campaign = "" or s.utm_campaign = "null", "Sem origem", s.utm_campaign) )', 'qtd' => 'count(distinct b.id)', 'qtd_convertidos' => 'count(distinct con.id)', 'qtd_pagos' => 'sum(IF(con.status_proposta = 43, 1, 0))', 'soma_pagos' => 'sum(IF(con.status_proposta = 43, (con.comissao_empresa*con.base_comissao_empresa_valor/100), 0))', 'acesso' => 'cor.grupo_acesso' ]); return $this->getAdapter()->fetchAll($leads); } public function leadsReferencia($fields) { $dataInicial = new Zend_Date($fields['data_simulacao_de']); $dataFinal = new Zend_Date($fields['data_simulacao_a']); $simulacoes = $this->getAdapter()->select()->from(['simulacoes' => 'tb_simulacao_aberta'],['cliente_id', 'http_referer' => 'max(http_referer)']) ->where("simulacoes.data_simulacao >= ?" , $dataInicial->get('yyyy-MM-dd') . ' 00:00:00') ->where("simulacoes.data_simulacao <= ?" , $dataFinal->get('yyyy-MM-dd') . ' 23:59:59') ->where('excluido <> 1') ->group('cliente_id'); $select = $this->getAdapter()->select() ->from(['b' => 'tb_callcenter_base'], []) ->joinInner(['s' => $simulacoes], 'b.id = s.cliente_id', []) ->order('qtd desc')->group('referencia') ->columns([ 'referencia' => 's.http_referer', 'qtd' => 'count(distinct b.id)' ]); return $this->getAdapter()->fetchAll($select); } public function limparTelefonesAgendadosLeads() { $select = $this->getAdapter()->select() ->from(['b' => $this->_name], []) ->joinInner(['t' => 'tb_callcenter_telefones'], 'b.id = t.cliente_id', ['t.fone']) ->where("b.data_ultimo_atendimento >= ?", date('Y-m-d')) ->group('t.fone'); $fones = $this->getAdapter()->fetchCol($select); if (empty($fones)) { return; } $fones = implode("', '", $fones); $notificacoes = new Model_DbTable_NotificacaoAgendamento(); return $notificacoes->delete("celular in('{$fones}') and data_envio is null"); } }
💾 保存文件
← 返回文件管理器