/**
  * Consulta notas para exportar RPS
  */
 public function rpsConsultarAction()
 {
     parent::noTemplate();
     $aParametros = $this->getRequest()->getParams();
     /**
      * Verifica se foi informado mês e ano da competência
      */
     if (!empty($aParametros['mes_competencia']) && !empty($aParametros['ano_competencia'])) {
         $oContribuinte = $this->_session->contribuinte;
         $sCodigosContribuintes = implode(',', $oContribuinte->getContribuintes());
         $oPaginatorAdapter = new DBSeller_Controller_Paginator(Contribuinte_Model_Nota::getQuery(), 'Contribuinte_Model_Nota', 'Contribuinte\\Nota');
         /**
          * Monta a query de consulta
          */
         $oPaginatorAdapter->where("e.id_contribuinte in ({$sCodigosContribuintes})");
         $oPaginatorAdapter->andWhere("e.mes_comp = {$aParametros['mes_competencia']}");
         $oPaginatorAdapter->andWhere("e.ano_comp = {$aParametros['ano_competencia']}");
         if (!empty($aParametros['numero_rps'])) {
             $oPaginatorAdapter->andWhere("e.nota = {$aParametros['numero_rps']}");
         }
         $oPaginatorAdapter->orderBy('e.nota', 'DESC');
         /**
          * Monta a paginação do GridPanel
          */
         $oResultado = new Zend_Paginator($oPaginatorAdapter);
         $oResultado->setItemCountPerPage(10);
         $oResultado->setCurrentPageNumber($this->_request->getParam('page'));
         foreach ($oResultado as $oNota) {
             $oNota->oContribuinte = $oContribuinte;
             $oNota->lNaoGeraGuia = !$oNota->getEmite_guia();
             $oNota->lGuiaEmitida = Contribuinte_Model_Guia::existeGuia($oContribuinte, $oNota->getMes_comp(), $oNota->getAno_comp(), Contribuinte_Model_Guia::$DOCUMENTO_ORIGEM_NFSE);
             /**
              * Informações da nota substituta
              */
             $oNota->oNotaSubstituida = NULL;
             if ($oNota->getIdNotaSubstituida()) {
                 $oNota->oNotaSubstituida = Contribuinte_Model_Nota::getById($oNota->getIdNotaSubstituida());
             }
             /**
              * Informações da nota substituta
              */
             $oNota->oNotaSubstituta = NULL;
             if ($oNota->getIdNotaSubstituta()) {
                 $oNota->oNotaSubstituta = Contribuinte_Model_Nota::getById($oNota->getIdNotaSubstituta());
             }
         }
         /**
          * Valores da pesquisa para montar a paginação
          */
         if (is_array($aParametros)) {
             foreach ($aParametros as $sParametro => $sParametroValor) {
                 if ($sParametroValor) {
                     $sParametroValor = str_replace('/', '-', $sParametroValor);
                     $this->view->sBusca .= "{$sParametro}/{$sParametroValor}/";
                 }
             }
         }
         $this->view->oDadosNota = $oResultado;
     }
 }
 /**
  * Exibe a lista das guias geradas
  */
 public function consultaEmissaoAction()
 {
     if ($this->getRequest()->isPost()) {
         parent::noTemplate();
         $aRecord = array();
         $iLimit = $this->_request->getParam('rows') ? $this->_request->getParam('rows') : 10;
         $iPage = $this->_request->getParam('page') ? $this->_request->getParam('page') : 0;
         $oContribuinte = $this->_session->contribuinte;
         $iIdContribuinte = $oContribuinte->getIdUsuarioContribuinte();
         $aGuias = Contribuinte_Model_Guia::consultaGuiasDesif($iIdContribuinte);
         $aGuias = Contribuinte_Model_Guia::atualizaSituacaoGuias($aGuias);
         $oPaginatorAdapter = new DBSeller_Controller_PaginatorArray($aGuias);
         $aResultado = new Zend_Paginator($oPaginatorAdapter);
         $aResultado->setItemCountPerPage($iLimit);
         $aResultado->setCurrentPageNumber($iPage);
         $iTotal = $aResultado->getTotalItemCount();
         $iTotalPages = $aResultado->getPages()->pageCount;
         foreach ($aResultado as $oResultado) {
             $sSituacaoLabel = null;
             switch ($oResultado->getSituacao()) {
                 case 'a':
                     $sSituacaoLabel = 'label label-warning';
                     break;
                 case 'p':
                     $sSituacaoLabel = 'label label-success';
                     break;
                 case 'c':
                     $sSituacaoLabel = 'label label-important';
                     break;
                 case 'd':
                 case 'x':
                 default:
                     $sSituacaoLabel = 'label';
             }
             $oGuia = new StdClass();
             $oGuia->id = $oResultado->getId();
             $oGuia->competencia = $oResultado->getAnoComp() . $oResultado->getMesComp();
             $oGuia->competencia_label = $oResultado->getAnoComp() . '/' . $oResultado->getMesComp();
             $oGuia->data_vencimento = $oResultado->getVencimento()->format('d/m/Y');
             $oGuia->valor_corrigido = DBSeller_Helper_Number_Format::toMoney($oResultado->getValorCorrigido(), 2, 'R$');
             $oGuia->valor_historico = DBSeller_Helper_Number_Format::toMoney($oResultado->getValorHistorico(), 2, 'R$');
             $oGuia->situacao = $oResultado->getSituacao();
             $oGuia->situacao_label = "<span class='" . $sSituacaoLabel . "'>";
             $oGuia->situacao_label .= Contribuinte_Model_Guia::$SITUACAO[$oResultado->getSituacao()] . "</span>";
             $aRecord[] = $oGuia;
         }
         /**
          * Parametros de retorno do AJAX
          */
         $aRetornoJson = array('total' => $iTotalPages, 'page' => $iPage, 'records' => $iTotal, 'rows' => $aRecord);
         echo $this->getHelper('json')->sendJson($aRetornoJson);
     }
 }
 /**
  * Instancia o formulario de emissão de RPS
  *
  * @param string                                  $sCodigoVerificacao Código de Verificação
  * @param Contribuinte_Model_ContribuinteAbstract $oContribuinte      Dados do contribuinte
  * @return Contribuinte_Form_Nota
  */
 private function formNota($sCodigoVerificacao, Contribuinte_Model_ContribuinteAbstract $oContribuinte = NULL)
 {
     // Seta o contribuinte da sessão se não for enviado por parâmetro
     $oContribuinte = $oContribuinte ? $oContribuinte : $this->_session->contribuinte;
     $iIdContribuinte = $oContribuinte->getIdUsuarioContribuinte();
     $maxNota = 0;
     $maxGuia = 0;
     $aListaIdContribuinte = $oContribuinte->getContribuintes();
     // Calcula quantos dias no passado a nota pode ser emtidida
     $oParametrosPrefeitura = Administrativo_Model_Prefeitura::getDadosPrefeituraBase();
     $max = $oParametrosPrefeitura->getNotaRetroativa();
     $oUltimaGuia = Contribuinte_Model_Guia::getUltimaGuiaNota($oContribuinte);
     $uDataUltimaNota = Contribuinte_Model_Nota::getUltimaNotaEmitidaByContribuinte($aListaIdContribuinte);
     $dia = new DateTime();
     if ($oUltimaGuia != NULL) {
         if ($oUltimaGuia->getMesComp() + 1 > 12) {
             $iMes = 1;
         } else {
             $iMes = $oUltimaGuia->getMesComp();
         }
         $uDataUltimoDiaCompetencia = new Zend_Date("01/{$iMes}/{$oUltimaGuia->getAnoComp()}");
         $uDataUltimoDiaCompetencia->sub(1, Zend_date::DAY);
         $diff = $dia->diff(new DateTime($uDataUltimoDiaCompetencia->get('YYYY-MM-dd')), TRUE);
         $maxGuia = $diff->d < $max ? $diff->d : $max;
     }
     if ($uDataUltimaNota != NULL) {
         $diff = $dia->diff(new DateTime($uDataUltimaNota), TRUE);
         $maxNota = $diff->d < $max ? $diff->d : $max;
     }
     if ($maxNota - $maxGuia < $maxGuia) {
         $max = $maxGuia - 1;
     } else {
         if ($maxNota > 0) {
             $max = $maxNota;
         } else {
             $max = 0;
         }
     }
     $dia = $dia->sub(new DateInterval('P' . $max . 'D'));
     $oForm = new Contribuinte_Form_Nota($sCodigoVerificacao, $dia, '/contribuinte/rps/index', TRUE);
     if ($oContribuinte !== NULL) {
         $oParametros = Contribuinte_Model_ParametroContribuinte::getById($iIdContribuinte);
         $oForm->preencheParametros($oParametros);
     }
     return $oForm;
 }
 /**
  * Atualiza a situação das guias conforme uma coleção de numpre e numpar informados
  *
  * @param array $aGuias
  * @return array
  * @throws Exception
  */
 public static function atualizaSituacaoGuias(array $aGuias)
 {
     $aResultado = array();
     // Agrupa os Numpres e Numpars do Contribuinte
     foreach ($aGuias as $oGuia) {
         $sChaveNumpreNumpar = "{$oGuia->getNumpre()}/{$oGuia->getMesComp()}";
         $aDadosSituacao[$sChaveNumpreNumpar]['iNumpre'] = $oGuia->getNumpre();
         $aDadosSituacao[$sChaveNumpreNumpar]['iNumpar'] = $oGuia->getMesComp();
     }
     if (isset($aDadosSituacao)) {
         $aSitucao = Contribuinte_Model_GuiaEcidade::pesquisaSituacaoGuias($aDadosSituacao);
         // Altera a situacao da guia conforme as situacoes encontradas na pesquisa
         foreach ($aGuias as $oGuia) {
             $sChaveNumpreNumpar = "{$oGuia->getNumpre()}/{$oGuia->getMesComp()}";
             $sSituacao = $aSitucao[$sChaveNumpreNumpar];
             if (!isset(self::$WS_NFSE_SITUACAO[$sSituacao])) {
                 throw new Exception("Situação de débito {$sSituacao} não mapeada para o modelo Guia");
             }
             $oGuia->setSituacao(self::$WS_NFSE_SITUACAO[$sSituacao]);
             $oComparaData = new Zend_Date("01-{$oGuia->getMesComp()}-{$oGuia->getAnoComp()}");
             $oComparaData->add(1, 'MM');
             // Verifica se a guia de débito foi cancelada no E-cidade remove o vinculo da guia, caso seja NFSE e não
             // estiver um mês retroativo apenas exibe como "Quitada Manualmente"
             if ($oComparaData->compare(new Zend_Date(), 'MM/yyyy') == 0 && $oGuia->getTipoDocumentoOrigem() == self::$DOCUMENTO_ORIGEM_NFSE || $oGuia->getTipoDocumentoOrigem() == self::$DOCUMENTO_ORIGEM_DMS) {
                 if (!empty($sSituacao) && $sSituacao == 'CANCELADO') {
                     $aAtributos = array('set' => array('guia' => NULL), 'where' => array('guia' => $oGuia->getEntity()));
                     Contribuinte_Model_DesifContaGuia::update($aAtributos['set'], $aAtributos['where']);
                     Contribuinte_Model_Guia::removeGuiaCancelada($oGuia);
                 } else {
                     $aResultado[] = $oGuia;
                 }
             } else {
                 $aResultado[] = $oGuia;
             }
         }
     }
     return $aResultado;
 }
 /**
  * Método para ver se a nota pode ser cancelada ou não
  * @param object $oContribuinte Model do contribuinte
  * @return boolean
  */
 public function podeCancelar($oContribuinte)
 {
     $oNota = $this->getEntity();
     $lExisteGuia = Contribuinte_Model_Guia::existeGuia($oContribuinte, $oNota->getMes_comp(), $oNota->getAno_comp(), Contribuinte_Model_Guia::$DOCUMENTO_ORIGEM_NFSE);
     $oSolicitacaoCancelamento = Contribuinte_Model_SolicitacaoCancelamento::getByAttribute('nota', $oNota);
     $uDataUltimaNota = Contribuinte_Model_Nota::getUltimaNotaEmitidaByContribuinte($oContribuinte->getContribuintes());
     $oDataUltimaNota = new DateTime($uDataUltimaNota);
     $oCompetencia = new Contribuinte_Model_Competencia($oNota->getAno_comp(), $oNota->getMes_comp(), $oContribuinte);
     $aCompetenciaSemMovimento = $oCompetencia->getDeclaracaoSemMovimento();
     if ($oNota->getAno_comp() < $oDataUltimaNota->format('Y')) {
         return FALSE;
     } else {
         if ($oNota->getAno_comp() == $oDataUltimaNota->format('Y') && $oNota->getMes_comp() < $oDataUltimaNota->format('m')) {
             return FALSE;
         } else {
             if ($oNota->getCancelada() || $lExisteGuia || $oNota->getImportada() || !empty($oSolicitacaoCancelamento)) {
                 return FALSE;
             } else {
                 if (isset($aCompetenciaSemMovimento[0]) && $oNota->getAno_comp() < $aCompetenciaSemMovimento[0]->ano) {
                     return FALSE;
                 } else {
                     if (isset($aCompetenciaSemMovimento[0]) && $oNota->getAno_comp() == $aCompetenciaSemMovimento[0]->ano && $oNota->getMes_comp() <= $aCompetenciaSemMovimento[0]->mes) {
                         return FALSE;
                     }
                 }
             }
         }
     }
     return TRUE;
 }
 /**
  * Geração do relatório de NFSe's
  */
 public function nfseGerarAction()
 {
     parent::noLayout();
     $aValidacaoFormulario = self::validarFormulario();
     if (is_array($aValidacaoFormulario)) {
         exit($this->getHelper('json')->sendJson($aValidacaoFormulario));
     }
     try {
         // Parâmetros do formulário
         $sCompetenciaInicial = $this->getRequest()->getParam('data_competencia_inicial');
         $sCompetenciaFinal = $this->getRequest()->getParam('data_competencia_final');
         $sPrestadorCnpj = $this->getRequest()->getParam('prestador_cnpj');
         $lGuiaEmitida = $this->getRequest()->getParam('guia_emitida') == 1 ? TRUE : FALSE;
         $sGuiaEmitida = $lGuiaEmitida ? 'Sim' : 'Não';
         // Prestador
         $oPrestador = Contribuinte_Model_Contribuinte::getByCpfCnpj($sPrestadorCnpj);
         // Separa os meses e anos
         $iCompetenciaInicialMes = intval(substr($sCompetenciaInicial, 0, 2));
         $iCompetenciaFinalMes = intval(substr($sCompetenciaFinal, 0, 2));
         $iCompetenciaInicialAno = intval(substr($sCompetenciaInicial, -4));
         $iCompetenciaFinalAno = intval(substr($sCompetenciaFinal, -4));
         $sNomeArquivo = 'relatorio_nfse_' . date('YmdHis') . '.pdf';
         $oPdf = new Fiscal_Model_Relatoriopdfmodelo1('P');
         $oPdf->Open(APPLICATION_PATH . "/../public/tmp/{$sNomeArquivo}");
         $oPdf->setLinhaFiltro('Relatório de NFSe');
         $oPdf->setLinhaFiltro('');
         $oPdf->setLinhaFiltro('FILTROS:');
         $oPdf->setLinhaFiltro("  CNPJ Prestador {$sPrestadorCnpj}");
         $oPdf->setLinhaFiltro("  Competência de {$sCompetenciaInicial} à {$sCompetenciaFinal}");
         $oPdf->setLinhaFiltro("  Guia Emitida? {$sGuiaEmitida}");
         $oPdf->carregaDados();
         $oEntityManager = Zend_Registry::get('em');
         $oConexao = $oEntityManager->getConnection();
         try {
             $lExistemRegistros = FALSE;
             // Prepara a consulta na base de dados
             $sSql = self::getSqlRelatorio2($lGuiaEmitida);
             $oStatement = $oConexao->prepare($sSql);
             // Limpa as máscaras do CNPJ
             $sPrestadorCnpj = DBSeller_Helper_Number_Format::getNumbers($sPrestadorCnpj);
             // Varre os anos
             for ($iAno = 0; $iAno <= $iCompetenciaFinalAno - $iCompetenciaInicialAno; $iAno++) {
                 $iAnoLoop = intval($iCompetenciaInicialAno) + $iAno;
                 // Varre os meses
                 for ($iMesLoop = 1; $iMesLoop <= 12; $iMesLoop++) {
                     // Ignora os meses anteriores e seguintes aos meses inicial e final
                     if ($iAnoLoop == $iCompetenciaInicialAno && $iMesLoop < $iCompetenciaInicialMes || $iAnoLoop == $iCompetenciaFinalAno && $iMesLoop > $iCompetenciaFinalMes) {
                         continue;
                     }
                     // Executa a consulta na base de dados com os parâmetros: cnpj, mês e ano da competência
                     $oStatement->execute(array($iMesLoop, $iAnoLoop, $sPrestadorCnpj, $iMesLoop, $iAnoLoop, $sPrestadorCnpj));
                     // Ignora loop caso não possua registros
                     if ($oStatement->rowCount() < 1) {
                         continue;
                     }
                     $lExistemRegistros = TRUE;
                     // Zera os dados
                     $aRelatorio = NULL;
                     $aDadosRelatorio = NULL;
                     // Monta os dados do relatório com o índice para ordenação
                     do {
                         // Busca os dados na base de dados
                         $aRelatorio = $oStatement->fetch();
                         // Ignora a busca caso não existam resultados
                         if (empty($aRelatorio)) {
                             continue;
                         }
                         // Dados do Prestador
                         $sPrestadorCnpjCpf = $aRelatorio['prestador_cnpjcpf'];
                         $sPrestadorCnpjCpf = DBSeller_Helper_Number_Format::maskCPF_CNPJ($sPrestadorCnpjCpf);
                         $sPrestadorInscricaoMunicipal = $aRelatorio['prestador_inscricao_municipal'];
                         $sPrestadorRazaoSocial = $aRelatorio['prestador_razao_social'];
                         $sPrestadorRazaoSocial = DBSeller_Helper_String_Format::wordsCap($sPrestadorRazaoSocial);
                         $sPrestadorMunicipioUf = $aRelatorio['prestador_endereco_municipio'];
                         $sPrestadorMunicipioUf = DBSeller_Helper_String_Format::wordsCap($sPrestadorMunicipioUf);
                         $sPrestadorMunicipioUf = "{$sPrestadorMunicipioUf}/{$aRelatorio['prestador_endereco_uf']}";
                         $sPrestadorTelefone = $aRelatorio['prestador_contato_telefone'];
                         $sPrestadorTelefone = DBSeller_Helper_Number_Format::maskPhoneNumber($sPrestadorTelefone);
                         $sPrestadorDocumentoNumero = $aRelatorio['prestador_documento_numero'];
                         $oPrestadorDocumentoData = new DateTime($aRelatorio['prestador_documento_data']);
                         $sPrestadorDocumentoTipo = $aRelatorio['prestador_documento_tipo'];
                         $sPrestadorDocumentoValor = $aRelatorio['prestador_valor_servico'];
                         $sPrestadorDocumentoValor = DBSeller_Helper_Number_Format::toMoney($sPrestadorDocumentoValor, 2);
                         $sPrestadorDocumentoAliquota = $aRelatorio['prestador_valor_aliquota'];
                         $sPrestadorDocumentoAliquota = DBSeller_Helper_Number_Format::toMoney($sPrestadorDocumentoAliquota, 2);
                         $sPrestadorDocumentoIss = $aRelatorio['prestador_valor_iss'];
                         $sPrestadorDocumentoIss = DBSeller_Helper_Number_Format::toMoney($sPrestadorDocumentoIss, 2);
                         $sPrestadorDocumentoIssRetido = $aRelatorio['prestador_iss_retido'] ? 'Não' : 'Sim';
                         // Dados Tomador
                         $sTomadorCnpjCpf = $aRelatorio['tomador_cnpjcpf'];
                         $sTomadorCnpjCpf = DBSeller_Helper_Number_Format::maskCPF_CNPJ($sTomadorCnpjCpf);
                         $sTomadorInscricaoMunicipal = $aRelatorio['tomador_inscricao_municipal'];
                         $sTomadorRazaoSocial = $aRelatorio['tomador_razao_social'];
                         $sTomadorRazaoSocial = DBSeller_Helper_String_Format::wordsCap($sTomadorRazaoSocial);
                         $sTomadorMunicipioUf = $aRelatorio['tomador_endereco_municipio'];
                         $sTomadorMunicipioUf = DBSeller_Helper_String_Format::wordsCap($sTomadorMunicipioUf);
                         $sTomadorMunicipioUf = "{$sTomadorMunicipioUf}/{$aRelatorio['tomador_endereco_uf']}";
                         $sTomadorTelefone = $aRelatorio['tomador_contato_telefone'];
                         $sTomadorTelefone = DBSeller_Helper_Number_Format::maskPhoneNumber($sTomadorTelefone);
                         $sTomadorDocumentoNumero = $aRelatorio['tomador_documento_numero'];
                         $oTomadorDocumentoData = new DateTime($aRelatorio['tomador_documento_data']);
                         $sTomadorDocumentoTipo = $aRelatorio['tomador_documento_tipo'];
                         $sTomadorDocumentoValor = $aRelatorio['tomador_valor_servico'];
                         $sTomadorDocumentoValor = DBSeller_Helper_Number_Format::toMoney($sTomadorDocumentoValor, 2);
                         $sTomadorDocumentoAliquota = $aRelatorio['tomador_valor_aliquota'];
                         $sTomadorDocumentoAliquota = DBSeller_Helper_Number_Format::toMoney($sTomadorDocumentoAliquota, 2);
                         $sTomadorDocumentoIss = $aRelatorio['tomador_valor_iss'];
                         $sTomadorDocumentoIss = DBSeller_Helper_Number_Format::toMoney($sTomadorDocumentoIss, 2);
                         $sTomadorDocumentoIssRetido = $aRelatorio['tomador_iss_retido'] ? 'Sim' : 'Não';
                         // Descrição do tipo de documento
                         $oPrestadorDocumentoTipo = Contribuinte_Model_Nota::getTipoNota($sPrestadorDocumentoTipo);
                         $sPrestadorDocumentoTipo = DBSeller_Helper_String_Format::wordsCap($oPrestadorDocumentoTipo->descricao);
                         $oTomadorDocumentoTipo = Contribuinte_Model_Nota::getTipoNota($sTomadorDocumentoTipo);
                         $sTomadorDocumentoTipo = DBSeller_Helper_String_Format::wordsCap($oTomadorDocumentoTipo->descricao);
                         // Indice para evitar a repetição do cabeçalho por prestador+tomador
                         $sIndiceRelatorio = "{$aRelatorio['prestador_cnpjcpf']}_{$aRelatorio['tomador_cnpjcpf']}";
                         // Dados do relatório
                         $aDadosRelatorio[$sIndiceRelatorio]['prestador_cnpjcpf'] = $sPrestadorCnpjCpf;
                         $aDadosRelatorio[$sIndiceRelatorio]['prestador_inscricao_municipal'] = $sPrestadorInscricaoMunicipal;
                         $aDadosRelatorio[$sIndiceRelatorio]['prestador_razao_social'] = utf8_decode($sPrestadorRazaoSocial);
                         $aDadosRelatorio[$sIndiceRelatorio]['prestador_municipio_uf'] = utf8_decode($sPrestadorMunicipioUf);
                         $aDadosRelatorio[$sIndiceRelatorio]['prestador_telefone'] = $sPrestadorTelefone;
                         $aDadosRelatorio[$sIndiceRelatorio]['tomador_cnpjcpf'] = $sTomadorCnpjCpf;
                         $aDadosRelatorio[$sIndiceRelatorio]['tomador_inscricao_municipal'] = $sTomadorInscricaoMunicipal;
                         $aDadosRelatorio[$sIndiceRelatorio]['tomador_razao_social'] = utf8_decode($sTomadorRazaoSocial);
                         $aDadosRelatorio[$sIndiceRelatorio]['tomador_municipio_uf'] = utf8_decode($sTomadorMunicipioUf);
                         $aDadosRelatorio[$sIndiceRelatorio]['tomador_telefone'] = $sTomadorTelefone;
                         $aDadosRelatorio[$sIndiceRelatorio]['documentos'][] = array('prestador_doc_numero' => utf8_decode($sPrestadorDocumentoNumero), 'prestador_doc_data' => $oPrestadorDocumentoData, 'prestador_doc_tipo' => utf8_decode($sPrestadorDocumentoTipo), 'prestador_doc_valor_servico' => utf8_decode($sPrestadorDocumentoValor), 'prestador_doc_valor_aliquota' => utf8_decode($sPrestadorDocumentoAliquota), 'prestador_doc_valor_iss' => utf8_decode($sPrestadorDocumentoIss), 'prestador_doc_iss_retido' => utf8_decode($sPrestadorDocumentoIssRetido), 'tomador_doc_numero' => utf8_decode($sTomadorDocumentoNumero), 'tomador_doc_data' => $oTomadorDocumentoData, 'tomador_doc_tipo' => utf8_decode($sTomadorDocumentoTipo), 'tomador_doc_valor_servico' => utf8_decode($sTomadorDocumentoValor), 'tomador_doc_valor_aliquota' => utf8_decode($sTomadorDocumentoAliquota), 'tomador_doc_valor_iss' => utf8_decode($sTomadorDocumentoIss), 'tomador_doc_iss_retido' => utf8_decode($sTomadorDocumentoIssRetido));
                     } while ($aRelatorio);
                     // Ordena a lista de documentos por número
                     $aDocumentosOrdenados = DBSeller_Helper_Array_Abstract::ordenarPorIndice($aDadosRelatorio[$sIndiceRelatorio]['documentos'], 'prestador_doc_numero');
                     $aDadosRelatorio[$sIndiceRelatorio]['documentos'] = $aDocumentosOrdenados;
                     // Ordena os dados do relatorio
                     if (isset($aDadosRelatorio) && is_array($aDadosRelatorio)) {
                         $aDadosRelatorio = DBSeller_Helper_Array_Abstract::ordenarPorIndice($aDadosRelatorio, 'prestador_cnpjcpf');
                     } else {
                         throw new Exception($this->translate->_('Erro ao gerar o relatório.'));
                     }
                     // Calcula a metade da página
                     $iMeiaPaginaX = $oPdf->w / 2 - $oPdf->lMargin;
                     // Percorre os dados do relatório
                     foreach ($aDadosRelatorio as $aRelatorioOrdenado) {
                         // Formata o texto da competência
                         $sCompetencia = str_pad($iMesLoop, 2, 0, STR_PAD_LEFT) . "/{$iAnoLoop}";
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(20, 5, utf8_decode('Competência: '));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell(22, 5, $sCompetencia);
                         // Dados da guia do prestador
                         if ($lGuiaEmitida) {
                             $oGuiaPrestador = Contribuinte_Model_Guia::getByCompetenciaAndContribuinte($iAnoLoop, $iMesLoop, $oPrestador, Contribuinte_Model_Guia::$PRESTADOR);
                             if (is_array($oGuiaPrestador) && count($oGuiaPrestador) > 0 && $oGuiaPrestador[0] instanceof Contribuinte_Model_Guia) {
                                 $oGuiaPrestador = reset($oGuiaPrestador);
                                 $oPdf->SetFont('Arial', 'B', 8);
                                 $oPdf->Cell(13, 5, utf8_decode('Numpre: '));
                                 $oPdf->SetFont('Arial', '', 8);
                                 $oPdf->Cell(20, 5, $oGuiaPrestador->getNumpre());
                             }
                         }
                         $oPdf->Ln();
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell($iMeiaPaginaX, 5, 'PRESTADOR', 1, 0, 'L', 1);
                         $oPdf->Cell($iMeiaPaginaX, 5, 'TOMADOR', 1, 0, 'L', 1);
                         $oPdf->Ln();
                         $oPdf->Rect($oPdf->GetX(), $oPdf->GetY(), $iMeiaPaginaX, 25);
                         $oPdf->Rect($iMeiaPaginaX + $oPdf->lMargin, $oPdf->GetY(), $iMeiaPaginaX, 25);
                         $oPdf->Ln(2);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(28, 4, utf8_decode('Inscrição Municipal:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 28, 4, $aRelatorioOrdenado['prestador_inscricao_municipal']);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(28, 4, utf8_decode('Inscrição Municipal:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 28, 4, $aRelatorioOrdenado['tomador_inscricao_municipal']);
                         $oPdf->Ln();
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(16, 4, 'CPNJ/CPF:');
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 16, 4, $aRelatorioOrdenado['prestador_cnpjcpf']);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(16, 4, 'CPNJ/CPF:');
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 16, 4, $aRelatorioOrdenado['tomador_cnpjcpf']);
                         $oPdf->Ln();
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(20, 4, utf8_decode('Razão Social:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 20, 4, $aRelatorioOrdenado['prestador_razao_social']);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(20, 4, utf8_decode('Razão Social:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 20, 4, $aRelatorioOrdenado['tomador_razao_social']);
                         $oPdf->Ln();
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(20, 4, utf8_decode('Município/UF:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 20, 4, $aRelatorioOrdenado['prestador_municipio_uf']);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(20, 4, utf8_decode('Município/UF:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 20, 4, $aRelatorioOrdenado['tomador_municipio_uf']);
                         $oPdf->Ln(5);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(14, 4, utf8_decode('Telefone:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 14, 4, $aRelatorioOrdenado['prestador_telefone']);
                         $oPdf->SetFont('Arial', 'B', 8);
                         $oPdf->Cell(14, 4, utf8_decode('Telefone:'));
                         $oPdf->SetFont('Arial', '', 8);
                         $oPdf->Cell($iMeiaPaginaX - 14, 4, $aRelatorioOrdenado['tomador_telefone']);
                         $oPdf->Ln(5);
                         if (count($aRelatorioOrdenado['documentos']) > 0) {
                             $aLarguraColuna = array(25, 14, 16, 51, 26, 18, 27, 13);
                             $oPdf->SetFont('Arial', 'B', 8);
                             $oPdf->Cell($aLarguraColuna[0], 5, utf8_decode('Nº do Documento'), 1, 0, 'C', 1);
                             $oPdf->Cell($aLarguraColuna[1], 5, utf8_decode('Origem'), 1, 0, 'L', 1);
                             $oPdf->Cell($aLarguraColuna[2], 5, utf8_decode('Data'), 1, 0, 'L', 1);
                             $oPdf->Cell($aLarguraColuna[3], 5, utf8_decode('Tipo de Documento'), 1, 0, 'L', 1);
                             $oPdf->Cell($aLarguraColuna[4], 5, utf8_decode('Valor Serviço (R$)'), 1, 0, 'R', 1);
                             $oPdf->Cell($aLarguraColuna[5], 5, utf8_decode('Alíquota (%)'), 1, 0, 'R', 1);
                             $oPdf->Cell($aLarguraColuna[6], 5, utf8_decode('Valor Imposto (R$)'), 1, 0, 'R', 1);
                             $oPdf->Cell($aLarguraColuna[7], 5, utf8_decode('Retido'), 1, 0, 'L', 1);
                             $oPdf->Ln(5);
                             // Flag para exibir a cor de fundo nas células
                             $iFundoLinha = 0;
                             // Percorre a lista de documentos
                             foreach ($aRelatorioOrdenado['documentos'] as $aDocumento) {
                                 $lFundoLinha = $iFundoLinha++ % 2 == 0 ? 0 : 1;
                                 // Cor de fundo das linhas (zebra)
                                 $oPdf->SetFont('Arial', '', 8);
                                 $oPdf->MultiCell($aLarguraColuna[0], 10, $aDocumento['prestador_doc_numero'], 1, 'C', $lFundoLinha);
                                 $oPdf->SetY($oPdf->getY() - 10);
                                 $oPdf->SetX($oPdf->getX() + $aLarguraColuna[0]);
                                 $oPdf->Cell($aLarguraColuna[1], 5, 'Prestador', 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[2], 5, $aDocumento['prestador_doc_data']->format('d/m/Y'), 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[3], 5, $aDocumento['prestador_doc_tipo'], 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[4], 5, $aDocumento['prestador_doc_valor_servico'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[5], 5, $aDocumento['prestador_doc_valor_aliquota'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[6], 5, $aDocumento['prestador_doc_valor_iss'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[7], 5, $aDocumento['prestador_doc_iss_retido'], 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Ln(5);
                                 $oPdf->Cell($aLarguraColuna[0], 5, '');
                                 $oPdf->Cell($aLarguraColuna[1], 5, 'Tomador', 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[2], 5, $aDocumento['tomador_doc_data']->format('d/m/Y'), 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[3], 5, $aDocumento['tomador_doc_tipo'], 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[4], 5, $aDocumento['tomador_doc_valor_servico'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[5], 5, $aDocumento['tomador_doc_valor_aliquota'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[6], 5, $aDocumento['tomador_doc_valor_iss'], 1, 0, 'R', $lFundoLinha);
                                 $oPdf->Cell($aLarguraColuna[7], 5, $aDocumento['tomador_doc_iss_retido'], 1, 0, 'L', $lFundoLinha);
                                 $oPdf->Ln(5);
                             }
                             $oPdf->Ln();
                         }
                     }
                 }
             }
         } catch (Exception $oErro) {
             throw new Exception($oErro->getMessage());
         }
         // Verifica se existem registro para gerar o relatório
         if ($lExistemRegistros) {
             $oPdf->Output();
         } else {
             throw new Exception($this->translate->_('Nenhum registro encontrado.'));
         }
         $aRetornoJson['status'] = TRUE;
         $aRetornoJson['url'] = $this->view->baseUrl("/tmp/{$sNomeArquivo}");
         $aRetornoJson['success'] = $this->translate->_('Relatório gerado com sucesso.');
     } catch (Exception $oErro) {
         $aRetornoJson['status'] = FALSE;
         $aRetornoJson['error'][] = $oErro->getMessage();
     }
     echo $this->getHelper('json')->sendJson($aRetornoJson);
 }
 /**
  * Consulta as guias pagas pelo optante simples
  *
  * @param Contribuinte_Model_ContribuinteAbstract $oContribuinte
  */
 public function consultaEmissaoOptanteSimples(Contribuinte_Model_ContribuinteAbstract $oContribuinte)
 {
     $aGuias = Contribuinte_Model_Guia::getGuiasPagasOptanteSimples($oContribuinte);
     $oPaginatorAdapter = new DBSeller_Controller_PaginatorArray($aGuias);
     $oPaginator = new Zend_Paginator($oPaginatorAdapter);
     $oPaginator->setItemCountPerPage(10);
     $oPaginator->setCurrentPageNumber($this->_request->getParam('page'));
     $this->view->oGuias = $oPaginator;
     $this->_helper->viewRenderer('consulta-optantes-simples');
 }
 /**
  * Define os dados do contribuinte
  *
  * @param Contribuinte_Model_Contribuinte $oContribuinte
  * @param                                 $iMesCompetencia
  * @param                                 $iAnoCompetencia
  * @param bool                            $lLivroFiscal
  */
 public function setDadosContribuinte(Contribuinte_Model_Contribuinte $oContribuinte, $iMesCompetencia, $iAnoCompetencia, $lLivroFiscal = TRUE)
 {
     if (!$lLivroFiscal) {
         $this->AddPage();
     }
     // Mês e ano da competnência por extenso
     $sCompetencia = DBSeller_Helper_Date_Date::mesExtenso($iMesCompetencia) . "/{$iAnoCompetencia}";
     $sCompetencia = utf8_decode($sCompetencia);
     // Mostra os campos referentes à guia somente para contribuintes NFSe
     if ($oContribuinte->getTipoEmissao() == Contribuinte_Model_Contribuinte::TIPO_EMISSAO_NOTA || !$lLivroFiscal) {
         // Situação da Guia
         $sDataFechamentoGuia = '-';
         $sSituacaoGuia = 'Em aberto';
         $oGuia = new Contribuinte_Model_Guia();
         $aGuia = $oGuia->getByCompetenciaAndContribuinte($iAnoCompetencia, $iMesCompetencia, $oContribuinte, Contribuinte_Model_Guia::$PRESTADOR);
         if (count($aGuia) > 0) {
             $oGuia = $aGuia[0]->getEntity();
             $sDataFechamentoGuia = $oGuia->getDataFechamento()->format('d/m/Y');
             $sSituacaoGuia = Contribuinte_Model_Guia::$SITUACAO[$oGuia->getSituacao()];
         }
         $aLarguraCelulas = array(57, 55, 55, 55, 55, 45, 50);
         $this->SetFont('Arial', 'B', 8);
         if ($lLivroFiscal) {
             // Mostra CGM ou Inscrição Municipal
             if ($oContribuinte->getCgm()) {
                 $this->Cell($aLarguraCelulas[0], 5, utf8_decode('CGM / Inscrição Municipal:'), 1);
             } else {
                 $this->Cell($aLarguraCelulas[0], 5, utf8_decode('Inscrição Municipal:'), 1);
             }
             $this->Cell($aLarguraCelulas[1], 5, utf8_decode('CPF / CNPJ:'), 1);
             $this->Cell($aLarguraCelulas[2], 5, utf8_decode('Mês Referência:'), 1);
             $this->Cell($aLarguraCelulas[3], 5, utf8_decode('Situação:'), 1);
             $this->Cell($aLarguraCelulas[4], 5, utf8_decode('Encerramento:'), 1);
             $this->Ln();
             $this->SetFont('Arial', NULL, 8);
             // Mostra CGM ou Inscrição Municipal
             if ($oContribuinte->getCgm()) {
                 $this->Cell($aLarguraCelulas[0], 5, $oContribuinte->getCgm(), 1);
             } else {
                 $this->Cell($aLarguraCelulas[0], 5, $oContribuinte->getInscricaoMunicipal(), 1);
             }
             $sCpfCnpjContribuinte = DBSeller_Helper_Number_Format::maskCPF_CNPJ($oContribuinte->getCgcCpf());
             $this->Cell($aLarguraCelulas[1], 5, $sCpfCnpjContribuinte, 1);
             $this->Cell($aLarguraCelulas[2], 5, $sCompetencia, 1);
             $this->Cell($aLarguraCelulas[3], 5, $sSituacaoGuia, 1);
             $this->Cell($aLarguraCelulas[4], 5, $sDataFechamentoGuia, 1);
             $this->Ln(6);
         } else {
             // Mostra CGM ou Inscrição Municipal
             if ($oContribuinte->getCgm()) {
                 $this->Cell($aLarguraCelulas[1], 5, utf8_decode('CGM / Inscrição Municipal:'), 1);
             } else {
                 $this->Cell($aLarguraCelulas[1], 5, utf8_decode('Inscrição Municipal:'), 1);
             }
             $this->Cell($aLarguraCelulas[6], 5, utf8_decode('CPF / CNPJ:'), 1);
             $this->Cell($aLarguraCelulas[5], 5, utf8_decode('Competencia Inicial:'), 1);
             $this->Cell($aLarguraCelulas[5], 5, utf8_decode('Competencia Final:'), 1);
             $this->Cell($aLarguraCelulas[5], 5, utf8_decode('Situação:'), 1);
             $this->Cell(0, 5, utf8_decode('Encerramento:'), 1);
             $this->Ln();
             $this->SetFont('Arial', NULL, 8);
             // Mostra CGM ou Inscrição Municipal
             if ($oContribuinte->getCgm()) {
                 $this->Cell($aLarguraCelulas[1], 5, $oContribuinte->getCgm(), 1);
             } else {
                 $this->Cell($aLarguraCelulas[1], 5, $oContribuinte->getInscricaoMunicipal(), 1);
             }
             $sCpfCnpjContribuinte = DBSeller_Helper_Number_Format::maskCPF_CNPJ($oContribuinte->getCgcCpf());
             $sCompetenciaInicial = $iMesCompetencia['inicial'] . '/' . $iAnoCompetencia['inicial'];
             $sCompetenciaFinal = $iMesCompetencia['final'] . '/' . $iAnoCompetencia['final'];
             $this->Cell($aLarguraCelulas[6], 5, $sCpfCnpjContribuinte, 1);
             $this->Cell($aLarguraCelulas[5], 5, $sCompetenciaInicial, 1);
             $this->Cell($aLarguraCelulas[5], 5, $sCompetenciaFinal, 1);
             $this->Cell($aLarguraCelulas[5], 5, $sSituacaoGuia, 1);
             $this->Cell(0, 5, $sDataFechamentoGuia, 1);
             $this->Ln(6);
         }
     } else {
         $aLarguraCelulas = array(93, 92, 92);
         $this->SetFont('Arial', 'B', 8);
         // Mostra CGM ou Inscrição Municipal
         if ($oContribuinte->getCgm()) {
             $this->Cell($aLarguraCelulas[0], 5, utf8_decode('CGM / Inscrição Municipal:'), 1);
         } else {
             $this->Cell($aLarguraCelulas[0], 5, utf8_decode('Inscrição Municipal:'), 1);
         }
         $this->Cell($aLarguraCelulas[1], 5, utf8_decode('CPF / CNPJ:'), 1);
         $this->Cell($aLarguraCelulas[2], 5, utf8_decode('Mês Referência:'), 1);
         $this->Ln();
         $this->SetFont('Arial', NULL, 8);
         // Mostra CGM ou Inscrição Municipal
         if ($oContribuinte->getCgm()) {
             $this->Cell($aLarguraCelulas[0], 5, $oContribuinte->getCgm(), 1);
         } else {
             $this->Cell($aLarguraCelulas[0], 5, $oContribuinte->getInscricaoMunicipal(), 1);
         }
         $this->Cell($aLarguraCelulas[1], 5, DBSeller_Helper_Number_Format::maskCPF_CNPJ($oContribuinte->getCgcCpf()), 1);
         $this->Cell($aLarguraCelulas[2], 5, $sCompetencia, 1);
         $this->Ln(6);
     }
     $this->SetFont('Arial', 'B', 8);
     $this->Cell(0, 5, utf8_decode('Razão Social:'), 1);
     $this->Ln();
     $this->SetFont('Arial', NULL, 8);
     $this->Cell(0, 5, utf8_decode($oContribuinte->getNome()), 1);
     $this->Ln(6);
     $this->SetFont('Arial', 'B', 8);
     $this->Cell(242, 5, utf8_decode('Endereço:'), 1);
     $this->Cell(35, 5, utf8_decode('Número:'), 1);
     $this->Ln();
     $this->SetFont('Arial', NULL, 8);
     $this->Cell(242, 5, utf8_decode($oContribuinte->getDescricaoLogradouro()), 1);
     $this->Cell(35, 5, utf8_decode($oContribuinte->getLogradouroNumero()), 1);
     $this->Ln(6);
     $this->SetFont('Arial', 'B', 8);
     $this->Cell(90, 5, utf8_decode('Complemento:'), 1);
     $this->Cell(80, 5, utf8_decode('Bairro:'), 1);
     $this->Cell(72, 5, utf8_decode('Cidade:'), 1);
     $this->Cell(35, 5, utf8_decode('Estado:'), 1);
     $this->Ln();
     $this->SetFont('Arial', NULL, 8);
     $this->Cell(90, 5, utf8_decode($oContribuinte->getLogradouroComplemento()), 1);
     $this->Cell(80, 5, utf8_decode($oContribuinte->getLogradouroBairro()), 1);
     $this->Cell(72, 5, utf8_decode($oContribuinte->getDescricaoMunicipio()), 1);
     $this->Cell(35, 5, utf8_decode($oContribuinte->getEstado()), 1);
     $this->Ln(6);
     $oDataAtual = new DateTime();
     $sEnderecoIp = $_SERVER['REMOTE_ADDR'];
     $this->SetFont('Arial', 'B', 8);
     $this->Cell(139, 5, utf8_decode("Endereço IP: {$sEnderecoIp}"), 1);
     $this->Cell(138, 5, utf8_decode("Data da impressão: {$oDataAtual->format('d/m/Y H:i:s')}"), 1);
     $this->Ln(7);
 }
 /**
  * Verifica se existe guia emitida
  *
  * @return boolean
  */
 public function existeGuiaEmitida()
 {
     return Contribuinte_Model_Guia::existeGuia($this->oContribuinte, $this->iMesCompetencia, $this->iAnoCompetencia, 10);
 }
 /**
  * Metodo responsavel por criar as guias dms do prestador
  *
  * @param Contribuinte_Model_Dms $oDms
  * @param                        $sDataPagamento
  * @return StdClass
  */
 public static function gerarGuiaDmsPrestador(Contribuinte_Model_Dms $oDms, $sDataPagamento)
 {
     try {
         $oDoctrine = Zend_Registry::get('em');
         $oDoctrine->getConnection()->beginTransaction();
         $aNotas = array();
         foreach ($oDms->getDmsNotas() as $oDadosNota) {
             $oNota = new Contribuinte_Model_DmsNota($oDadosNota);
             // Ignora notas prestadas e retidas pelo tomador
             if ($oDms->getOperacao() == 's' && $oNota->getServicoImpostoRetido() == TRUE) {
                 continue;
             }
             // Ignora notas tomadas e retidas pelo tomador
             if ($oDms->getOperacao() == 'e' && $oNota->getServicoImpostoRetido() == FALSE) {
                 continue;
             }
             // Ignora notas anuladas, extraviadas ou canceladas
             if ($oNota->getStatus() == 5 || in_array($oNota->getSituacaoDocumento(), array('E', 'C'))) {
                 continue;
             }
             // Ignora notas isentas
             if ($oNota->getEmiteGuia() == FALSE) {
                 continue;
             }
             // Ignora notas com aliquota ou servico zerados
             if (floatval($oNota->getServicoAliquota()) <= 0) {
                 continue;
             } else {
                 if (floatval($oNota->getServicoValorImposto()) <= 0) {
                     continue;
                 }
             }
             $aNotas[$oNota->getId()] = $oNota;
         }
         $iMesCompetencia = $oDms->getMesCompetencia();
         $iAnoCompetencia = $oDms->getAnoCompetencia();
         $oUsuarioContribuinte = Administrativo_Model_UsuarioContribuinte::getById($oDms->getIdContribuinte());
         $oContribuinte = Administrativo_Model_UsuarioContribuinte::getContribuinte($oDms->getIdContribuinte());
         // Salva guia antes de ser gerada no e-cidade
         $oGuia = new Contribuinte_Model_Guia();
         $sDataPagamentoGuia = DBSeller_Helper_Date_Date::invertDate($sDataPagamento);
         $oGuia->gerarGuiaDmsPrestador($oContribuinte, new DateTime($sDataPagamentoGuia), $iMesCompetencia, $iAnoCompetencia);
         // Envia Guia para o e-cidade
         $oGuiaGerar = self::montaDadosGuia($oUsuarioContribuinte, $iAnoCompetencia, $iMesCompetencia, $aNotas, $sDataPagamento, $oGuia->getId());
         $oGuiaGerada = self::gerarGuia($oGuiaGerar, $sDataPagamento, self::TIPO_DEBITO_RETIDO);
         $oDms->setCodigoPlanilha($oGuiaGerada->codigo_planilha);
         $oDms->setStatus('emitida');
         $aDadosNotas = $oGuiaGerar->notas;
         $aDadosNotas += $oGuiaGerada->notas;
         foreach ($aDadosNotas as $oNotaProcessada) {
             $oNota = $aNotas[$oNotaProcessada->codigo_documento];
             $oNota->setCodigoNotaPlanilha($oNotaProcessada->codigo_nota_planilha);
             $oNota->setNumpre($oGuiaGerada->debito_planilha);
         }
         $oDms->persist();
         $oGuia->complementaGuiaDmsPrestador($oGuiaGerada->debito, $oDms);
         $oGuiaGerada->arquivo_guia = self::salvarPdf($oGuiaGerada->debito->dados_boleto->arquivo_guia, 'guia_substituto');
         $oDoctrine->getConnection()->commit();
         return $oGuiaGerada;
     } catch (Exception $oError) {
         $oDoctrine->getConnection()->rollback();
         return $oError->getMessage();
     }
 }
 /**
  * Formulário NFSE
  *
  * @param string $sCodigoVerificacao
  * @param string $oContribuinte
  * @return Contribuinte_Form_Nota
  */
 private function formNota($sCodigoVerificacao, $oContribuinte = NULL)
 {
     $oContribuinte = $oContribuinte ?: $this->_session->contribuinte;
     $iMaxNota = 0;
     $iMaxGuia = 0;
     // Calcula quantos dias no passado a nota pode ser emitida
     $oParametrosPrefeitura = Administrativo_Model_Prefeitura::getDadosPrefeituraBase();
     $iDiasRetroativosEmissaoNota = $oParametrosPrefeitura->getNotaRetroativa();
     $oDataCorrente = new DateTime();
     $oUltimaGuia = Contribuinte_Model_Guia::getUltimaGuiaNota($oContribuinte);
     $uDataUltimaNota = Contribuinte_Model_Nota::getUltimaNotaEmitidaByContribuinte($oContribuinte->getContribuintes());
     if ($uDataUltimaNota != NULL) {
         $oDiff = $oDataCorrente->diff(new DateTime($uDataUltimaNota), TRUE);
         $iMaxNota = $oDiff->days < $iDiasRetroativosEmissaoNota ? $oDiff->days : $iDiasRetroativosEmissaoNota;
     }
     if (!empty($oUltimaGuia)) {
         $iMes = $oUltimaGuia->getMesComp();
         $iAno = $oUltimaGuia->getAnoComp();
         if ($oUltimaGuia->getMesComp() + 1 > 12) {
             $iMes = 1;
         }
         $iMes = str_pad($iMes, 2, '0', STR_PAD_LEFT);
         $uDataUltimoDiaCompetencia = new Zend_Date("01/{$iMes}/{$iAno}");
         $uDataUltimoDiaCompetencia->sub(-1, Zend_date::MONTH);
         $oDiff = $oDataCorrente->diff(new DateTime($uDataUltimoDiaCompetencia->get('Y-M-d')), TRUE);
         $iMaxGuia = $oDiff->days < $iDiasRetroativosEmissaoNota ? $oDiff->days : $iDiasRetroativosEmissaoNota;
     }
     if ($iMaxNota > $iMaxGuia && $iMaxGuia > 0) {
         $iDiasRetroativosEmissaoNota = $iMaxGuia;
     } else {
         if ($iMaxNota > 0) {
             $iDiasRetroativosEmissaoNota = $iMaxNota;
         } else {
             if (!$iDiasRetroativosEmissaoNota || $iMaxNota == 0) {
                 $iDiasRetroativosEmissaoNota = 0;
             }
         }
     }
     $oDataCorrente = new DateTime();
     $oDataCorrente = $oDataCorrente->sub(date_interval_create_from_date_string("{$iDiasRetroativosEmissaoNota} days"));
     $oForm = new Contribuinte_Form_Nota($sCodigoVerificacao, $oDataCorrente);
     if ($oContribuinte !== NULL) {
         $oParametros = Contribuinte_Model_ParametroContribuinte::getById($oContribuinte->getIdUsuarioContribuinte());
         if ($oParametros instanceof Contribuinte_Model_ParametroContribuinte) {
             $oForm->preencheParametros($oParametros);
         }
     }
     return $oForm;
 }