Пример #1
0
 /**
  * verifica
  * Verifica o status da SEFAZ com o webservice e retorna tags html com o resultado
  * @param string $config json do arquivo de configuração
  * @return string
  */
 public static function verifica($config = '')
 {
     $aRetorno = array();
     if (empty($config)) {
         return '';
     }
     self::$config = $config;
     if (is_file(APP_ROOT . '/base/status.json')) {
         $aRetorno = (array) json_decode(FilesFolders::readFile(APP_ROOT . '/base/status.json'));
     }
     $tstmp = DateTime::convertSefazTimeToTimestamp($aRetorno['dhRecbto']);
     $tsnow = time();
     $dif = $tsnow - $tstmp;
     //caso tenha passado mais de uma hora desde a ultima verificação
     if ($dif > 3600) {
         self::$nfe = new ToolsNFe($config);
         self::$certTS = self::$nfe->certExpireTimestamp;
         self::$nfe->sefazStatus('', '', $aRetorno);
         $retJson = json_encode($aRetorno);
         FilesFolders::saveFile(APP_ROOT . '/base', 'status.json', $retJson);
     }
     $tstmp = DateTime::convertSefazTimeToTimestamp($aRetorno['dhRecbto']);
     $dhora = date('d/m/Y H:i:s', $tstmp);
     $htmlStatus = "<p class=\"smallred\">OFF-LINE</p>\n<p class=\"smallred\">{$dhora}</p>";
     if ($aRetorno['cStat'] == '107') {
         $htmlStatus = "<p class=\"smallgreen\">SEFAZ On-Line</p>\n<p class=\"smallgreen\">{$dhora}</p>";
     }
     return $htmlStatus;
 }
Пример #2
0
 /**
  * zMontaMessagem
  *
  * @param string $pathFile
  */
 protected function zMontaMessagem($pathFile)
 {
     $dom = new Dom();
     $dom->loadXMLFile($pathFile);
     $infNFe = $dom->getNode('infNFe', 0);
     $ide = $infNFe->getElementsByTagName('ide')->item(0);
     $dest = $infNFe->getElementsByTagName('dest')->item(0);
     $emit = $infNFe->getElementsByTagName('emit')->item(0);
     $icmsTot = $infNFe->getElementsByTagName('ICMSTot')->item(0);
     $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue;
     $nNF = $ide->getElementsByTagName('nNF')->item(0)->nodeValue;
     $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue;
     $xNome = $dest->getElementsByTagName('xNome')->item(0)->nodeValue;
     $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue;
     $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi));
     $vNF = $icmsTot->getElementsByTagName('vNF')->item(0)->nodeValue;
     $this->aMail[] = !empty($dest->getElementsByTagName('email')->item(0)->nodeValue) ? $dest->getElementsByTagName('email')->item(0)->nodeValue : '';
     //pega os emails que existirem em obsCont
     $infAdic = $infNFe->getElementsByTagName('infAdic')->item(0);
     if (!empty($infAdic)) {
         $obsConts = $infAdic->getElementsByTagName('obsCont');
         foreach ($obsConts as $obsCont) {
             if (strtoupper($obsCont->getAttribute('xCampo')) === 'EMAIL') {
                 $this->aMail[] = $obsCont->getElementsByTagName('xTexto')->item(0)->nodeValue;
             }
         }
     }
     $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nNF, $serie, $vNF, $razao);
     $this->msgTxt = utf8_encode(Html2Text::convert(utf8_decode($this->msgHtml)));
     return "NFe n. {$nNF} - {$razao}";
 }
Пример #3
0
 /**
  * zMontaMessagem
  * @param string $pathFile
  */
 protected function zMontaMessagem($pathFile)
 {
     $dom = new Dom();
     $dom->loadXMLFile($pathFile);
     $infMDFe = $dom->getNode('infMDFe', 0);
     $ide = $infMDFe->getElementsByTagName('ide')->item(0);
     $emit = $infMDFe->getElementsByTagName('emit')->item(0);
     $tot = $infMDFe->getElementsByTagName('tot')->item(0);
     $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue;
     $nMDF = $ide->getElementsByTagName('nMDF')->item(0)->nodeValue;
     $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue;
     $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue;
     $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi));
     $vCarga = $tot->getElementsByTagName('vCarga')->item(0)->nodeValue;
     $xNome = '';
     $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nMDF, $serie, $vCarga, $razao);
     $this->msgTxt = utf8_encode(Html2Text::convert(utf8_decode($this->msgHtml)));
     return "MDFe n. {$nMDF} - {$razao}";
 }
Пример #4
0
 /**
  * zMontaMessagem
  *
  * @param string $pathFile
  */
 protected function zMontaMessagem($pathFile)
 {
     $dom = new Dom();
     $dom->loadXMLFile($pathFile);
     $infCTe = $dom->getNode('infCte', 0);
     $ide = $infCTe->getElementsByTagName('ide')->item(0);
     $dest = $infCTe->getElementsByTagName('dest')->item(0);
     $emit = $infCTe->getElementsByTagName('emit')->item(0);
     $vPrest = $infCTe->getElementsByTagName('vPrest')->item(0);
     $razao = $emit->getElementsByTagName('xNome')->item(0)->nodeValue;
     $nCT = $ide->getElementsByTagName('nCT')->item(0)->nodeValue;
     $serie = $ide->getElementsByTagName('serie')->item(0)->nodeValue;
     $xNome = $dest->getElementsByTagName('xNome')->item(0)->nodeValue;
     $dhEmi = !empty($ide->getElementsByTagName('dhEmi')->item(0)->nodeValue) ? $ide->getElementsByTagName('dhEmi')->item(0)->nodeValue : $ide->getElementsByTagName('dEmi')->item(0)->nodeValue;
     $data = date('d/m/Y', DateTime::convertSefazTimeToTimestamp($dhEmi));
     $vCT = $vPrest->getElementsByTagName('vTPrest')->item(0)->nodeValue;
     $this->aMail[] = !empty($dest->getElementsByTagName('email')->item(0)->nodeValue) ? $dest->getElementsByTagName('email')->item(0)->nodeValue : '';
     $this->msgHtml = $this->zRenderTemplate($xNome, $data, $nCT, $serie, $vCT, $razao);
     $cHTT = new Html2Text($this->msgHtml);
     $this->msgTxt = $cHTT->getText();
     return "CTe n. {$nCT} - {$razao}";
 }
Пример #5
0
 /**
  * tgaide
  * Informações de identificação da NF-e B01 pai A01
  * tag NFe/infNFe/ide
  * @param string $cUF
  * @param string $cNF
  * @param string $natOp
  * @param string $indPag
  * @param string $mod
  * @param string $serie
  * @param string $nNF
  * @param string $dhEmi
  * @param string $dhSaiEnt
  * @param string $tpNF
  * @param string $idDest
  * @param string $cMunFG
  * @param string $tpImp
  * @param string $tpEmis
  * @param string $cDV
  * @param string $tpAmb
  * @param string $finNFe
  * @param string $indFinal
  * @param string $indPres
  * @param string $procEmi
  * @param string $verProc
  * @param string $dhCont
  * @param string $xJust
  * @return DOMElement
  */
 public function tagide($cUF = '', $cNF = '', $natOp = '', $indPag = '', $mod = '', $serie = '', $nNF = '', $dhEmi = '', $dhSaiEnt = '', $tpNF = '', $idDest = '', $cMunFG = '', $tpImp = '', $tpEmis = '', $cDV = '', $tpAmb = '', $finNFe = '', $indFinal = '0', $indPres = '', $procEmi = '', $verProc = '', $dhCont = '', $xJust = '')
 {
     $this->tpAmb = $tpAmb;
     $identificador = 'B01 <ide> - ';
     $ide = $this->dom->createElement("ide");
     $this->dom->addChild($ide, "cUF", $cUF, true, $identificador . "Código da UF do emitente do Documento Fiscal");
     $this->dom->addChild($ide, "cNF", $cNF, true, $identificador . "Código Numérico que compõe a Chave de Acesso");
     $this->dom->addChild($ide, "natOp", $natOp, true, $identificador . "Descrição da Natureza da Operaçãoo");
     $this->dom->addChild($ide, "indPag", $indPag, true, $identificador . "Indicador da forma de pagamento");
     $this->dom->addChild($ide, "mod", $mod, true, $identificador . "Código do Modelo do Documento Fiscal");
     $this->dom->addChild($ide, "serie", $serie, true, $identificador . "Série do Documento Fiscal");
     $this->dom->addChild($ide, "nNF", $nNF, true, $identificador . "Número do Documento Fiscal");
     if ($dhEmi == '') {
         $dhEmi = DateTime::convertTimestampToSefazTime();
     }
     $this->dom->addChild($ide, "dhEmi", $dhEmi, true, $identificador . "Data e hora de emissão do Documento Fiscal");
     if ($mod == '55' && $dhSaiEnt != '') {
         $this->dom->addChild($ide, "dhSaiEnt", $dhSaiEnt, false, $identificador . "Data e hora de Saída ou da Entrada da Mercadoria/Produto");
     }
     $this->dom->addChild($ide, "tpNF", $tpNF, true, $identificador . "Tipo de Operação");
     $this->dom->addChild($ide, "idDest", $idDest, true, $identificador . "Identificador de local de destino da operação");
     $this->dom->addChild($ide, "cMunFG", $cMunFG, true, $identificador . "Código do Município de Ocorrência do Fato Gerador");
     $this->dom->addChild($ide, "tpImp", $tpImp, true, $identificador . "Formato de Impressão do DANFE");
     $this->dom->addChild($ide, "tpEmis", $tpEmis, true, $identificador . "Tipo de Emissão da NF-e");
     $this->dom->addChild($ide, "cDV", $cDV, true, $identificador . "Dígito Verificador da Chave de Acesso da NF-e");
     $this->dom->addChild($ide, "tpAmb", $tpAmb, true, $identificador . "Identificação do Ambiente");
     $this->dom->addChild($ide, "finNFe", $finNFe, true, $identificador . "Finalidade de emissão da NF-e");
     $this->dom->addChild($ide, "indFinal", $indFinal, true, $identificador . "Indica operação com Consumidor final");
     $this->dom->addChild($ide, "indPres", $indPres, true, $identificador . "Indicador de presença do comprador no estabelecimento comercial no momento da operação");
     $this->dom->addChild($ide, "procEmi", $procEmi, true, $identificador . "Processo de emissão da NF-e");
     $this->dom->addChild($ide, "verProc", $verProc, true, $identificador . "Versão do Processo de emissão da NF-e");
     if ($dhCont != '' && $xJust != '') {
         $this->dom->addChild($ide, "dhCont", $dhCont, true, $identificador . "Data e Hora da entrada em contingência");
         $this->dom->addChild($ide, "xJust", $xJust, true, $identificador . "Justificativa da entrada em contingência");
     }
     $this->mod = $mod;
     $this->ide = $ide;
     return $ide;
 }
Пример #6
0
 /**
  * sefazEPEC
  * Solicita autorização em contingência EPEC
  * TODO: terminar esse método
  * @param string|array $aXml
  * @param string $tpAmb
  * @param string $siglaUF
  * @param array $aRetorno
  * @return string
  * @throws Exception\InvalidArgumentException
  */
 public function sefazEPEC($aXml, $tpAmb = '2', $siglaUF = 'AN', &$aRetorno = array())
 {
     //na nfe deve estar indicado a entrada em contingencia da data hora e o motivo
     //caso contrario ignorar a solicitação de EPEC
     if (!is_array($aXml)) {
         $aXml[] = $aXml;
         //se não é um array converte
     }
     if (count($aXml) > 20) {
         $msg = "O limite é de 20 NFe em um lote EPEC, você está passando [" . count($aXml) . "]";
         throw new Exception\InvalidArgumentException($msg);
     }
     if ($tpAmb == '') {
         $tpAmb = $this->aConfig['tpAmb'];
     }
     //carrega serviço
     $servico = 'RecepcaoEPEC';
     $this->zLoadServico('nfe', $servico, $siglaUF, $tpAmb);
     if ($this->urlService == '') {
         $msg = "A recepção de EPEC não está disponível na SEFAZ !!!";
         throw new Exception\RuntimeException($msg);
     }
     $aRetorno = array();
     $cnpj = $this->aConfig['cnpj'];
     $aRet = $this->zTpEv($tpEvento);
     $descEvento = $aRet['desc'];
     $cOrgao = '91';
     $tpEvento = '110140';
     //EPEC
     $datEv = '';
     $numLote = LotNumber::geraNumLote();
     foreach ($aXml as $xml) {
         $dat = $this->zGetInfo($xml);
         if ($dat['dhCont'] == '' || $dat['xJust'] == '') {
             $msg = "Somente é possivel enviar para EPEC as notas emitidas " . "em contingência com a data/hora e justificativa da contingência.";
             throw new Exception\InvalidArgumentException($msg);
         }
         $sSeqEvento = str_pad('1', 2, "0", STR_PAD_LEFT);
         $eventId = "ID" . $tpEvento . $chNFe . $sSeqEvento;
         $chNFe = $dat['chave'];
         $dhEvento = DateTime::convertTimestampToSefazTime();
         $mensagem = "<evento xmlns=\"{$this->urlPortal}\" versao=\"{$this->urlVersion}\">" . "<infEvento Id=\"{$eventId}\">" . "<cOrgao>{$cOrgao}</cOrgao>" . "<tpAmb>{$tpAmb}</tpAmb>" . "<CNPJ>{$cnpj}</CNPJ>" . "<chNFe>{$chNFe}</chNFe>" . "<dhEvento>{$dhEvento}</dhEvento>" . "<tpEvento>{$tpEvento}</tpEvento>" . "<nSeqEvento>1</nSeqEvento>" . "<verEvento>{$this->urlVersion}</verEvento>" . "<detEvento versao=\"{$this->urlVersion}\">" . "<descEvento>{$descEvento}</descEvento>" . "<cOrgaoAutor>" . $dat['cOrgaoAutor'] . "</cOrgaoAutor>" . "<tpAutor>" . $dat['tpAutor'] . "</tpAutor>" . "<verAplic>{$this->verAplic}</verAplic>" . "<dhEmi>" . $dat['dhEmi'] . "</dhEmi>" . "<tpNF>" . $dat['tpNF'] . "</tpNF>" . "<IE>" . $dat['IE'] . "</IE>" . "<dest>" . "<UF>" . $dat['UF'] . "</UF> ";
         if ($dat['CNPJ'] != '') {
             $mensagem .= "<CNPJ>." . $dat['CNPJ'] . "</CNPJ>";
         } elseif ($dat['CPF'] != '') {
             $mensagem .= "<CPF>" . $dat['CPF'] . "</CPF>";
         } else {
             $mensagem .= "<idEstrangeiro>" . $dat['idEstrangeiro'] . "</idEstrangeiro>";
         }
         if ($dat['IEdest'] != '') {
             $mensagem .= "<IE>" . $dat['IEdest'] . "</IE>";
         }
         $mensagem .= "</dest>" . "<vNF>" . $dat['vNF'] . "</vNF>" . "<vICMS>" . $dat['vICMS'] . "</vICMS>" . "<vST>" . $dat['vST'] . "</vST>" . "</detEvento>" . "</infEvento>" . "</evento>";
         //assinatura dos dados
         $signedMsg = $this->oCertificate->signXML($mensagem, 'infEvento');
         $signedMsg = Strings::clearXml($signedMsg, true);
         $datEv .= $signedMsg;
     }
     $cons = "<envEvento xmlns=\"{$this->urlPortal}\" versao=\"{$this->urlVersion}\">" . "<idLote>{$numLote}</idLote>" . "{$datEv}" . "</envEvento>";
     //valida mensagem com xsd
     //no caso do evento nao tem xsd organizado, esta fragmentado
     //e por vezes incorreto por isso essa validação está desabilitada
     //if (! $this->zValidMessage($cons, 'nfe', 'envEvento', $version)) {
     //    $msg = 'Falha na validação. '.$this->error;
     //    throw new Exception\RuntimeException($msg);
     //}
     $body = "<nfeDadosMsg xmlns=\"{$this->urlNamespace}\">{$cons}</nfeDadosMsg>";
     //envia a solicitação via SOAP
     $retorno = $this->oSoap->send($this->urlService, $this->urlNamespace, $this->urlHeader, $body, $this->urlMethod);
     $lastMsg = $this->oSoap->lastMsg;
     $this->soapDebug = $this->oSoap->soapDebug;
     //salva mensagens
     $filename = "{$numLote}-envEpec.xml";
     $this->zGravaFile('nfe', $tpAmb, $filename, $lastMsg);
     $filename = "{$numLote}-retEnvEpec.xml";
     $this->zGravaFile('nfe', $tpAmb, $filename, $retorno);
     //tratar dados de retorno
     //TODO : incluir nos xml das NF o protocolo EPEC
     $aRetorno = ReturnNFe::readReturnSefaz($servico, $retorno);
     return $retorno;
 }
Пример #7
0
 /**
  * assinaDoc
  * @param string $xml
  * @param string $tipo nfe, cte, ou mdfe
  * @param string $tag Nome da tag a ser assinada 
  * @param boolean $saveFile APENAS para salvar NFe, CTe ou MDFe
  * @return string
  * @throws Exception\InvalidArgumentException
  * @throws Exception\RuntimeException
  */
 public function assinaDoc($xml = '', $tipo = '', $tag = '', $saveFile = false)
 {
     if ($tag == '') {
         $msg = 'Deve ser indicada uma tag a ser assinada';
         throw new Exception\InvalidArgumentException($msg);
     }
     if (is_file($xml)) {
         $xml = Files\FilesFolders::readFile($xml);
     }
     $sxml = $this->oCertificate->signXML($xml, $tag);
     $dom = new Dom();
     $dom->loadXMLString($sxml);
     //$versao = $dom->getElementsByTagName($tag)->item(0)->getAttribute('versao');
     //if (! $this->zValidMessage($sxml, $tipo, $versao)) {
     //$msg = "Falha na validação do $tipo. ".$this->error;
     //  throw new Exception\RuntimeException($msg);
     //}
     if ($saveFile && $tipo != '') {
         $dom = new Dom();
         $dom->loadXMLString($sxml);
         $tpAmb = $dom->getElementsByTagName('tpAmb')->item(0)->nodeValue;
         $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($dom->getElementsByTagName('dhEmi')->item(0)->nodeValue));
         $chave = $dom->getChave($tag);
         $filename = "{$chave}-{$tipo}.xml";
         $this->zGravaFile($tipo, $tpAmb, $filename, $sxml, 'assinadas', $anomes);
     }
     return $sxml;
 }
Пример #8
0
 /**
  * addCancelamento
  * Adiciona a tga de cancelamento a uma MDFe já autorizada
  * NOTA: não é requisito da SEFAZ, mas auxilia na identificação das MDFe que foram canceladas
  * @param string $pathMDFefile
  * @param string $pathCancfile
  * @param bool $saveFile
  * @return string
  * @throws Exception\RuntimeException
  */
 public function addCancelamento($pathMDFefile = '', $pathCancfile = '', $saveFile = false)
 {
     $procXML = '';
     //carrega a NFe
     $docmdfe = new Dom();
     $docmdfe->loadXMLFile($pathMDFefile);
     $nodemdfe = $docmdfe->getNode('MDFe', 0);
     if ($nodemdfe == '') {
         $msg = "O arquivo indicado como MDFe não é um xml de MDFe!";
         throw new Exception\RuntimeException($msg);
     }
     $proMDFe = $docmdfe->getNode('protMDFe');
     if ($proMDFe == '') {
         $msg = "O MDFe não está protocolado ainda!!";
         throw new Exception\RuntimeException($msg);
     }
     $chaveMDFe = $proMDFe->getElementsByTagName('chMDFe')->item(0)->nodeValue;
     //$nProtNFe = $proNFe->getElementsByTagName('nProt')->item(0)->nodeValue;
     $tpAmb = $docmdfe->getNodeValue('tpAmb');
     $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($docmdfe->getNodeValue('dhEmi')));
     //carrega o cancelamento
     //pode ser um evento ou resultado de uma consulta com multiplos eventos
     $doccanc = new Dom();
     $doccanc->loadXMLFile($pathCancfile);
     $eventos = $doccanc->getElementsByTagName('infEvento');
     foreach ($eventos as $evento) {
         //evento
         $cStat = $evento->getElementsByTagName('cStat')->item(0)->nodeValue;
         $tpAmb = $evento->getElementsByTagName('tpAmb')->item(0)->nodeValue;
         $chaveEvento = $evento->getElementsByTagName('chNFe')->item(0)->nodeValue;
         $tpEvento = $evento->getElementsByTagName('tpEvento')->item(0)->nodeValue;
         //$nProtEvento = $evento->getElementsByTagName('nProt')->item(0)->nodeValue;
         //verifica se conferem os dados
         //cStat = 135 ==> evento homologado
         //tpEvento = 110111 ==> Cancelamento
         //chave do evento == chave da NFe
         //protocolo do evneto ==  protocolo da NFe
         if ($cStat == '135' && $tpEvento == '110111' && $chaveEvento == $chaveMDFe) {
             $proMDFe->getElementsByTagName('cStat')->item(0)->nodeValue = '101';
             $proMDFe->getElementsByTagName('xMotivo')->item(0)->nodeValue = 'Cancelamento de NF-e homologado';
             $procXML = $docmdfe->saveXML();
             //remove as informações indesejadas
             $procXML = Strings::clearProt($procXML);
             if ($saveFile) {
                 $filename = "{$chaveMDFe}-protMDFe.xml";
                 $this->zGravaFile('mdfe', $tpAmb, $filename, $procXML, 'enviadas' . DIRECTORY_SEPARATOR . 'aprovadas', $anomes);
             }
             break;
         }
     }
     return (string) $procXML;
 }
Пример #9
0
 /**
  * __construct
  *
  * @param string $configJson
  * @param bool   $ignore default false usado para testes apenas
  * @throws InvalidArgumentException
  * @throws RuntimeException
  */
 public function __construct($configJson = '', $ignore = false)
 {
     if ($configJson == '') {
         $msg = 'O arquivo de configuração no formato JSON deve ser passado para a classe.';
         throw new InvalidArgumentException($msg);
     }
     if (is_file($configJson)) {
         $configJson = Files\FilesFolders::readFile($configJson);
     }
     //carrega os dados de configuração
     $this->aConfig = (array) json_decode($configJson, true);
     $this->aProxyConf = (array) $this->aConfig['aProxyConf'];
     $this->verAplic = $this->aConfig['verAplic'];
     //seta o timezone
     DateTime::tzdBR($this->aConfig['siglaUF']);
     //carrega os certificados
     $this->oCertificate = new Pkcs12($this->aConfig['pathCertsFiles'], $this->aConfig['cnpj'], '', '', '', $ignore);
     $timestampnow = gmmktime(0, 0, 0, date("m"), date("d"), date("Y"));
     if ($this->oCertificate->expireTimestamp == 0 || $this->oCertificate->expireTimestamp < $timestampnow) {
         //tentar carregar novo certificado
         $this->atualizaCertificado($this->aConfig['pathCertsFiles'] . $this->aConfig['certPfxName'], $this->aConfig['certPassword']);
         if ($this->oCertificate->expireTimestamp == 0 || $this->oCertificate->expireTimestamp < $timestampnow) {
             $msg = 'Não existe certificado válido disponível. Atualize o Certificado.';
             throw new RuntimeException($msg);
         }
     }
     $this->setAmbiente($this->aConfig['tpAmb']);
     $this->certExpireTimestamp = $this->oCertificate->expireTimestamp;
     $this->certExpireDate = date('d/m/Y', $this->certExpireTimestamp);
     $this->loadSoapClass();
 }
Пример #10
0
 public static function extrai($aList, $cnpj = '')
 {
     $aResp = array();
     $totFat = 0;
     $totPeso = 0;
     $totIcms = 0;
     foreach ($aList as $file) {
         $dom = null;
         $ide = null;
         $emit = null;
         $dest = null;
         try {
             $dom = new Dom();
             $dom->loadXMLFile($file);
             $ide = $dom->getNode('ide');
             $emit = $dom->getNode('emit');
             $dest = $dom->getNode('dest');
             $icmsTot = $dom->getNode('ICMSTot');
             $vol = $dom->getNode('vol');
             $cStat = $dom->getNodeValue('cStat');
             if ($cStat != '100') {
                 self::$nCanc++;
             }
             $dhEmi = $dom->getValue($ide, 'dhEmi');
             if (empty($dhEmi)) {
                 $dhEmi = $dom->getValue($ide, 'dEmi');
             }
             //echo $file.'___'.$dhEmi.'<br>';
             $tsEmi = DateTime::convertSefazTimeToTimestamp($dhEmi);
             $data = '';
             if (is_numeric($tsEmi)) {
                 $data = date('d/m/Y', $tsEmi);
             }
             $emitCNPJ = $dom->getValue($emit, 'CNPJ');
             $emitRazao = $dom->getValue($emit, 'xNome');
             $destRazao = $dom->getValue($dest, 'xNome');
             $vNF = $dom->getValue($icmsTot, 'vNF');
             $vNFtext = $vNF;
             if (is_numeric($vNF)) {
                 $vNFtext = 'R$ ' . number_format($vNF, '2', ',', '.');
             }
             $serie = $dom->getNodeValue('serie');
             $nProt = $dom->getNodeValue('nProt');
             $nome = $emitRazao;
             if ($emitCNPJ == $cnpj) {
                 $nome = $destRazao;
             }
             $email = $dom->getValue($dest, 'email');
             $aObscont = $dom->getElementsByTagName('obsCont');
             if (count($aObscont) > 0) {
                 foreach ($aObscont as $obsCont) {
                     $xCampo = $obsCont->getAttribute('xCampo');
                     if ($xCampo == 'email') {
                         $email .= ";" . $dom->getValue($obsCont, 'xTexto');
                     }
                 }
             }
             if (substr($email, 0, 1) == ';') {
                 $email = substr($email, 1, strlen($email) - 1);
             }
             $vICMS = $dom->getValue($icmsTot, 'vICMS');
             $totIcms += $vICMS;
             $valorFat = 0;
             if ($vICMS != 0 && $cStat == '100') {
                 $valorFat = $vNF;
             }
             $totFat += $valorFat;
             $pesoL = $dom->getValue($vol, 'pesoL');
             if ($pesoL != '') {
                 $totPeso += $pesoL;
             }
             $aResp[] = array('nNF' => $dom->getValue($ide, 'nNF'), 'serie' => $serie, 'data' => $data, 'nome' => $nome, 'natureza' => $dom->getValue($ide, 'natOp'), 'cStat' => $cStat, 'vNF' => $vNFtext, 'nProt' => $nProt, 'email' => $email);
         } catch (RuntimeException $e) {
             $aResp[] = array('nNF' => '000000', 'serie' => '000', 'data' => '000', 'nome' => 'FALHA', 'natureza' => "{$file}", 'cStat' => '', 'vNF' => 0, 'nProt' => '', 'email' => '');
         }
     }
     return array('totFat' => $totFat, 'totPeso' => $totPeso, 'totIcms' => $totIcms, 'aNF' => $aResp);
 }
Пример #11
0
 /**
  * @dataProvider siglasNaoExistentes
  */
 public function testTZDSiglaNaoExistente($uf)
 {
     $this->assertEmpty(DateTime::tzdBR($uf));
 }
Пример #12
0
 /**
  * tgaide
  * Informações de identificação da MDFe 4 pai 1
  * tag MDFe/infMDFe/ide
  *
  * @param  string $cUF
  * @param  string $tbAmb
  * @param  string $tpEmit
  * @param  string $mod
  * @param  string $serie
  * @param  string $nMDF
  * @param  string $cMDF
  * @param  string $cDV
  * @param  string $modal
  * @param  string $dhEmi
  * @param  string $tpEmis
  * @param  string $procEmi
  * @param  string $verProc
  * @param  string $ufIni
  * @param  string $ufFim
  * @return DOMElement
  */
 public function tagide($cUF = '', $tpAmb = '', $tpEmit = '', $mod = '58', $serie = '', $nMDF = '', $cMDF = '', $cDV = '', $modal = '', $dhEmi = '', $tpEmis = '', $procEmi = '', $verProc = '', $ufIni = '', $ufFim = '')
 {
     $this->tpAmb = $tpAmb;
     if ($dhEmi == '') {
         $dhEmi = DateTime::convertTimestampToSefazTime();
     }
     $identificador = '[4] <ide> - ';
     $ide = $this->dom->createElement("ide");
     $this->dom->addChild($ide, "cUF", $cUF, true, $identificador . "Código da UF do emitente do Documento Fiscal");
     $this->dom->addChild($ide, "tpAmb", $tpAmb, true, $identificador . "Identificação do Ambiente");
     $this->dom->addChild($ide, "tpEmit", $tpEmit, true, $identificador . "Indicador da tipo de emitente");
     $this->dom->addChild($ide, "mod", $mod, true, $identificador . "Código do Modelo do Documento Fiscal");
     $this->dom->addChild($ide, "serie", $serie, true, $identificador . "Série do Documento Fiscal");
     $this->dom->addChild($ide, "nMDF", $nMDF, true, $identificador . "Número do Documento Fiscal");
     $this->dom->addChild($ide, "cMDF", $cMDF, true, $identificador . "Código do numérico do MDF");
     $this->dom->addChild($ide, "cDV", $cDV, true, $identificador . "Dígito Verificador da Chave de Acesso da NF-e");
     $this->dom->addChild($ide, "modal", $modal, true, $identificador . "Modalidade de transporte");
     $this->dom->addChild($ide, "dhEmi", $dhEmi, true, $identificador . "Data e hora de emissão do Documento Fiscal");
     $this->dom->addChild($ide, "tpEmis", $tpEmis, true, $identificador . "Tipo de Emissão do Documento Fiscal");
     $this->dom->addChild($ide, "procEmi", $procEmi, true, $identificador . "Processo de emissão");
     $this->dom->addChild($ide, "verProc", $verProc, true, $identificador . "Versão do Processo de emissão");
     $this->dom->addChild($ide, "UFIni", $ufIni, true, $identificador . "Sigla da UF do Carregamento");
     $this->dom->addChild($ide, "UFFim", $ufFim, true, $identificador . "Sigla da UF do Descarregamento");
     $this->mod = $mod;
     $this->ide = $ide;
     return $ide;
 }
Пример #13
0
 public function testConvertTimestampToSefazTime()
 {
     DateTime::tzdBR('CE');
     $seft = DateTime::convertTimestampToSefazTime($this->tstp);
     $this->assertEquals($seft, $this->sefTime);
 }
Пример #14
0
 /**
  * zTrataProcEvent
  * @param array $resp
  */
 private static function zTrataProcEvent($resp = array())
 {
     $aResp = array();
     $content = $resp['doc'];
     $dom = new Dom();
     $dom->loadXMLString($content);
     $xmldata = $dom->saveXML();
     $xmldata = str_replace('<?xml version="1.0"?>', '<?xml version="1.0" encoding="utf-8"?>', $xmldata);
     $data = $dom->getNodeValue('dhEvento');
     $tsdhevento = DateTime::convertSefazTimeToTimestamp($data);
     $anomes = date('Ym', $tsdhevento);
     $tpEvento = $dom->getNodeValue('tpEvento');
     $chave = $dom->getNodeValue('chNFe');
     if ($tpEvento == '110111') {
         //confirmado cancelamento, localizar o xml da NFe recebida
         //na pasta anomes
         $path = $this->pathNFe . DIRECTORY_SEPARATOR . $this->ambiente . DIRECTORY_SEPARATOR . "recebidas" . DIRECTORY_SEPARATOR . $anomes;
         $pathFile = $path . DIRECTORY_SEPARATOR . $chave . '-nfe.xml';
         self::zCancela($pathFile);
         $aResp[] = array('tipo' => '-cancNFe.xml', 'chave' => $chave, 'anomes' => $anomes, 'xml' => $xmldata);
     } elseif ($tpEvento == '110110') {
         //evento Carta de Correção
         $aResp[] = array('tipo' => '-cce.xml', 'chave' => $chave, 'anomes' => $anomes, 'xml' => $xmldata);
     }
     return $aResp;
 }
Пример #15
0
 /**
  * addCancelamento
  * Adiciona a tga de cancelamento a uma CTe já autorizada
  * NOTA: não é requisito da SEFAZ, mas auxilia na identificação das CTe que foram canceladas
  * @param string $pathCTefile
  * @param string $pathCancfile
  * @param bool $saveFile
  * @return string
  * @throws Exception\RuntimeException
  */
 public function addCancelamento($pathCTefile = '', $pathCancfile = '', $saveFile = false)
 {
     $procXML = '';
     //carrega a CTe
     $docCTe = new Dom();
     if (file_exists($pathCTefile)) {
         //carrega o XML pelo caminho do arquivo informado
         $docCTe->loadXMLFile($pathCTefile);
     } else {
         //carrega o XML pelo conteúdo
         $docCTe->loadXMLString($pathCTefile);
     }
     $nodeCTe = $docCTe->getNode('CTe', 0);
     if ($nodeCTe == '') {
         $msg = "O arquivo indicado como CTe não é um xml de CTe!";
         throw new Exception\RuntimeException($msg);
     }
     $proCTe = $docCTe->getNode('protCTe');
     if ($proCTe == '') {
         $msg = "A CTe não está protocolada ainda!!";
         throw new Exception\RuntimeException($msg);
     }
     $chaveCTe = $proCTe->getElementsByTagName('chCTe')->item(0)->nodeValue;
     //$nProtCTe = $proCTe->getElementsByTagName('nProt')->item(0)->nodeValue;
     $tpAmb = $docCTe->getNodeValue('tpAmb');
     $anomes = date('Ym', DateTime::convertSefazTimeToTimestamp($docCTe->getNodeValue('dhEmi')));
     //carrega o cancelamento
     //pode ser um evento ou resultado de uma consulta com multiplos eventos
     $doccanc = new Dom();
     if (file_exists($pathCancfile)) {
         //carrega o XML pelo caminho do arquivo informado
         $doccanc->loadXMLFile($pathCancfile);
     } else {
         //carrega o XML pelo conteúdo
         $doccanc->loadXMLString($pathCancfile);
     }
     $retEvento = $doccanc->getElementsByTagName('retEventoCTe')->item(0);
     $eventos = $retEvento->getElementsByTagName('infEvento');
     foreach ($eventos as $evento) {
         //evento
         $cStat = $evento->getElementsByTagName('cStat')->item(0)->nodeValue;
         $tpAmb = $evento->getElementsByTagName('tpAmb')->item(0)->nodeValue;
         $chaveEvento = $evento->getElementsByTagName('chCTe')->item(0)->nodeValue;
         $tpEvento = $evento->getElementsByTagName('tpEvento')->item(0)->nodeValue;
         //$nProtEvento = $evento->getElementsByTagName('nProt')->item(0)->nodeValue;
         //verifica se conferem os dados
         //cStat = 135 ==> evento homologado
         //cStat = 136 ==> vinculação do evento à respectiva NF-e prejudicada
         //cStat = 155 ==> Cancelamento homologado fora de prazo
         //tpEvento = 110111 ==> Cancelamento
         //chave do evento == chave da CTe
         //protocolo do evneto ==  protocolo da CTe
         if (($cStat == '135' || $cStat == '136' || $cStat == '155') && $tpEvento == '110111' && $chaveEvento == $chaveCTe) {
             $proCTe->getElementsByTagName('cStat')->item(0)->nodeValue = '101';
             $proCTe->getElementsByTagName('xMotivo')->item(0)->nodeValue = 'Cancelamento de CT-e homologado';
             $procXML = $docCTe->saveXML();
             //remove as informações indesejadas
             $procXML = Strings::clearProt($procXML);
             if ($saveFile) {
                 $filename = "{$chaveCTe}-protCTe.xml";
                 $this->zGravaFile('cte', $tpAmb, $filename, $procXML, 'canceladas', $anomes);
             }
             break;
         }
     }
     return (string) $procXML;
 }
Пример #16
0
 /**
  * Busca a data e hora do processamento
  *
  * @param DOMElement $node
  * @return strinf
  */
 protected static function retDataHora($node)
 {
     $data = '';
     $dtHora = self::retValue($node, 'dataHoraProcessamento');
     if (empty($dtHora)) {
         $dtHora = self::retValue($node, 'dhProcessamento');
     }
     if (!empty($dtHora)) {
         $data = date('d/m/Y H:i:s', DateTime::convertSefazTimeToTimestamp($dtHora));
     }
     return $data;
 }