✏️ 正在编辑: SincronizacaoController.php
路径:
/srv/systems_dir/yuppiecred-lidernegocios/application/controllers/SincronizacaoController.php
提示:
您可以编辑任何文件(包括二进制文件),但请注意不当修改可能导致文件损坏。
<?php /** * Sincronização */ class SincronizacaoController extends Zend_Controller_Action { public function init() { } public function indexAction() { $this->_helper->redirector('localizar-arquivos'); } public function importarGcomAction() { set_time_limit(0); // ini_set('memory_limit', '-1'); $this->_helper->flashMessenger(array( 'info' => 'Atenção! O campo "Usar planilha genérica", serve apenas para importação da planilha padrão.' )); $request = $this->getRequest(); $form = new Form_SincronizarGcom(); if ($request->isPost() && $form->isValid($request->getPost())) { $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination(UPLOAD_PATH); try { $upload->receive(); } catch ( Zend_File_Transfer_Exception $e ) { $this->_helper->flashMessenger(array( 'error' => $e->getMessage() )); } $file = $upload->getFileName(); $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $pathinfo = pathinfo($file); $log = new stdClass(); $log->arquivo = isset($pathinfo) ? $pathinfo['basename'] : ""; if( $extension == 'txt' && $form->getValue('banco_id') == 4 ){ try { $resultado = Core_Banco_Planilha_Pan_Extrator::lerArquivo($file); } catch ( Exception $exception ) { $this->_helper->flashMessenger(array( 'error' => $exception->getMessage() )); } $ns = new Zend_Session_Namespace('importacao_gcom'); $ns->unsetAll(); $ns->importacao_gcom = $resultado; $ns->arquivo = $log; if( $resultado > 0 && $request->isXmlHttpRequest() ){ $this->_helper->json(array( 'params' => $this->getRequest()->getParams(), 'url' => '/sincronizacao/processar-gcom' )); } } if( in_array($extension, array( 'csv', 'txt' )) ){ $objReader = PHPExcel_IOFactory::createReader('CSV'); $objReader->setDelimiter($extension == 'csv' ? ';' : '#'); $encoding = Core_Util::detectFileEncoding($file); if(strstr($encoding, 'unknown') || is_null($encoding) || strstr($encoding, 'binary')){ $encoding = mb_detect_encoding(file_get_contents($file), "UTF-8,ISO-8859-1,ISO-8859-15,WINDOWS-1252"); } $objReader->setInputEncoding($encoding); } else { $objReader = PHPExcel_IOFactory::createReaderForFile($file); $fileinfo = $objReader->listWorksheetInfo($file); if( is_array($fileinfo) && ($arrayFilter = array_filter($fileinfo) != null) ){ $firstSheetName = $fileinfo[0]['worksheetName']; $objReader->setLoadSheetsOnly($firstSheetName); } } try { $objPHPExcel = $objReader->load($file); } catch ( Exception $e ) { if( $e->getMessage() == "Cannot read encrypted file" ){ $this->_helper->flashMessenger(array( 'alert' => 'O arquivo não pode ser lido. Verifique se ele ' . 'está protegido por senha e tente novamente.' )); } } if( isset($objPHPExcel) && is_object($objPHPExcel) ){ $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $objPHPExcel->disconnectWorksheets(); unset($objPHPExcel); unset($objReader); unlink($file); $ns = new Zend_Session_Namespace('importacao_gcom'); $ns->unsetAll(); array_shift($sheetData); $ns->importacao_gcom = $sheetData; $ns->arquivo = $log; } } if( $request->isXmlHttpRequest() ){ $this->_helper->json(array( 'params' => $this->getRequest()->getPost(), 'url' => '/sincronizacao/processar-gcom' )); } $this->view->form = $form; } public function processarGcomAction() { set_time_limit(0); // ini_set('memory_limit', '-1'); $dados = array( 'readCompleted' => null, 'result' => null ); $request = $this->getRequest(); $ns = new Zend_Session_Namespace('importacao_gcom'); $params = $request->getParam('params'); if( !$params['banco_id'] ){ $this->_helper->json(array( 'alert' => 'Atenção! Banco deve ser informado.', )); return; } $linhas = $ns->importacao_gcom; $ns->importacao_gcom = array_slice($linhas, 100, null, true); $sheetData = array_diff_key($linhas, $ns->importacao_gcom); $arquivo = $ns->arquivo; $contrato = new Model_Contrato(); //CONTROLE DO INÍCIO DA EXECUÇÃO $inicioLaco = null; if( isset($params['lacoIniciado']) ){ $inicioLaco = 0; } if( !isset($params['usar_padrao']) ){ $params['usar_padrao'] = null; } $naoImportados = null; if( is_string($params['banco_id']) && !empty($params['banco_id']) && !is_numeric($params['banco_id']) ){ if( $params['banco_id'] == "BANCO GENERICO" ){ $params['banco_id'] = 999; } else { $params['banco_id'] = Model_Banco::bancoPorNome($params['banco_id']); } } try { $naoImportados = $contrato->importarComissaoBanco($params['banco_id'], $sheetData, $params['usar_padrao'], $inicioLaco, $params['layout_banco'], $arquivo); } catch ( Exception $e ) { $this->_helper->json(array( 'error' => $e->getMessage() )); } $dados = array( 'readCompleted' => count($ns->importacao_gcom) > 0 ? false : true, 'result' => $naoImportados ); $error = new Zend_Session_Namespace('error'); if( !is_array($error->error) ){ $error->error = $naoImportados; } else { $tmp = array_merge($error->error, array_values($naoImportados)); $error->error = $tmp; } if( count($ns->importacao_gcom) <= 0 ){ $this->view->nao_baixados = $error->error; $error->unsetAll(); $this->_helper->json(array( 'content' => $this->view->render('sincronizacao/nao-baixados.phtml') )); } $this->_helper->json($dados); } public function cadastrarUsuariosApiAction() { $request = $this->getRequest(); $id = $request->getParam('id'); $form = new Form_CadastrarUsuariosApi($id); if ($request->isPost() && $form->isValid($request->getPost())) { try { $model = new Model_UsuariosApi($request->getPost()); $id = $model->salvar($model); if ($id > 0) { $this->_helper->flashMessenger([ 'success' => 'Configurações salvas com sucesso.' ]); $this->_helper->redirector('cadastrar-usuarios-api', null, null, ['id' => $id]); } $this->_helper->flashMessenger(['error' => "Houve um erro ao salvar o usuário."]); } catch ( Core_Exception $e ){ $this->_helper->flashMessenger(['error' => "Houve um erro ao salvar o usuário. Erro: " . $e->getMessage()]); } catch ( Throwable $e ) { $this->_helper->flashMessenger(array('error' => $e->getMessage())); } } if ($id > 0) { $model = new Model_UsuariosApi(); $dados = $model->exibir($id); $form->populate($dados->toArray()); } if ($id > 0 && empty($dados['ativo'])) { $this->_helper->flashMessenger([ 'alert' => 'Usuário inativo por erro na integração com a API.' ]); } $this->view->form = $form; } public function ativarUsuariosApiAction() { $request = $this->getRequest(); $id = $request->getParam('id'); if (Model_UsuariosApi::ativarUsuario($id)) { $this->_helper->flashMessenger([ 'success' => 'Usuário reativado com sucesso.' ]); } else { $this->_helper->flashMessenger([ 'error' => 'Houve um erro ao reativar usuário.' ]); } $this->_helper->redirector('cadastrar-usuarios-api', null, null, ['id' => $id]); } public function dadosSincronizacaoAction() { $this->view->usuarios = (new Model_UsuariosApi())->listar(); } public function deleteUsuariosApiAction() { try { $request = $this->getRequest(); $id = $request->getParam('id'); $model = new Model_UsuariosApi(); $result = $model->excluir($id); if ($result) { $this->_helper->flashMessenger([ 'success' => 'Usuário excluído com sucesso.' ]); $this->_helper->redirector('dados-sincronizacao'); } $this->_helper->flashMessenger(['error' => "Houve um erro ao excluir o usuário."]); } catch (Throwable $erro) { $this->_helper->flashMessenger(['error' => "Houve um erro ao excluir o usuário. Erro: " . $erro->getMessage()]); } $this->_helper->redirector('dados-sincronizacao'); } public function importarDiretoAction() { $request = $this->getRequest(); $form = new Form_ImportarDireto(); $bancoNome = $request->getParam('banco_nome'); if( $request->isPost() && $form->isValid($request->getPost()) ){ $bancoNome = Model_Banco::getNomeBancoImportacao($bancoNome); $bancoId = Model_Banco::bancoPorNome($bancoNome); $falhaDb = new Model_DbTable_FalhaImportacao(); $where = 'banco_id = ' . $bancoId . " AND " . "data_falha >= STR_TO_DATE('{$request->getParam('data_importacao')} 00:00:00', '%d/%m/%Y %H:%i:%s') AND " . "data_falha <= STR_TO_DATE('{$request->getParam('data_importacao')} 23:59:59', '%d/%m/%Y %H:%i:%s')"; $naoImportados = $falhaDb->fetchAll($where); if( count($naoImportados) == 0 ){ $this->_helper->flashMessenger(array( 'alert' => 'Nenhum registro encontrado' )); } $this->view->nao_importados = $naoImportados; } $this->_helper->flashMessenger(array('info' => "Alteração na rotina de importação! Agora você configura os dados do banco <a href='dados-sincronizacao'>clicando aqui!</a>")); $this->view->form = $form; } public function importacaoDiretaAction() { set_time_limit(0); $bancoNome = $this->getRequest()->getParam('banco_nome'); $dataImportacao = $this->getRequest()->getParam('data_importacao'); $empresaId = $this->getRequest()->getParam('empresa_id'); $sincronizacaoId = $this->getRequest()->getParam('sincronizacao_id'); if (!$bancoNome) { $this->_helper->json(['alert' => "Banco não informado."]); } if ($bancoNome == 'API Yuppie' && empty($sincronizacaoId)) { $this->_helper->json(['alert' => 'Selecione um sub-estabelecido e um sistema origem', 'mensagens' => null]); } if ($bancoNome == 'API Yuppie' && !empty($sincronizacaoId)) { $tbTokens = new Model_DbTable_SincYuppies(); $tokenRow = $tbTokens->fetchRow(['id = ?' => $sincronizacaoId]); $token = $tokenRow->toArray(); $token['ultima_sincronizacao'] = Core_Util::convertDate($dataImportacao) . " 00:00:00"; $token['empresa_id'] = $empresaId; $sinc = new Core_Sincronizacao($token); $return = $sinc->getDadosOrigem(); if (!empty($return['erro'])) { $this->_helper->json(['erro' => 'Houve um erro na sincronização entre Yuppies!', 'mensagens' => null]); } $this->_helper->json(['success' => 'Sincronização entre Yuppies realizada!', 'mensagens' => null]); } else { try { $result = (new Model_ImportarDireto()) ->setBancoNome($bancoNome) ->setDataImportacao($dataImportacao) ->setEmpresaId($empresaId) ->importar(); } catch ( Exception $e ) { $this->_helper->json(['alert' => $e->getMessage(), 'mensagens' => null]); } $this->_helper->json($result); } } public function localizarArquivosAction() { $form = new Form_Sincronizar(); $request = $this->getRequest(); $bancoId = (int) $request->getParam('banco_id'); if( $this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost()) ){ $file = new Core_File(); $file->setPath($bancoId); $listaArquivos = $file->listFiles(); $arquivos = array(); $arquivosBonsucesso = array(); foreach ( $listaArquivos as $arquivo ) { $f = pathinfo($arquivo); //Bradesco if( strtolower($f['extension']) == "txt" ){ $arquivos[] = $arquivo; } //BonSucesso if( strtolower($f['extension']) == "gz" && (strpos($f['filename'], "DadosProposta") || strpos($f['filename'], "SituacaoProposta") || strpos($f['filename'], "CreditoCliente") || strpos($f['filename'], "_Cliente")) ){ $fName = explode("_", $arquivo); if( strpos($f['filename'], "_Cliente") ){ $indice = "0_"; }elseif( strpos($f['filename'], "DadosProposta") ){ $indice = "1_"; }elseif( strpos($f['filename'], "CreditoCliente") ){ $indice = "2_"; }elseif( strpos($f['filename'], "SituacaoProposta") ){ $indice = "3_"; } $indice .= $fName[0] . "_" . $fName[1]; $indice .= is_numeric($fName[2]) ? "_" . $fName[2] : ""; $arquivosBonsucesso[$indice] = $arquivo; } } if( count($arquivosBonsucesso) > 0 ){ ksort($arquivosBonsucesso); $arquivos = $arquivosBonsucesso; } $this->view->files = $arquivos; } if( $this->getRequest()->getParam('status') == 1 ){ $this->_helper->flashMessenger(array( 'success' => 'A sincronização foi concluída com sucesso!' )); } $this->view->form = $form; $this->view->bancoId = $bancoId; } public function importarArquivoAction() { $request = $this->getRequest(); $arquivo = $request->getParam('file'); $bancoId = (int) $request->getParam('banco_id'); $reset = (int) $request->getParam('reset'); $sheetData = array(); $result = array(); $dados = array( 'readCompleted' => null, 'result' => null ); if( !empty($arquivo) && $bancoId > 0 ){ $ns = new Zend_Session_Namespace('arquivo_net_certo'); $file = new Core_File(); try { $banco = Core_Banco_Service_Ftp::factoryBanco($bancoId, $arquivo); } catch ( Exception $ex ) { $this->_helper->json(array( "readCompleted" => 1, "error" => "Não foi possível localizar o banco. Motivo: " . $ex->getMessage() )); } if( $reset == 1 ){ $ns->unsetAll(); try { $retorno = $file->_readFile($arquivo, $bancoId); } catch ( Exception $ex ) { $this->_helper->json(array( "readCompleted" => 1, "error" => "Não foi possível ler o arquivo: {$arquivo} . Motivo: " . $ex->getMessage() )); } $ns->arquivo_net_certo = $retorno; } if( count($ns->arquivo_net_certo) > 0 ){ $sheetData = Core_Banco_Planilha::arraySlice($ns->arquivo_net_certo, 100); } $naoImportados = null; try { $banco->setArquivoOrigem($arquivo); $naoImportados = $banco->importar($sheetData); } catch ( Exception $ex ) { $this->_helper->json(array( 'error' => 'Ocorreu algum erro na importaçao!' . $ex->getMessage(), 'readCompleted' => 1, )); } if( $naoImportados != null ){ $falhaImportacao = new Model_DbTable_FalhaImportacao(); foreach ( $naoImportados as $data ) { $data['arquivo'] = $arquivo; $data['banco_id'] = $bancoId; unset($data['valor_liquido']); $falhaImportacao->insert($data); } } $dados = array( 'readCompleted' => count($ns->arquivo_net_certo) > 0 ? 0 : 1, 'result' => $naoImportados ); $error = new Zend_Session_Namespace('error'); if( !is_array($error->error) ){ $error->error = $naoImportados; } else { $tmp = array_merge($error->error, array_values($naoImportados)); $error->error = $tmp; } if( count($ns->arquivo_net_certo) <= 0 && count($sheetData) > 0 ){ $this->view->nao_baixados = $error->error; $error->unsetAll(); $this->_helper->json(array( 'content' => $this->view->render('sincronizacao/nao-baixados.phtml') )); } } $this->_helper->json($dados); } public function arquivosImportadosAction() { $request = $this->getRequest(); $form = new Form_Filtro_ArquivosSincronizados(); $this->_helper->flashMessenger(array( 'alert' => 'Atenção!!! Apenas remova o arquivo caso queira que seja importado novamente.' )); $arquivos = array(); if( $request->isPost() ){ $form->populate($request->getPost()); $where = null; if( $request->getPost('data_de') != null && $request->getPost('data_a') != null ){ $where = "(data_importacao >= STR_TO_DATE('" . $request->getPost('data_de') . "', '%d/%m/%Y %H:%i:%s')" . " AND data_importacao <= STR_TO_DATE('" . $request->getPost('data_a') . " 23:59:59', '%d/%m/%Y %H:%i:%s'))"; } if( $request->getPost('banco_id') != null && $request->getPost('banco_id') > 0 ){ if( $where ){ $where .= " AND "; } $banco = $request->getPost('banco_id'); $where .= "(banco_id = {$banco} )"; } $arquivo = $request->getPost('arquivo'); if( $arquivo != null && !empty($arquivo) ){ if( $where ){ $where .= " AND "; } $where .= "(arquivo LIKE '%{$arquivo}%')"; } if( $where ){ $where .= ' AND excluido <> 1'; } else { $where .= 'excluido <> 1'; } $arquivo = new Model_DbTable_ArquivoImportado(); $arquivos = $arquivo->fetchAll($where, 'id DESC'); } $this->view->arquivos = $arquivos; $this->view->form = $form; } public function excluirArquivosAction() { $this->_helper->viewRenderer->setNoRender(); $this->_helper->getHelper('layout')->disableLayout(); $request = $this->getRequest(); $id = (int) $request->getParam('id'); $arquivos = $request->getParam('arquivos'); $arquivoDb = new Model_DbTable_ArquivoImportado(); $count = 0; if( count($arquivos) <= 0 && $id <= 0 ){ $this->_helper->flashMessenger(array( 'alert' => 'Nenhum arquivo selecionado' )); $this->_helper->redirector('arquivos-importados'); } if( $id > 0 ){ $arquivo = $arquivoDb->fetchRow("id = " . $id); $falhaDb = new Model_DbTable_FalhaImportacao(); $contratos = $falhaDb->delete("arquivo = '{$arquivo['arquivo']}'"); $result = $arquivoDb->delete("id = " . $id); if( $result > 0 ){ $this->_helper->flashMessenger(array( 'success' => 'Registro excluido com sucesso.' )); } else { $this->_helper->flashMessenger(array( 'error' => 'Nenhum registro foi alterado.' )); } $this->_helper->redirector('arquivos-importados'); } if( count($arquivos) > 0 ){ foreach ( $arquivos as $a ) { $result = $arquivoDb->delete("id = " . $a); $count++; } if( $result > 0 ){ $this->_helper->flashMessenger(array( 'success' => $count > 0 ? 'Registro excluido com sucesso.' : 'Registros excluidos com sucesso.' )); } else { $this->_helper->flashMessenger(array( 'error' => 'Nenhum registro foi alterado.' )); } $this->_helper->redirector('arquivos-importados'); } } public function baixarArquivoFtpAction() { set_time_limit(0); $empresaId = (int) $this->getRequest()->getParam('empresa_id'); $bancoId = (int) $this->getRequest()->getParam('banco_id'); if( !$empresaId || !$bancoId ){ $this->_helper->json(array( 'alert' => "Empresa ou Banco não foi informado." )); } try { $ftp = Core_Banco_Service_Ftp::factory($empresaId, $bancoId); } catch ( Exception $ex ) { $this->_helper->json(array( 'alert' => $ex->getMessage() )); } if( !$ftp->getIsConnected() ){ $this->_helper->json(array( 'alert' => 'Não foi possível estabelecer uma conexão FTP. Verifique se os dados de acesso estão corretos.' )); } $classe = get_class($ftp); $qtdArquivosBaixados = 0; switch ( $classe ) { case 'Core_Banco_Service_FtpBradesco': try { $qtdArquivosBaixados = $ftp->baixarArquivos(utf8_decode('Saida'), $bancoId); } catch ( Exception $exc ) { $this->_helper->json(array( 'alert' => $exc->getMessage() )); } break; case 'Core_Banco_Service_FtpBonSucesso': try { //Arquivos do diretório raiz $qtdArquivosBaixados = $ftp->baixarArquivos(null, $bancoId, false); //Arquivos da pasta NBC $qtdArquivosBaixadosNbc = $ftp->baixarArquivos('NBC', $bancoId); } catch ( Exception $exc ) { $this->_helper->json(array( 'alert' => $exc->getMessage() )); } $qtdArquivosBaixados += $qtdArquivosBaixadosNbc; //4 arquivos equivalem a 1 na listagem $qtdArquivosBaixados = $qtdArquivosBaixados > 0 ? round(($qtdArquivosBaixados / 4)) : 0; break; default: throw new Yuppie_Exception('Ocorreu algum erro ao baixar os arquivos'); } if( $qtdArquivosBaixados > 0 ){ $this->_helper->json(array( 'alert' => $qtdArquivosBaixados . ' foram baixados.' )); } else { $this->_helper->json(array( 'alert' => 'Nenhum arquivo foi baixado.' )); } } public function importarAdiantamentosAction() { ini_set('memory_limit', '400M'); $request = $this->getRequest(); $form = new Form_SincronizarAdiantamento(); if( $request->isPost() && $form->isValid($request->getPost()) ){ $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination(UPLOAD_PATH); try { $upload->receive(); } catch ( Zend_File_Transfer_Exception $e ) { $this->_helper->flashMessenger(array( 'error' => $e->getMessage() )); } $extension = strtolower(pathinfo($upload->getFileName(), PATHINFO_EXTENSION)); if( in_array($extension, array( 'csv', 'txt' )) ){ $objReader = PHPExcel_IOFactory::createReader('CSV'); $objReader->setDelimiter($extension == 'csv' ? ';' : '#'); } else { $objReader = PHPExcel_IOFactory::createReaderForFile($upload->getFileName()); $fileinfo = $objReader->listWorksheetInfo($upload->getFileName()); if( is_array($fileinfo) && ($arrayFilter = array_filter($fileinfo) != null) ){ $firstSheetName = $fileinfo[0]['worksheetName']; $objReader->setLoadSheetsOnly($firstSheetName); } } try { $objPHPExcel = $objReader->load($upload->getFileName()); } catch ( Exception $e ) { if( $e->getMessage() == "Cannot read encrypted file" ){ $this->_helper->flashMessenger(array( 'alert' => 'O arquivo não pode ser lido. Verifique se ele ' . 'está protegido por senha e tente novamente.' )); } } if( isset($objPHPExcel) && is_object($objPHPExcel) ){ $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $objPHPExcel->disconnectWorksheets(); unset($objPHPExcel); unset($objReader); unlink($upload->getFileName()); $ns = new Zend_Session_Namespace('importacao_adiantamento'); $ns->unsetAll(); array_shift($sheetData); $ns->importacao_adiantamento = $sheetData; } } if( $request->isXmlHttpRequest() ){ $this->_helper->json(array( 'params' => $this->getRequest()->getPost(), 'url' => '/sincronizacao/processar-adiantamento' )); } $this->view->form = $form; } public function processarAdiantamentoAction() { $dados = array( 'readCompleted' => null, 'result' => null ); $request = $this->getRequest(); $ns = new Zend_Session_Namespace('importacao_adiantamento'); $params = $request->getParam('params'); $linhas = $ns->importacao_adiantamento; $ns->importacao_adiantamento = array_slice($linhas, 100, null, true); $sheetData = array_diff_key($linhas, $ns->importacao_adiantamento); $naoImportados = null; $importarBanco = null; try { switch ( $params['banco_id'] ) { case 'BMG': $bancoId = Model_Banco::bancoPorNome('BMG'); $importarBanco = new Core_Banco_Planilha_Bmg_Adiantamento($bancoId); $importarBanco->setDataSaldo($params['data_saldo']); $naoImportados = $importarBanco->importar($sheetData); break; case 'PAN': $bancoId = Model_Banco::bancoPorNome('PAN'); $importarBanco = new Core_Banco_Planilha_Pan_Adiantamento($bancoId); $importarBanco->setDataSaldo($params['data_saldo']); $naoImportados = $importarBanco->importar($sheetData); break; } } catch ( Exception $e ) { $this->_helper->json(array( 'error' => $e->getMessage() )); } $dados = array( 'readCompleted' => count($ns->importacao_adiantamento) > 0 ? false : true, 'result' => $naoImportados ); $error = new Zend_Session_Namespace('error'); if( !is_array($error->error) ){ $error->error = $naoImportados; } else { $tmp = array_merge($error->error, array_values($naoImportados)); $error->error = $tmp; } if( count($ns->importacao_adiantamento) <= 0 ){ $this->view->nao_baixados = $error->error; $error->unsetAll(); $this->_helper->json(array( 'content' => $this->view->render('sincronizacao/nao-baixados.phtml') )); } $this->_helper->json($dados); } public function listarTokenYuppiesAction() { $request = $this->getRequest(); $formFiltro = new Form_Filtro_SincYuppies(); $dados = array_filter($request->getPost()); $dbtable = new Model_SincYuppies(); if( $request->isPost() && $formFiltro->isValid($request->getPost()) ){ unset($dados['btn_filtrar']); $this->view->paginator = $dbtable->listar($dados); } $this->view->form = $formFiltro; } public function saveTokenYuppiesAction() { $form = new Form_SincYuppies(); $request = $this->getRequest(); $id = $request->getParam("id"); $sinc = new Model_SincYuppies(); $dbt = new Model_DbTable_SincYuppies(); if( $id ){ $form->populate($sinc->exibir($id)->toArray()); } if ($request->isPost() && $form->isValid($request->getPost())) { $sinc->setToken($request->getPost('token')); $sinc->setSistema($request->getPost('sistema')); $sinc->setSubestabelecidoId($request->getPost('subestabelecido_id')); $sinc->setDominio($request->getPost('dominio')); if( $id ){ $sinc->setId($id); } else { $token = $dbt->getSinc($sinc->getToken(), $sinc->getSistema()); if( $token ){ $this->_helper->flashMessenger(array( 'error' => 'Token já cadastrado.' )); $this->_redirect('sincronizacao/save-token-yuppies/'); } } $save = $sinc->salvar($sinc); if( $save > 0 ){ $this->_helper->flashMessenger(array( 'success' => 'Dados salvos com sucesso.' )); } else { $this->_helper->flashMessenger(array( 'error' => 'Nenhum registro foi alterado.' )); } $this->_redirect('sincronizacao/save-token-yuppies/id/' . $id); } $this->view->form = $form; } public function deleteTokenYuppiesAction() { $request = $this->getRequest(); $id = (int) $request->getParam('id'); if( $id > 0 ){ $dbtable = new Model_DbTable_SincYuppies(); $dbtable->delete("id = {$id}"); $this->_helper->flashMessenger(array( 'success' => 'Registro excluído com sucesso' )); } $this->_redirect("sincronizacao/listar-token-yuppies"); } public function sincYuppiesAction() { $request = $this->getRequest(); $naoImportados = $request->getPost("naoImportados"); if ($naoImportados) { $this->view->nao_baixados = $naoImportados; $this->_helper->json([ 'content' => $this->view->render('sincronizacao/nao-baixados.phtml') ]); } else { $contratos = $request->getPost("contratos"); $comissoes = $request->getPost("comissoes"); $id = $request->getPost("id"); $token = $request->getPost("token"); $sistema = $request->getPost("sistema"); $subestabelecidoId = $request->getPost("subestabelecidoId"); $sincronizacao = new Core_Contrato_Sincronizacao($id, $token, $sistema, $subestabelecidoId); if ($contratos) { $sincronizacao->importar($contratos); } if ($comissoes) { $sincronizacao->setarComissoes($comissoes); } } $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); } public function naoBaixadosAction() { $request = $this->getRequest(); $arquivo = $request->getParam('arquivo'); $falhaDb = new Model_DbTable_FalhaImportacao(); $naoImportados = $falhaDb->fetchAll("arquivo = '{$arquivo}'"); $this->view->nao_baixados = $naoImportados; } public function excluirNaoImportadosAction() { $request = $this->getRequest(); $registro = $request->getParam('id'); $arquivo = $request->getParam('arquivo'); $banco = $request->getParam("banco"); $falhaDb = new Model_DbTable_FalhaImportacao(); $excluido = $falhaDb->delete('id = ' . $registro); if( $arquivo != null ){ $this->_redirect("/sincronizacao/nao-baixados/arquivo/$arquivo"); } else { $this->_helper->flashMessenger(array( 'success' => "Erro excluído com sucesso." )); $this->_redirect('/sincronizacao/importar-direto'); } } public function sincStartConsigAction() { $request = $this->getRequest(); $form = new Form_SincronizarStartConsig(); $this->_helper->flashMessenger(array( 'info' => "O período mínimo para sincronização é de 1 dia e máximo de 7 dias." )); if( $request->isPost() ){ $dataInicial = new Zend_Date($request->getPost('data_de')); $dataFinal = new Zend_Date($request->getPost('data_a')); $diff = new Zend_Date($request->getPost('data_a')); $diff->subTimestamp($dataInicial); $dias = ceil(($diff->toValue()) / 60 / 60 / 24) + 1; if( $dataInicial->isEarlier($dataFinal) && $dias <= 7 ){ try { $service = new Core_Service_StartConsig($dataInicial, $dataFinal); $result = $service->sincronizar(); } catch ( Exception $exc ) { $this->_helper->flashMessenger(array( 'error' => $exc->getMessage() )); } if( isset($result) && count($result) > 1 ){ $this->view->nao_importados = $result['nao_importados']; $this->_helper->flashMessenger(array( 'success' => "Sincronização realizada com sucesso, {$result['total_importados']} contrato(s) atualizado(s)" )); } } else { $this->_helper->flashMessenger(array( 'error' => 'Por favor, informe um periodo válido. Máximo de 7 dias e mínimo de 1 dia' )); } } $this->view->form = $form; } public function deleteFalhasAction() { $request = $this->getRequest(); $falhas = $request->getParam('falhas'); $dbtable = new Model_DbTable_FalhaImportacao(); if( is_array($falhas) && count($falhas) > 0 ){ $cont = 0; foreach ( $falhas as $falhaId ) { $dbtable->delete("id = {$falhaId}"); $cont++; } if( $cont > 0 ){ $this->_helper->flashMessenger(array( 'success' => "{$cont} Erro(s) excluído(s) com sucesso." )); } else { $this->_helper->flashMessenger(array( 'alert' => "Nenhuma erro excluído." )); } } $this->_redirect('/sincronizacao/importar-direto'); } public function sincronizarBancoAction() { try { /** @var Service_Mailw $mailw */ $mailw = service('mailw'); $request = $this->getRequest(); $mailw->sincronizar((int) $request->getParam('banco')); $this->_helper->json(['sucess' => true]); } catch (DomainException $domainException) { $this->_helper->json(['erro' => $domainException->getMessage()]); } catch (Throwable $throwable) { $this->_helper->json(['erro' => $throwable->getMessage()]); } } }
💾 保存文件
← 返回文件管理器