✏️ 正在编辑: ServiceController.php
路径:
/srv/systems_dir/yuppiecred/application/controllers/ServiceController.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php use Modules\Core\Exception\CPFJaCadastradoException; use Yuppie_Core_SecretSiteKey as Secret; /** * @sem_permissao */ class ServiceController extends Zend_Controller_Action { private $_log = null; public const ERRO = 'Ocorreu um erro durante a solicitação.'; public const ACTION_EXCEPTION_AUTHENTICATE = [ 'sinc-yuppies', 'sinc-yuppies-comissionamento', 'webhook-higienizacao-cpf', 'proposta' ]; public function init() { if (!in_array($this->getRequest()->getActionName(), self::ACTION_EXCEPTION_AUTHENTICATE)) { try { $enable = service('config')->get()->yuppie->api ?: null; Secret::validHash(getallheaders(), $enable); } catch (Throwable $throwable) { Yuppie_Log::write(self::ERRO . ": " . print_r(getallheaders(), true) . "\n" . $throwable->getMessage() . "\n" . $throwable->getTraceAsString(), $this); $this->_helper->json([ 'error' => self::ERRO, 'description' => "Não há autorização para o acesso" ]); } } $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout->disableLayout(); /* Apenas para LOG */ $urlSistema = Yuppie_Auth::getSiteKey(); $writer = new Zend_Log_Writer_Stream("/var/log/sistemayuppie/zf_log_{$urlSistema}_mobile_" . Zend_Date::now()->get("ddMMyyyy") . ".txt"); $this->_log = new Zend_Log($writer); $this->_log->log('#######################', Zend_Log::INFO); if( $this->getRequest()->getActionName() == "sinc-yuppies" ){ $this->_log->log('WEBSERVICE SINCRONIZACAO YUPPIES', Zend_Log::INFO); } else { $this->_log->log('WEBSERVICE APLICATIVO', Zend_Log::INFO); } $this->_log->log('$_SERVER', Zend_Log::INFO); $this->_log->log(print_r($_SERVER, true), Zend_Log::INFO); $this->_log->log('Action:' . $this->getRequest()->getActionName(), Zend_Log::INFO); $url = "http://" . $_SERVER['SERVER_NAME'] . $this->getRequest()->getBaseUrl(); $this->_helper->layout->setLayout('layout_basico'); $this->_helper->viewRenderer->setNoRender(); $this->_helper->getHelper('layout')->disableLayout(); $this->_wsdl = $url . "/service/wsdl?wsdl"; if( isset($_SERVER['HTTP_ORIGIN']) ){ header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ){ if( isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) ) header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if( isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']) ) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); } //actions liberadas $actions = ['proposta', 'combos', 'sinc-yuppies', 'sinc-yuppies-comissionamento', 'webhook-higienizacao-cpf']; if( !in_array($this->getRequest()->getActionName(), $actions) ){ $config = new Zend_Config_Ini(CLIENT_PATH . '/configs/application.ini', APPLICATION_ENV); $dados = $config->yuppie; if( $dados ){ $permissionAPP = $dados->toArray(); if( $permissionAPP['webservice'] == false ){ $this->_helper->json(array( 'status' => 'fail', 'result' => 'Aplicativo não liberado.' )); } } } } public function indexAction() { if( isset($_GET['wsdl']) ){ //return the WSDL $this->hadleWSDL(); } else { //handle SOAP request $this->handleSOAP(); } } /** * Esse método deve existir pois nos testes com o C# ele sempre aponta para o endereco /index/wsdl o que * causa um erro. Mesmo sendo informado no visual studio a referencia para /index?wsdl * */ public function wsdlAction() { if( isset($_GET['wsdl']) ){ //return the WSDL $this->hadleWSDL(); } else { //handle SOAP request $this->handleSOAP(); } } private function hadleWSDL() { $autodiscover = new Zend_Soap_AutoDiscover(); $autodiscover->setClass('Service_ServerSoap'); $autodiscover->handle(); } private function handleSOAP() { $soap = new Zend_Soap_Server($this->_wsdl); $soap->setClass('Service_ServerSoap'); $soap->handle(); } public function propostaAction() { if( $this->_request->isPost() ){ $dados = $this->_request->getPost(); $url = $this->_request->getPost('retorno'); if( !$url ){ die(utf8_decode('ERRO! Url de retorno não definida!')); } try { if( $_FILES['file_cpf']['name'] == '' && $_FILES['file_rg']['name'] == '' && $_FILES['file_contra_cheque']['name'] == '' && $_FILES['file_ficha_cadastral']['name'] == '' && $_FILES['file_beneficio']['name'] == '' ){ $url .= '?erro=4'; // Nenhum anexo foi enviado $this->getHelper('Redirector')->gotoUrlAndExit($url); } if( !$dados['login'] || !$dados['senha'] ){ $url .= '?erro=1'; // Login e senha obrigatórios $this->getHelper('Redirector')->gotoUrlAndExit($url); } $modelCorretor = new Model_Corretor(); if( !$modelCorretor->autenticar($dados['login'], $dados['senha']) ){ $url .= '?erro=2'; // Login ou senha incorretos $this->getHelper('Redirector')->gotoUrlAndExit($url); } /* TO DO * tratar consulta para evitar SQL Injections */ $tbCorretor = new Model_DbTable_Corretor(); $corretor = $tbCorretor->fetchRow( "login = '{$dados['login']}' " . "AND senha = '" . md5($dados['senha']) . "' " . "AND excluido = 0" ); $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination(UPLOAD_PATH); $files = array(); foreach ( $upload->getFileInfo() as $file => $info ) { $fname = substr(md5(microtime()), 1, 4) . $info['name']; $upload->addFilter(new Zend_Filter_File_Rename(array( 'target' => UPLOAD_PATH . '/' . $fname, 'overwrite' => false ))); if( $upload->receive($file) ){ $files[$file] = $fname; } } $dados['corretor_id'] = $corretor->id; $dados['empresa_id'] = $corretor->empresa_id; // Banco $modelBanco = new Model_Banco(); $dados['banco_id'] = $modelBanco->bancoPorNome($dados['banco']); unset($dados['banco']); if( !$dados['banco_id'] ){ $url .= '?erro=5'; // Banco para liberação inválido $this->getHelper('Redirector')->gotoUrlAndExit($url); } // Convênio $tbConvenio = new Model_DbTable_Convenio(); /* TO DO * tratar consulta para evitar SQL Injections */ $convenio = $tbConvenio->fetchRow( "nome = '{$dados['convenio']}'"); $dados['convenio_id'] = $convenio->id; unset($dados['convenio']); if( !$dados['convenio_id'] ){ $url .= '?erro=6'; // Convênio inválido $this->getHelper('Redirector')->gotoUrlAndExit($url); } // Banco Beneficiado $tbBancoFebraban = new Model_DbTable_BancoFebraban(); $bancoBeneficiado = $tbBancoFebraban->findByCodigo($dados['banco_beneficiado']); $dados['banco_beneficiado'] = $bancoBeneficiado->codigo; if( !$dados['banco_beneficiado'] ){ $url .= '?erro=7'; // Banco do beneficiado inválido $this->getHelper('Redirector')->gotoUrlAndExit($url); } $proposta = new Model_Proposta($dados); if( count($files) > 0 ){ if( isset($files['file_cpf']) ){ $proposta->setAnexoCpf($files['file_cpf']); } if( isset($files['file_rg']) ){ $proposta->setAnexoRg($files['file_rg']); } if( isset($files['file_contra_cheque']) ){ $proposta->setAnexoContraCheque($files['file_contra_cheque']); } if( isset($files['file_ficha_cadastral']) ){ $proposta->setAnexoFichaCadastral($files['file_ficha_cadastral']); } if( isset($files['file_beneficio']) ){ $proposta->setAnexoBeneficio($files['file_beneficio']); } } $cliente = new Model_Cliente($dados); $result = $proposta->salvar($proposta, $cliente); if( !$result ){ $url .= '?erro=3'; // Erro ao tentar salvar proposta } else { $url .= '?success=1'; // Proposta cadastrada com sucesso } } catch ( Zend_Exception $e ) { $url .= '?erro=8'; // Erro desconhecido echo $e->getMessage(); die($e->getTraceAsString()); } $this->getHelper('Redirector')->gotoUrlAndExit($url); } } public function fisicosPendentesAction() { $request = $this->getRequest(); $login = $request->getParam('l'); $senha = $request->getParam('p'); $service = new Service_ServerSoap(); return $service->getFisicosPendentes($login, $senha); } public function echoWsdlAction() { die($this->_wsdl); } public function loginCorretorAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $cpf = $data['cpf']; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($cpf)) { $this->_helper->json(['error' => 'CPF não informado.']); } $corretor = (new Model_Corretor())->getByCpf($cpf, false); if (!$corretor) { $this->_helper->json(['status' => '0', 'msg' => 'Cadastro não localizado.']); } if (!$corretor->permitir_sinc_yuppies) { $this->_helper->json(['status' => '0', 'msg' => 'Seu acesso não está liberado.']); } $this->_helper->json(['status' => 1, "token" => $corretor->token_sinc_yuppies]); } public function meusProtocolosAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $data['token']; $dataPagamento = $data['data_pagamento'] ?: null; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['Token não identificado.']); } try { $service = new Service_ServerSoap(); $response = $service->getProtocolosCorretor($token, $dataPagamento); } catch (Exception $e) { $this->_helper->json(["status" => 0, "msg" => $e->getMessage()]); } if ($response) { $this->_helper->json(["status" => 1, "result" => $response]); } $this->_helper->json(["status" => 0, "msg" => "Nenhum protocolo encontrado."]); } public function minhasPendenciasCorretorAction() { $request = $this->getRequest(); if( $request->isGet() ){ $params = $request->getParams(); } else { $input = file_get_contents("php://input"); $postdata = json_decode($input); $this->_log->log("POSTDATA: " . print_r($postdata, true), Zend_Log::INFO); $params = (array) $postdata; } if( isset($params) ){ $token = $params['token']; $pendencias = $params['pendencia_fisicos']; $service = new Service_ServerSoap(); $response = $service->getFisicosPendentesCorretor($token, $pendencias, $params); if( $response ){ $this->_helper->json(array( $response )); } else { $this->_helper->json(array( "not_found" => "Nenhuma pendência encontrada." )); } } else { $this->_helper->json("Não foi possível consultar, por favor tente novamente."); } } public function sincYuppiesAction() { if ($this->_request->isPost()) { $dados = $this->_request->getPost(); try { if (empty($dados['token'])) { $this->_helper->json('Token obrigatório.'); } $sistema = Yuppie_Auth::getSiteKey(); $modelCorretor = new Model_Corretor(); if (!$corretor = $modelCorretor->autenticarSinc($dados['token'])) { $this->_helper->json(["error" => "Token incorreto."]); } $dbtContrato = new Model_DbTable_Contrato(); $contratos = $dbtContrato->fetchSincronizacaoYuppies($corretor->id, $dados['offset'], $dados['ultimaSinc']); $comissoes = (new Model_DbTable_ProtocoloContrato())->getProtocolosPagos($corretor->id, $dados['offset'], $dados['ultimaSinc']); $this->_helper->json([ "token" => $dados['token'], "contratos" => $contratos, 'comissoes' => $comissoes, "sistema" => $sistema ]); } catch ( Core_Exception $e ) { $this->_helper->json($e->getMessage()); } catch ( Exception $e ) { Yuppie_Log::write($e->getMessage(), $this); $this->_helper->json("Falha de comunicação com o sistema origem"); } } } public function sincYuppiesComissionamentoAction() { if ($this->_request->isPost()) { $dados = $this->_request->getPost(); $bancoId = Model_Banco::bancoPorNome($dados['banco']); try { if (empty($dados['token'])) { $this->_helper->json('Token obrigatório.'); } $sistema = Yuppie_Auth::getSiteKey(); $modelCorretor = new Model_Corretor(); if (!$corretor = $modelCorretor->autenticarSinc($dados['token'])) { $this->_helper->json(["error" => "Token incorreto."]); } $dbtComissionamentoIndividual = new Model_ComissionamentoCorretorPercentual(); $comissionamentoIndividual = $dbtComissionamentoIndividual->listar([ 'corretor_id' => $corretor->id, 'data_importacao' => $dados['ultimaSinc'], 'page' => $dados['offset'], 'banco_id' => $bancoId ], $dados['offset'], 100); $individual = (array) $comissionamentoIndividual; $dbtComissionamentoGrupo = new Model_ComissionamentoGrupoPercentual(); $comissionamentoGrupo = $dbtComissionamentoGrupo->listar([ 'corretor_id' => $corretor->id, 'data_importacao' => $dados['ultimaSinc'], 'page' => $dados['offset'], 'banco_id' => $bancoId ], $dados['offset'], 100); $grupo = (array) $comissionamentoGrupo; if (!empty($corretor->grupo_comissao)) { $grupoCorretor = (new Model_GrupoComissao())->exibir($corretor->grupo_comissao); $dbtComissionamentoGrupoGeral = new Model_Comissionamento(); $comissionamentoGrupoGeral = $dbtComissionamentoGrupoGeral->listarPercValido([ 'corretor_id' => $corretor->id, 'data_importacao' => $dados['ultimaSinc'], 'page' => $dados['offset'], 'banco_id' => $bancoId ], ['comissionamento.id ASC', 'perc.id ASC', 'tipo_produto ASC'], true, 'perc.id', $dados['offset']); $grupoGeral = (array) $comissionamentoGrupoGeral; $grupoCorretor = (array) $grupoCorretor; } $this->_helper->json([ "token" => $dados['token'], "individual" => $individual, 'grupo' => $grupo, 'grupo_geral' => $grupoGeral, 'grupo_corretor' => $grupoCorretor, "sistema" => $sistema ]); } catch ( Core_Exception $e ) { $this->_helper->json($e->getMessage()); } catch ( Exception $e ) { Yuppie_Log::write($e->getMessage(), $this); $this->_helper->json("Falha de comunicação com o sistema origem"); } } } public function webhookHigienizacaoCpfAction() { $params = json_decode($this->getRequest()->getRawBody()); if (empty($params->listaMargemConsignacao)) { $this->_helper->json(['alert' => 'Nenhuma informação a ser lida.']); } foreach ($params->listaMargemConsignacao as $margem) { try { $callcenterBase = new Model_CallcenterBase(); $callcenterBase->gravarConsultaOmega($margem); } catch (Core_Exception $e) { continue; } catch (Zend_Db_Exception $e) { $this->_helper->json(['error' => 'Erro ao salvar dados no banco de dados.']); } } $this->_helper->json(['success' => 'Processo concluído com sucesso.']); } public function saveSupervisorAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($data['empresa_id'])) { $this->_helper->json(['status' => '0', 'msg' => 'Empresa não informada']); } if (empty($data['gerente_id'])) { $this->_helper->json(['status' => '0', 'msg' => 'Gerente não informado']); } $manager = (new Model_Gerente())->exibir($data['gerente_id']); if (empty($manager)) { $this->_helper->json(['status' => '0', 'msg' => 'Gerente não localizado']); } $model = new Model_GerenteRota($data); if ($data['codigo_extra']) { $dataSet = $model->exibirPorCodigoExtra($data['codigo_extra']); if ($dataSet) { $model->setId($dataSet->id); } } if (empty($dataSet)) { $dataSet = $model->getByCpf($data['cpf']); if ($dataSet) { $model->setId($dataSet->id); } } try { $result = $model->salvar($model); } catch (CPFJaCadastradoException $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { $this->_helper->json(['status' => 0, 'msg' => "Falha na inclusão"]); } if ($result) { $this->_helper->json(['status' => 1, 'msg' => 'Dados salvos com sucesso.', 'result' => $result]); } $this->_helper->json(['status' => 0, 'msg' => 'Nenhum registro foi salvo']); } public function saveRouteAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($data['gerente_id'])) { $this->_helper->json(['status' => '0', 'msg' => 'Gerente não informado']); } $manager = (new Model_GerenteRota())->exibir($data['gerente_id']); if (empty($manager)) { $this->_helper->json(['status' => '0', 'msg' => 'Gerente não localizado']); } $model = new Model_Rota($data); $dataSet = $model->exibirPorGerente($data['gerente_id']); if ($dataSet) { $model->setId($dataSet->id); } try { $result = $model->salvar($model); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { $this->_helper->json(['status' => 0, 'msg' => "Falha na inclusão"]); } if ($result) { $this->_helper->json(['status' => 1, 'msg' => 'Dados salvos com sucesso.', 'result' => $result]); } $this->_helper->json(['status' => 0, 'msg' => 'Nenhum registro foi salvo']); } public function savePartnerAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($data['empresa_id'])) { $this->_helper->json(['status' => '0', 'msg' => 'Empresa não informada']); } //cadastrar ou atualizar o afiliado/corretor //retornar o ID gerado //pode ser cadastrado pelo código (ID) que ele já tenha $model = new Model_Corretor($data); if (empty($data['supervisor_id'])) { $this->_helper->json(['status' => '0', 'msg' => 'Informe o campo supervisor_id']); } $supervisor = (new Model_GerenteRota())->exibirPorCodigoExtra($data['supervisor_id']); if (empty($supervisor)) { $supervisor = (new Model_GerenteRota())->exibir($data['supervisor_id']); } if (empty($supervisor)) { $this->_helper->json(['status' => '0', 'msg' => 'Supervisor não localizado']); } $rota = (new Model_Rota())->exibirPorGerente($supervisor->id); if (empty($rota)) { $this->_helper->json(['status' => '0', 'msg' => 'Supervisor não possui rota vinculada']); } if ($data['codigo_extra']) { $dataSet = $model->exibirPorCodigoExtra($data['codigo_extra']); if ($dataSet) { $model->setId($dataSet->id); } } if (empty($dataSet)) { $dataSet = $model->getByCpf($data['cpf']); if ($dataSet) { $model->setId($dataSet->id); } } try { $model->setRotaId($rota->id); $model->setGrupoAcesso($data['grupo_acesso'] ?: 1); $result = $model->salvar($model); } catch (CPFJaCadastradoException $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { Yuppie_Log::write($e->getMessage() . $e->getTraceAsString()); $this->_helper->json(['status' => 0, 'msg' => "Falha na inclusão"]); } if ($result) { $this->_helper->json(['status' => 1, 'msg' => 'Dados salvos com sucesso.', 'result' => $result]); } $this->_helper->json(['status' => 0, 'msg' => 'Nenhum registro foi salvo']); } public function getLinkAutocontratacaoAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $links = []; $modelCorretor = new Model_Corretor(); $dataSet = $modelCorretor->exibir($request->getParam('id')); $token = $data['codigo_extra'] ?: $data['token']; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Corretor/Afiliado não identificado.']); } $corretor = (new Model_Corretor())->exibirPorCodigoExtra($token) ?: (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => 'Corretor/Afiliado não localizado.']); } try { $modelCorretor->gerarMeusLinks([ 'FGTS' => 'AUTO-CONTRATAÇÃO FGTS', 'INSS' => 'AUTO-CONTRATAÇÃO INSS', 'SIAPE' => 'AUTO-CONTRATAÇÃO SIAPE', 'CREDCESTA' => 'AUTO-CONTRATAÇÃO CREDCESTA', 'CARTAO_BENEFICIO' => 'CARTÃO BENEFÍCIO INSS', 'GOV_BA' => 'GOVERNO DA BAHIA', ], $links, 'simulacao-aberta', false, $dataSet->id); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } if (empty($links)) { $this->_helper->json(['status' => 0, 'msg' => 'Nenhum link gerado.']); } $this->_helper->json(['status' => 1, 'result' => $links]); } public function consultarContratosAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $data['codigo_extra'] ?: $data['token']; $contratos = []; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Corretor/Afiliado não identificado.']); } $corretor = (new Model_Corretor())->exibirPorCodigoExtra($token) ?: (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => "Corretor/Afiliado não encontrado"]); } if (empty($data['numero_contrato']) && empty($data['cpf_cliente']) && empty($data['data_emissao_de']) && empty($data['data_emissao_a']) && empty($data['data_liberacao_de']) && empty($data['data_emissao_a'])) { $data['data_emissao_de'] = date('d/m/Y', strtotime('-7 days')); $data['data_emissao_a'] = date('d/m/Y'); } try { $service = new Service_ServerSoap(); $contratos = $service->getSituacaoContrato($corretor->token_sinc_yuppies, $data); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { echo $e->getMessage(); die($e->getTraceAsString()); $this->_helper->json(['status' => 0, 'msg' => "Falha na excecução"]); } if (empty($contratos)) { $this->_helper->json(['status' => 0, 'msg' => "Nenhum contrato localizado"]); } $this->_helper->json(['status' => 1, "count" => count($contratos), 'result' => $contratos]); } public function savePartnerBankCodeAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $request->getParam('codigo_extra') ?: $request->getParam('token'); if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Corretor/Afiliado não identificado.']); } $corretor = (new Model_Corretor())->exibirPorCodigoExtra($token) ?: (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => "Corretor/Afiliado não encontrado"]); } if (empty($data['banco'])) { $this->_helper->json(['status' => 0, 'msg' => 'Banco não informado.']); } $bancoId = (new Model_Banco())->bancoPorNome($data['banco']); if (empty($bancoId)) { $this->_helper->json(['status' => 0, 'msg' => "Banco não localizado."]); } $model = new Model_CorretorSenha(); $model->setBancoId($bancoId); $model->setSenha($data['usuario']); $model->setCorretorId($corretor->id); try { $result = $model->salvar($model); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { Yuppie_Log::write($e->getMessage() . $e->getTraceAsString()); $this->_helper->json(['status' => 0, 'msg' => "Falha na inclusão"]); } if ($result) { $this->_helper->json(['status' => 1, 'msg' => 'Dados salvos com sucesso.', 'result' => $result]); } $this->_helper->json(['status' => 0, 'msg' => 'Nenhum registro foi salvo']); } public function saveProposalAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $data['codigo_extra'] ?: $data['token']; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Corretor/Afiliado não identificado.']); } $corretor = (new Model_Corretor())->exibirPorCodigoExtra($token) ?: (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => "Corretor/Afiliado não encontrado"]); } if (empty($data['banco'])) { $this->_helper->json(['status' => 0, 'msg' => 'Banco não informado.']); } $bancoId = (new Model_Banco())->bancoPorNome($data['banco']); if (empty($bancoId)) { $this->_helper->json(['status' => 0, 'msg' => "Banco não localizado."]); } if (empty($data['convenio'])) { $this->_helper->json(['status' => 0, 'msg' => 'Convênio não informado.']); } $convenioId = (new Model_Convenio())->getOrCreateConvenio($data['convenio']); if (empty($convenioId)) { $this->_helper->json(['status' => 0, 'msg' => "Convênio não localizado."]); } if (empty($data['tabela_codigo'])) { $this->_helper->json(['status' => 0, 'msg' => 'Código da Tabela não informado.']); } $tabelaId = (new Model_Tabela())->getOrCreateTabelaByCodigo($data['tabela_codigo'], $data['tabela_descricao'], $convenioId, $bancoId); if (empty($tabelaId)) { $this->_helper->json(['status' => 0, 'msg' => "Tabela não localizada."]); } if (empty($data['nome'])) { $this->_helper->json(['status' => 0, 'msg' => 'Nome do cliente não informado.']); } if (empty($data['cpf'])) { $this->_helper->json(['status' => 0, 'msg' => 'CPF do cliente não informado.']); } try { $data['empresa_id'] = $corretor->empresa_id; $clienteId = (new Model_Cliente($data))->getOrCreateByCpf($data['cpf']); } catch (Exception $e) { $clienteId = null; Yuppie_Log::write("Falha ao cadastrar/buscar cliente: " . $e->getMessage() . $e->getTraceAsString(), $this); } if (empty($clienteId)) { $this->_helper->json(['status' => 0, 'msg' => "Cliente não localizado."]); } $model = new Model_Proposta($data); $model->setBancoId($bancoId); $model->setConvenioId($convenioId); $model->setTabelaId($tabelaId); $model->setClienteId($clienteId); $model->setCorretorId($corretor->id); try { $result = $model->salvar($model); } catch (Core_Exception $e) { $this->_helper->json(['status' => 0, 'msg' => $e->getMessage()]); } catch (Throwable $e) { Yuppie_Log::write($e->getMessage() . $e->getTraceAsString()); $this->_helper->json(['status' => 0, 'msg' => "Falha na inclusão"]); } if ($result) { $this->_helper->json(['status' => 1, 'msg' => 'Dados salvos com sucesso.', 'result' => $result]); } $this->_helper->json(['status' => 0, 'msg' => 'Nenhum registro foi salvo']); } public function consultarCondicoesComerciaisAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $data['token']; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Token não informado.']); } $corretor = (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => "Corretor/Afiliado não encontrado"]); } $convenio = (new Model_Convenio())->existe($data['convenio']); $fields = $data; $fields['corretor_id'] = $corretor->id; $fields['convenio_id'] = $convenio ? $convenio->id : null; $fields['banco_id'] = $data['banco'] ? (new Model_Banco())->bancoPorNome($data['banco']) : null; $comissoesCorretor = (new Model_Corretor())->exibirCondicoesComerciais($fields); $comissoes = array_map(function($comissao){ return [ "banco_nome" => $comissao['detalhe']['banco_nome'], "convenio_nome" => $comissao['detalhe']['convenio_nome'], "tabela_nome" => $comissao['detalhe']['tabela_nome'], "base_comissao" => $comissao['detalhe']['base_comissao'], "comissao" => $comissao['detalhe']['comissao'], "tipo_produto" => $comissao['detalhe']['tipo_produto'], "prazo_de" => $comissao['detalhe']['prazo_de'], "prazo_a" => $comissao['detalhe']['prazo_a'], "idade_inicial" => $comissao['detalhe']['idade_inicial'], "idade_final" => $comissao['detalhe']['idade_final'], ]; }, $comissoesCorretor); $this->_helper->json(['status' => 1, 'result' => current($comissoes)]); } public function linkDigitacaoPropostaAction() { $request = $this->getRequest(); $data = (array) json_decode($request->getRawBody()); $token = $data['token']; if (!$request->isPost()) { $this->_helper->json(['status' => '0', 'msg' => 'Método não permitido']); } if (empty($token)) { $this->_helper->json(['status' => 0, 'msg' => 'Token não informado.']); } $corretor = (new Model_Corretor())->exibirPorToken($token); if (empty($corretor)) { $this->_helper->json(['status' => 0, 'msg' => "Corretor/Afiliado não encontrado"]); } $link = Core_Link::criaLink("https://{$_SERVER['HTTP_HOST']}{$this->getRequest()->getBaseUrl()}/proposta-cliente", "corretor_id={$corretor->id}"); $this->_helper->json(['status' => 1, 'result' => ['link' => $link]]); } }
💾 保存文件
← 返回文件管理器