NFe_Chave.'-nfe.err')){ unlink(nfe_pasta_raiz().'retorno/'.$reg_nota->NFe_Chave.'-nfe.err'); } //cria objeto xml $xml = new XML(); $dados_partilha = false; //adiciona dados da nota $r = &$xml->createRoot("NFe"); $r->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe', true); $nf_inf = &$r->addChild("infNFe"); //$nf_inf->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance', true); $nf_inf->addAttribute('Id', 'NFe'.$reg_nota->NFe_Chave, true); $nf_inf->addAttribute('versao', $reg_nota->NFe_Versao, true); //chave da NFe $ide = &$nf_inf->addChild("ide"); $chave = $reg_nota->NFe_Chave; //UF $ide->addAttribute('cUF', substr($chave,0,2) , false); //Número aleatório if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $ide->addAttribute('cNF', substr($chave,35,8) , false); }else{ //2.00 $ide->addAttribute('cNF', substr($chave,34,9) , false); } //natureza de operação $ide->addAttribute('natOp', $reg_nota->Nat_Op_Descricao , false); //forma de pagto if ($reg_nota->Forma_Pagto == 1){ $forma = '0'; //à vista }else if ($reg_nota->Forma_Pagto == 0){ $forma = '2'; //outros (não tem vencimentos) }else{ $forma = '1'; //prazo } if ($reg_nota->NFe_Versao == '3.10'){ $ide->addAttribute('indPag', $forma , false); } //modelo $ide->addAttribute('mod', substr($chave,20,2) , false); //serie $ide->addAttribute('serie', $reg_nota->Serie , false); //nr doc $ide->addAttribute('nNF', $reg_nota->NrDoc , false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //data de emissao $uf = substr($reg_nota->NFe_Chave,0,2); $data = substr($reg_nota->DH_Emissao,0,10); $dif_UTC = calcula_horario_verao($data,$uf); $ide->addAttribute('dhEmi', str_replace(' ','T',$reg_nota->DH_Emissao).$dif_UTC, false); if ($reg_nota->Modelo == '55'){ //data de saida //$uf = substr($reg_nota->NFe_Chave,0,2); if (dataf($reg_nota->DH_SaidaNota)!='00/00/0000'){ $data = substr($reg_nota->DH_SaidaNota,0,10); $dif_UTC = calcula_horario_verao($data,$uf); $ide->addAttribute('dhSaiEnt', str_replace(' ','T',$reg_nota->DH_SaidaNota).$dif_UTC, false); } } }else{ //data de emissao $ide->addAttribute('dEmi', datad(dataf($reg_nota->DH_Emissao)) , false); //data de saida $ide->addAttribute('dSaiEnt', datad(dataf($reg_nota->DH_EntSai)) , false); if ($reg_nota->NFe_Versao == '2.00'){ //hora da saida $ide->addAttribute('hSaiEnt', substr($reg_nota->DH_EntSai,11,8) , false); } } //tipo entrada saida $ide->addAttribute('tpNF', $reg_nota->TipoES, false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //Tipo operação Interna/interestdual/com o exterior $idDest = '1'; if ( (substr($reg_nota->Nat_Op_CFOP,0,1) == '2')|| (substr($reg_nota->Nat_Op_CFOP,0,1) == '6')){ $idDest = '2'; }else if ( (substr($reg_nota->Nat_Op_CFOP,0,1) == '3')|| (substr($reg_nota->Nat_Op_CFOP,0,1) == '4')|| (substr($reg_nota->Nat_Op_CFOP,0,1) == '7')|| (substr($reg_nota->Nat_Op_CFOP,0,1) == '8')){ $idDest = '3'; } $ide->addAttribute('idDest', $idDest, false); } //cidade fato gerador $ide->addAttribute('cMunFG', $reg_nota->Cidade_FG, false); //consulta notas referenciadas $con_ref = 'select * from nota_fiscal_refenciada'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'; if ($reg_nota->NFe_TipoEmissao=='3'){ $con_ref.= ' and Tipo_Doc<>"E" and Tipo_Doc<>"F"'; } $con_ref.= ' order by Seq_Doc'; if (($reg_nota->Finalidade=='2') || ($reg_nota->Finalidade=='3')){ $con_ref.= ' Desc limit 1'; } if (($reg_nota->NFe_Versao != '3.10')&&($reg_nota->NFe_Versao != '4.00')){ $res_ref = consulta_sql($con_ref); $nrw_ref = consulta_num_registros($res_ref); //para cada documento referenciado for($ref=0;$ref<$nrw_ref;$ref++){ //adiciona dados das notas referenciadas $reg_ref = consulta_ler_objeto($res_ref); //tag do grupo de referencia if ($reg_ref->Tipo_Doc == 'E'){ //nota eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref->addAttribute('refNFe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'F'){ //nota ao consumidor eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref->addAttribute('refNFe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'N'){ //nota normal $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refNF"); //consulta uf para saber o código da UF $con_uf = 'select Codigo_UF from uf '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and UF="'.$reg_ref->NF_UF.'"'; $res_uf = consulta_sql($con_uf); $reg_uf = consulta_ler_linha($res_uf); consulta_limpa($res_uf); //UF $nf_ref_n->addAttribute('cUF', fill_full($reg_uf[0],2), false); //ano mes $nf_ref_n->addAttribute('AAMM', nfe_ano_mes($reg_ref->NF_DT_Emissao,'AAMM'), false); //cnpj do emitente $nf_ref_n->addAttribute('CNPJ', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->NF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('serie', $reg_ref->NF_Serie, false); //nr de doc $nf_ref_n->addAttribute('nNF', $reg_ref->NF_Nr_Doc, false); } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_ref->Tipo_Doc == 'P'){ //nota de produtor $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refNFP"); //consulta uf para saber o código da UF $con_uf = 'select Codigo_UF from uf '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and UF="'.$reg_ref->NF_UF.'"'; $res_uf = consulta_sql($con_uf); $reg_uf = consulta_ler_linha($res_uf); consulta_limpa($res_uf); //UF $nf_ref_n->addAttribute('cUF', fill_full($reg_uf[0],2), false); //ano mes $nf_ref_n->addAttribute('AAMM', nfe_ano_mes($reg_ref->NF_DT_Emissao,'AAMM'), false); if (strlen($reg_ref->NF_Emitente_CNPJ)==18){ //cnpj do emitente $nf_ref_n->addAttribute('CNPJ', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); }else{ //cpf do emitente $nf_ref_n->addAttribute('CPF', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); } //inscricao de produtor $nf_ref_n->addAttribute('IE', substr(limpa_numero2($reg_ref->NF_Emitente_IE),0,14), false); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->NF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('serie', $reg_ref->NF_Serie, false); //nr de doc $nf_ref_n->addAttribute('nNF', $reg_ref->NF_Nr_Doc, false); }else if ($reg_ref->Tipo_Doc == 'T'){ //conehcimento de transporte eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $reg_ref->addAttribute('refCTe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'C'){ //cupom fiscal $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refECF"); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->ECF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('nECF', $reg_ref->ECF_Caixa, false); //nr de doc $nf_ref_n->addAttribute('nCOO', $reg_ref->ECF_COO, false); } } } consulta_limpa($res_ref); }else{ //só pra fazer certo a aba finalidade abaixo $res_ref = consulta_sql($con_ref); $reg_ref = consulta_ler_objeto($res_ref); consulta_limpa($res_ref); } //termina dados do cabeçalho da nf //tipo impressão do DANFe $ide->addAttribute('tpImp', $reg_nota->NFe_FormatoDANFe, false); //tipo emissao $ide->addAttribute('tpEmis', $reg_nota->NFe_TipoEmissao, false); //digito verificador Nfe $ide->addAttribute('cDV', substr($chave,43,1), false); //ambiente NFe $ide->addAttribute('tpAmb', $reg_nota->NFe_Ambiente, false); $finalidade = $reg_nota->Finalidade; if(($reg_nota->NFe_TipoEmissao=='3')&&($reg_nota->Finalidade!=1)){ if ($reg_ref->Tipo_Doc == 'E'){ $finalidade = '1'; } }else if(($reg_nota->Empresa_UF=='PR')&&($reg_nota->Finalidade!=1)){ //Finalidade if ($reg_ref->Tipo_Doc == 'E'){ //consulta a nota $con_nota_r = 'select NFe_Versao, NFe_TipoEmissao from nota_fiscal '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$reg_ref->Nota_Empresa.'"'. ' and Nr_Nota = "'.$reg_ref->Nota_Nr_Nota.'"'; $res_nota_r = consulta_sql($con_nota_r); $reg_nota_r = consulta_ler_linha($res_nota_r); consulta_limpa($res_nota_r); if($reg_nota_r[0]=='1.10'){ $finalidade = '1'; } if($reg_nota_r[1]=='3'){ $finalidade = '1'; } } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //finalidade devolução if (($finalidade == '1')||($finalidade == '3')){ $cfop = $reg_nota->Nat_Op_CFOP; if(($cfop == '1.999')|| ($cfop == '2.999')|| ($cfop == '5.999')|| ($cfop == '6.999')){ //consultar cfop do primeiro item e colocar na variavel $cfop $con_item = 'select CFOP from nota_fiscal_item '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' LIMIT 1'; $res_item = consulta_sql($con_item); $reg_item = consulta_ler_linha($res_item); consulta_limpa($res_item); $cfop = $reg_item[0]; } if ( ($cfop == '1.201')|| ($cfop == '1.202')|| ($cfop == '1.203')|| ($cfop == '1.204')|| ($cfop == '1.208')|| ($cfop == '1.209')|| ($cfop == '1.410')|| ($cfop == '1.411')|| ($cfop == '1.503')|| ($cfop == '1.504')|| ($cfop == '1.553')|| ($cfop == '1.660')|| ($cfop == '1.661')|| ($cfop == '1.662')|| ($cfop == '1.903')|| ($cfop == '1.918')|| //($cfop == '1.921')|| ($cfop == '2.201')|| ($cfop == '2.202')|| ($cfop == '2.203')|| ($cfop == '2.204')|| ($cfop == '2.208')|| ($cfop == '2.209')|| ($cfop == '2.410')|| ($cfop == '2.411')|| ($cfop == '2.503')|| ($cfop == '2.504')|| ($cfop == '2.553')|| ($cfop == '2.660')|| ($cfop == '2.661')|| ($cfop == '2.662')|| ($cfop == '2.903')|| ($cfop == '2.918')|| //($cfop == '2.921')|| ($cfop == '3.201')|| ($cfop == '3.202')|| ($cfop == '3.211')|| ($cfop == '3.503')|| ($cfop == '3.553')|| ($cfop == '5.201')|| ($cfop == '5.202')|| ($cfop == '5.208')|| ($cfop == '5.209')|| ($cfop == '5.210')|| ($cfop == '5.410')|| ($cfop == '5.411')|| ($cfop == '5.412')|| ($cfop == '5.413')|| ($cfop == '5.503')|| ($cfop == '5.553')|| ($cfop == '5.555')|| ($cfop == '5.556')|| ($cfop == '5.660')|| ($cfop == '5.661')|| ($cfop == '5.662')|| ($cfop == '5.918')|| ($cfop == '5.921')|| ($cfop == '6.201')|| ($cfop == '6.202')|| ($cfop == '6.208')|| ($cfop == '6.209')|| ($cfop == '6.210')|| ($cfop == '6.410')|| ($cfop == '6.411')|| ($cfop == '6.412')|| ($cfop == '6.413')|| ($cfop == '6.503')|| ($cfop == '6.553')|| ($cfop == '6.555')|| ($cfop == '6.556')|| ($cfop == '6.660')|| ($cfop == '6.661')|| ($cfop == '6.662')|| ($cfop == '6.918')|| ($cfop == '6.921')|| ($cfop == '7.201')|| ($cfop == '7.202')|| ($cfop == '7.210')|| ($cfop == '7.211')|| ($cfop == '7.553')|| ($cfop == '7.556')|| ($cfop == '1.505')|| ($cfop == '1.506')|| ($cfop == '1.919')|| ($cfop == '2.505')|| ($cfop == '2.506')|| ($cfop == '2.919')|| ($cfop == '5.919')|| ($cfop == '6.919')){ $finalidade = '4'; } } } $ide->addAttribute('finNFe', $finalidade, false); $indFinal = '1'; $indPres = '1'; if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_nota->Modelo == '55'){ if (($finalidade=='2')|| ($finalidade=='3')){ $indPres = '0'; } if (substr(limpa_numero($reg_nota->Dest_CPF_CNPJ),0,8)== substr(limpa_numero($reg_nota->Empresa_CNPJ),0,8)){ $indFinal = '0'; if ($reg_nota->Dest_Insc_Estadual==''){ $indFinal = '1'; } }else if (strlen(limpa_numero($reg_nota->Dest_CPF_CNPJ))==14){ $indFinal = '0'; if ($reg_nota->Dest_Insc_Estadual==''){ $indFinal = '1'; if ($reg_nota->Dest_UF == 'EX'){ $indFinal = '0'; } }else{ //consulta tipo de pessoa $con_tp_pessoa = 'select Tipo_Cad_Pessoa from pessoa '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa="'.$reg_nota->Destinatario.'"'; $res_tp_pessoa = consulta_sql($con_tp_pessoa); $reg_tp_pessoa = consulta_ler_linha($res_tp_pessoa); consulta_limpa($res_tp_pessoa); if (($reg_tp_pessoa[0]=='3')||($reg_tp_pessoa[0]=='6')){ $indFinal = '0'; }else{ $indFinal = '1'; } } } if ($reg_nota->TipoES=='0'){ $indFinal = '0'; if ($reg_nota->Dest_Insc_Estadual==''){ $indFinal = '1'; } } } if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_nota->TipoES == '1'){ //se saida de vednda embarca $con_pres = 'select Nota_Empresa,Nota_Nr_Nota from nota_fiscal_refenciada '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Nota_Empresa>0 '. ' and Nota_Nr_Nota>0'; $res_pres = consulta_sql($con_pres); $reg_pres = consulta_ler_linha($res_pres); consulta_limpa($res_pres); if ($reg_pres[1]>0){ $con_pres = 'select Nat_Op_CFOP from nota_fiscal '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$reg_pres[1].'"'. ' and Nr_Nota = "'.$reg_pres[0].'"'; $res_pres = consulta_sql($con_pres); $reg_pres = consulta_ler_linha($res_pres); consulta_limpa($res_pres); if (($reg_pres[0]=='5.904')||($reg_pres[0]=='5.914')){ $indPres = '5';//venda embarcada } } } } $ide->addAttribute('indFinal', $indFinal, false); $ide->addAttribute('indPres', $indPres, false); } //NFe_Processo 0 - Apolicativo Contribuinte $ide->addAttribute('procEmi', '0', false); //versão do sistema if ($reg_nota->Empresa_UF == 'PR'){ $ide->addAttribute('verProc', '71411', false); //$ide->addAttribute('verProc', '03048-0', false); }else{ $ide->addAttribute('verProc', 'SIMPLES V W'.config_pad('sistema_versao'), false); } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_nota->NFe_Contigencia_Motivo != ''){ $dif_UTC = ''; if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //data de emissao //$uf = substr($reg_nota->NFe_Chave,0,2); $data = substr($reg_nota->NFe_Contigencia_DH,0,10); $dif_UTC = calcula_horario_verao($data,$uf); } //data hora da entrrada em contingência $ide->addAttribute('dhCont', str_replace(' ','T',$reg_nota->NFe_Contigencia_DH).$dif_UTC, false); //motivo $ide->addAttribute('xJust', $reg_nota->NFe_Contigencia_Motivo, false); } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $res_ref = consulta_sql($con_ref); $nrw_ref = consulta_num_registros($res_ref); //para cada documento referenciado for($ref=0;$ref<$nrw_ref;$ref++){ //adiciona dados das notas referenciadas $reg_ref = consulta_ler_objeto($res_ref); //tag do grupo de referencia if ($reg_ref->Tipo_Doc == 'E'){ //nota eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref->addAttribute('refNFe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'F'){ //nota ao comsumidor eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref->addAttribute('refNFe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'N'){ //nota normal $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refNF"); //consulta uf para saber o código da UF $con_uf = 'select Codigo_UF from uf '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and UF="'.$reg_ref->NF_UF.'"'; $res_uf = consulta_sql($con_uf); $reg_uf = consulta_ler_linha($res_uf); consulta_limpa($res_uf); //UF $nf_ref_n->addAttribute('cUF', fill_full($reg_uf[0],2), false); //ano mes $nf_ref_n->addAttribute('AAMM', nfe_ano_mes($reg_ref->NF_DT_Emissao,'AAMM'), false); //cnpj do emitente $nf_ref_n->addAttribute('CNPJ', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->NF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('serie', $reg_ref->NF_Serie, false); //nr de doc $nf_ref_n->addAttribute('nNF', $reg_ref->NF_Nr_Doc, false); } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_ref->Tipo_Doc == 'P'){ //nota de produtor $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refNFP"); //consulta uf para saber o código da UF $con_uf = 'select Codigo_UF from uf '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and UF="'.$reg_ref->NF_UF.'"'; $res_uf = consulta_sql($con_uf); $reg_uf = consulta_ler_linha($res_uf); consulta_limpa($res_uf); //UF $nf_ref_n->addAttribute('cUF', fill_full($reg_uf[0],2), false); //ano mes $nf_ref_n->addAttribute('AAMM', nfe_ano_mes($reg_ref->NF_DT_Emissao,'AAMM'), false); if (strlen($reg_ref->NF_Emitente_CNPJ)==18){ //cnpj do emitente $nf_ref_n->addAttribute('CNPJ', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); }else{ //cpf do emitente $nf_ref_n->addAttribute('CPF', limpa_numero($reg_ref->NF_Emitente_CNPJ), false); } //inscricao de produtor $nf_ref_n->addAttribute('IE', substr(limpa_numero2($reg_ref->NF_Emitente_IE),0,14), false); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->NF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('serie', $reg_ref->NF_Serie, false); //nr de doc $nf_ref_n->addAttribute('nNF', $reg_ref->NF_Nr_Doc, false); }else if ($reg_ref->Tipo_Doc == 'T'){ //conehcimento de transporte eletronica $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref->addAttribute('refCTe', $reg_ref->NFe_Chave, false); }else if ($reg_ref->Tipo_Doc == 'C'){ //cupom fiscal $nf_ref = &$ide->addChild("NFref"); //chave da NFe $nf_ref_n = &$nf_ref->addChild("refECF"); //modelo de doc $nf_ref_n->addAttribute('mod', fill_full($reg_ref->ECF_Modelo,2), false); //série de doc $nf_ref_n->addAttribute('nECF', $reg_ref->ECF_Caixa, false); //nr de doc $nf_ref_n->addAttribute('nCOO', $reg_ref->ECF_COO, false); } } } consulta_limpa($res_ref); } //adiciona dados do emitente $emit = &$nf_inf->addChild("emit"); if (strlen(limpa_numero($reg_nota->Empresa_CNPJ))==14){ //cnpj do emitente $emit->addAttribute('CNPJ', limpa_numero($reg_nota->Empresa_CNPJ), false); }else{ //cpf emitente //cpf do emitente $emit->addAttribute('CPF', limpa_numero($reg_nota->Empresa_CNPJ), false); } //nome/razao $emit->addAttribute('xNome', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Razao,0,60)), false); if (($reg_nota->Empresa_Fantasia != '')&& (strlen($reg_nota->Empresa_CNPJ)>14)){ //fantasia $emit->addAttribute('xFant', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Fantasia,0,60)), false); } //endereco do emitente $emit_end = &$emit->addChild("enderEmit"); //logradouro $emit_end->addAttribute('xLgr', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Logradouro,0,60)), false); //numero if (trim($reg_nota->Empresa_Numero) != ''){ $emit_end->addAttribute('nro', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Numero,0,60)), false); }else{ $emit_end->addAttribute('nro', 'S/N', false); } //complemento if (trim($reg_nota->Empresa_Complemento) != ''){ $emit_end->addAttribute('xCpl', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Complemento,0,60)), false); } //bairro $emit_end->addAttribute('xBairro', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Bairro,0,60)), false); //nr cidade $emit_end->addAttribute('cMun', $reg_nota->Empresa_Codigo_Cidade, false); //nome cidade $emit_end->addAttribute('xMun', trim(nfe_retira_texto_excesso($reg_nota->Empresa_Nome_Cidade,0,60)), false); //uf $emit_end->addAttribute('UF', $reg_nota->Empresa_UF, false); //CEP if (($reg_nota->Empresa_CEP != '00000-000')&& (limpa_numero($reg_nota->Empresa_CEP) != '')){ $emit_end->addAttribute('CEP', limpa_numero($reg_nota->Empresa_CEP), false); } //cod país $emit_end->addAttribute('cPais', $reg_nota->Empresa_Codigo_Pais, false); //nome país $emit_end->addAttribute('xPais', $reg_nota->Empresa_Nome_Pais, false); if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //telefone if (limpa_numero($reg_nota->Empresa_Telefone_Nr) != ''){ $emit_end->addAttribute('fone', nfe_retira_texto_excesso(limpa_numero($reg_nota->Empresa_Telefone_Nr),0,20), false); } } //demais dados do emitente //IE $emit->addAttribute('IE', substr(limpa_numero2($reg_nota->Empresa_Insc_Estadual),0,14), false); //IE ST if ($reg_nota->Modelo == '55'){ //IE_ST não vale pra NFC-e if (limpa_numero($reg_nota->Empresa_IE_ST) != ''){ $emit->addAttribute('IEST', substr(limpa_numero2($reg_nota->Empresa_IE_ST),0,14), false); } } //IM if ((limpa_numero($reg_nota->Empresa_IM) != '')&& (limpa_numero($reg_nota->Empresa_CNAE) != '')){ $emit->addAttribute('IM', substr(limpa_numero($reg_nota->Empresa_IM),0,15), false); //} //CNAE //if (limpa_numero($reg_nota->Empresa_CNAE) != ''){ $emit->addAttribute('CNAE', fill_full(substr(limpa_numero($reg_nota->Empresa_CNAE),0,7),7), false); } //regime Simples Nacional if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_nota->Empresa_CRT == 'S'){ $regime = '1'; //simples nacional }else{ $regime = '3'; //normal } $emit->addAttribute('CRT', $regime, false); } //adiciona dados do destinatário if (($reg_nota->Modelo=='65')&&($reg_nota->Destinatario==0)){ }else{ //echo 'reg_nfe-MOdelo;'.$reg_nota->Modelo.'-'.$reg_nota->Destinatario; $dest = &$nf_inf->addChild("dest"); if ($reg_nota->Dest_UF == 'EX'){ if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $dest->addAttribute('idEstrangeiro', substr($reg_nota->Dest_Insc_Estadual,0,20), false); }else{ $dest->addAttribute('CNPJ', '', false); } }else{ //if ($reg_nota->NFe_Ambiente=='2'){ // $dest->addAttribute('CNPJ', '99999999000191', false); //}else if (strlen(limpa_numero($reg_nota->Dest_CPF_CNPJ))==14){ //cnpj do emitente $dest->addAttribute('CNPJ', limpa_numero($reg_nota->Dest_CPF_CNPJ), false); }else{ //cpf emitente //cpf do emitente $dest->addAttribute('CPF', limpa_numero($reg_nota->Dest_CPF_CNPJ), false); } } //nome/razao if ($reg_nota->NFe_Ambiente=='2'){ $dest->addAttribute('xNome', 'NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL', false); }else{ //$texto = nfe_retira_texto_excesso($reg_nota->Dest_Razao,0,60); $texto = $reg_nota->Dest_Razao; if($_SESSION['Dominio'] == $dominios['205']){ //$texto2 = nfe_retira_texto_excesso($reg_nota->Dest_Fantasia,0,60); $texto2 = $reg_nota->Dest_Fantasia; if($texto != $texto2){ $texto.= ' / '.$texto2; } } $dest->addAttribute('xNome', nfe_retira_texto_excesso($texto,0,60), false); } //endereco do destinatario if (($reg_nota->Modelo=='65')&&($reg_nota->Dest_Endereco==0)){ }else{ $dest_end = &$dest->addChild("enderDest"); //logradouro $dest_end->addAttribute('xLgr', trim(nfe_retira_texto_excesso($reg_nota->Dest_Logradouro,0,60)), false); //numero if (trim($reg_nota->Dest_Numero) != ''){ $dest_end->addAttribute('nro', trim(nfe_retira_texto_excesso($reg_nota->Dest_Numero,0,60)), false); }else{ $dest_end->addAttribute('nro', 'S/N', false); } //complemento if (trim($reg_nota->Dest_Complemento) != ''){ $dest_end->addAttribute('xCpl', trim(nfe_retira_texto_excesso($reg_nota->Dest_Complemento,0,60)), false); } if ($reg_nota->Dest_UF =='EX'){ //bairro $dest_end->addAttribute('xBairro', trim(nfe_retira_texto_excesso($reg_nota->Dest_Bairro.'-'.$reg_nota->Dest_Nome_Cidade.'-'.$reg_nota->Dest_Nome_Pais,0,60)), false); //nr cidade $dest_end->addAttribute('cMun', '9999999', false); //nome cidade $dest_end->addAttribute('xMun', 'EXTERIOR', false); //uf $dest_end->addAttribute('UF', 'EX', false); //CEP //if (($reg_nota->Dest_CEP != '00000-000')&& // (limpa_numero($reg_nota->Dest_CEP) != '')){ // $dest_end->addAttribute('CEP', limpa_numero($reg_nota->Dest_CEP), false); //} //cod país $dest_end->addAttribute('cPais', $reg_nota->Dest_Codigo_Pais, false); //nome país $dest_end->addAttribute('xPais', trim($reg_nota->Dest_Nome_Pais), false); }else{ //bairro $dest_end->addAttribute('xBairro', trim(nfe_retira_texto_excesso($reg_nota->Dest_Bairro,0,60)), false); //nr cidade $dest_end->addAttribute('cMun', $reg_nota->Dest_Codigo_Cidade, false); //nome cidade $dest_end->addAttribute('xMun', nfe_retira_texto_excesso($reg_nota->Dest_Nome_Cidade,0,60), false); //uf $dest_end->addAttribute('UF', $reg_nota->Dest_UF, false); //CEP if (($reg_nota->Dest_CEP != '00000-000')&& (limpa_numero($reg_nota->Dest_CEP) != '')){ $dest_end->addAttribute('CEP', limpa_numero($reg_nota->Dest_CEP), false); } //cod país //$dest_end->addAttribute('cPais', $reg_nota->Dest_Codigo_Pais, false); //nome país //$dest_end->addAttribute('xPais', $reg_nota->Dest_Nome_Pais, false); } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //telefone if (limpa_numero($reg_nota->Dest_Telefone_Nr) != ''){ $dest_end->addAttribute('fone', nfe_retira_texto_excesso(limpa_numero($reg_nota->Dest_Telefone_Nr),0,20), false); } } } //demais dados do destinatario //IE //if ($reg_nota->NFe_Ambiente=='2'){ // $dest->addAttribute('IE', '', false); //}else{ if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $indIEDest='9'; if (($reg_nota->Dest_UF =='EX')||($reg_nota->Modelo =='65')){ $indIEDest='9'; }else if ($reg_nota->Dest_Insc_Estadual=='ISENTO'){ $indIEDest='2'; }else if ($reg_nota->Dest_Insc_Estadual=='ISENTA'){ $indIEDest='2'; }else if (substr(limpa_numero2($reg_nota->Dest_Insc_Estadual),0,14)!=''){ $indIEDest='1'; } $X_indIEDest = $indIEDest; $ie_Cliente = $reg_nota->Dest_Insc_Estadual; if ($X_indIEDest=='1'){ IF (substr($reg_nota->Dest_Insc_Estadual,0,2)=='NC'){ $indIEDest = '9'; $ie_Cliente = substr($ie_Cliente,2,20); } } $dest->addAttribute('indIEDest', $indIEDest, false); if ($X_indIEDest=='1'){ $dest->addAttribute('IE', substr(limpa_numero2($ie_Cliente),0,14), false); } }else{ if ($reg_nota->Dest_UF =='EX'){ $dest->addAttribute('IE', '', false); }else{ $dest->addAttribute('IE', substr(limpa_numero2($reg_nota->Dest_Insc_Estadual),0,14), false); } } //SUFRAMA if (limpa_numero($reg_nota->Dest_Suframa) != ''){ $dest->addAttribute('ISUF', substr(fill_full(limpa_numero($reg_nota->Dest_Suframa),9),0,9), false); } //todo 3.10 IM if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //EMail if ($reg_nota->Dest_EMail != ''){ $dest->addAttribute('email', trim(nfe_retira_texto_excesso($reg_nota->Dest_EMail,0,60)), false); } } } //adiciona dados da retirada/entrega $diferente = false; $dados_partilha = ( (($ie_Cliente=='')||(substr($reg_nota->Dest_Insc_Estadual,0,2)=='NC')) && ((substr($reg_nota->Nat_Op_CFOP,0,1) == '6')||((substr($reg_nota->Nat_Op_CFOP,0,1) == '2')&&($reg_nota->Total_ICMS_Dest>0))) ); $dados_partilha2 = BuscaParam('CALC_ICMS_PARTILHA'); if ($reg_nota->BuscaEntrega_Endereco != 0){ if ($reg_nota->BuscaEntrega == 'B'){ if (($reg_nota->BuscaEntrega_Local != $reg_nota->Empresa)|| ($reg_nota->BuscaEntrega_Endereco != $reg_nota->Empresa_Endereco)){ $diferente = true; if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if (strlen(limpa_numero($reg_nota->BuscaEntrega_CPF_CNPJ))!=14){ $diferente = false; } } if ($diferente){ $local = &$nf_inf->addChild("retirada"); } } }else if ($reg_nota->BuscaEntrega == 'E'){ if ($reg_nota->BuscaEntrega_Endereco != $reg_nota->Dest_Endereco ){ $diferente = true; if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if (strlen(limpa_numero($reg_nota->BuscaEntrega_CPF_CNPJ))!=14){ $diferente = false; } } if ($diferente){ $local = &$nf_inf->addChild("entrega"); } } } } if ($diferente){ //if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if (strlen(limpa_numero($reg_nota->BuscaEntrega_CPF_CNPJ))==14){ //cnpj do local entrega/busca $local->addAttribute('CNPJ', limpa_numero($reg_nota->BuscaEntrega_CPF_CNPJ ), false); }else{ //cpf do local entrega/busca $local->addAttribute('CPF', limpa_numero($reg_nota->BuscaEntrega_CPF_CNPJ ), false); } //} $local->addAttribute('xLgr', trim(nfe_retira_texto_excesso($reg_nota->BuscaEntrega_Logradouro,0,60)), false); //numero if (trim($reg_nota->BuscaEntrega_Numero) != ''){ $local->addAttribute('nro', trim(nfe_retira_texto_excesso($reg_nota->BuscaEntrega_Numero,0,60)), false); }else{ $local->addAttribute('nro', 'S/N', false); } //complemento if (trim($reg_nota->BuscaEntrega_Complemento) != ''){ $local->addAttribute('xCpl', trim(nfe_retira_texto_excesso($reg_nota->BuscaEntrega_Complemento,0,60)), false); } if ($reg_nota->BuscaEntrega_UF =='EX'){ //bairro $local->addAttribute('xBairro', trim(substr($reg_nota->BuscaEntrega_Bairro.'-'.$reg_nota->BuscaEntrega_Nome_Cidade,0,60)), false); //nr cidade $local->addAttribute('cMun', '9999999', false); //nome cidade $local->addAttribute('xMun', 'EXTERIOR', false); //uf $local->addAttribute('UF', 'EX', false); }else{ //bairro $local->addAttribute('xBairro', trim(nfe_retira_texto_excesso($reg_nota->BuscaEntrega_Bairro,0,60)), false); //nr cidade $local->addAttribute('cMun', $reg_nota->BuscaEntrega_Codigo_Cidade, false); //nome cidade $local->addAttribute('xMun', trim(nfe_retira_texto_excesso($reg_nota->BuscaEntrega_Nome_Cidade,0,60)), false); //uf $local->addAttribute('UF', $reg_nota->BuscaEntrega_UF, false); } } //autxaml /* $con_pessoa_empresa = 'select AUT_XML from pessoa_empresa '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa = "'.$reg_nota->Empresa.'"'; $res_pessoa_empresa = consulta_sql($con_pessoa_empresa); $reg_pessoa_empresa = consulta_ler_linha($res_pessoa_empresa); consulta_limpa($res_pessoa_empresa);*/ $conteudo_xml = BuscaParamEmpresa('AUT_XML',$reg_nota->Empresa); if($conteudo_xml!=''){ $lista_aut_xml = explode(';',$conteudo_xml); } if(count($lista_aut_xml)>0){ $cont_aut = 0; foreach ($lista_aut_xml as $cpf_cnpj){ if ($cpf_cnpj != ''){ if($cont_aut<=10){ $aut = &$nf_inf->addChild("autXML"); $cpf_cnpj = limpa_numero($cpf_cnpj); if(strlen($cpf_cnpj)==14){ $aut->addAttribute('CNPJ', $cpf_cnpj, false); }else if(strlen($cpf_cnpj)==11){ $aut->addAttribute('CPF', $cpf_cnpj, false); } $cont_aut++; } } } } $fixacao = false; $con_itens = 'select * from nota_fiscal_item_ref'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Campo="Qtd_Fixar"'. ' limit 1'; $res_itens = consulta_sql($con_itens); $fixacao = (consulta_num_registros($res_itens)>0); consulta_limpa($res_itens); $total_produtos = 0; $val_impo_total = 0; $valor_total_item = 0; $total_diferido = 0; //consulta itens da NF $con_itens = 'select * from nota_fiscal_item'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' order by Seq_Item'; $res_itens = consulta_sql($con_itens); $nrw_itens = consulta_num_registros($res_itens); //para cada item da nota for($itens=0;$itens<$nrw_itens;$itens++){ $reg_itens = consulta_ler_objeto($res_itens); //adiciona dados dos itens ao arquivo $det = &$nf_inf->addChild("det"); //seq do item na NF $det->addAttribute('nItem', ($itens+1), true); //dados do produto $prod = &$det->addChild("prod"); //código do produto/serviço if ($reg_itens->Codigo_Produto==''){ //não é um produto (caso de complementação) $prod->addAttribute('cProd', 'CFOP'.limpa_numero($reg_itens->CFOP), false); }else{ $prod->addAttribute('cProd', $reg_itens->Codigo_Produto, false); } //if ((strlen($reg_itens->Barra_Produto) == 8) || // (strlen($reg_itens->Barra_Produto) >= 12)){ $barras = ''; $barra_produto_validator = new BarcodeValidator($reg_itens->Barra_Produto); if ($barra_produto_validator->isValid()){ $barras = $reg_itens->Barra_Produto; } if($barras == ''){ $cons_barra = 'SELECT * from produto_cod_barras '. ' WHERE Dominio = "'.$_SESSION["Dominio"].'"'. ' AND Id_Produto = "'.$reg_itens->Id_Produto.'"'. ' AND Codigo_Barras = "'.$reg_itens->Barra_Produto.'"'; $res_barra = consulta_sql($cons_barra); $reg_barra = consulta_ler_objeto($res_barra); consulta_limpa($res_barra); if($reg_barra->Barra_NFe != ''){ $barra_nfe_validator = new BarcodeValidator($reg_barra->Barra_NFe); if($barra_nfe_validator->isValid()){ $barras = $reg_barra->Barra_NFe; } } } /* if (valida_ean($reg_itens->Barra_Produto)){ $barras = $reg_itens->Barra_Produto; } */ if ($reg_nota->NFe_Versao == '4.00'){ if ($barras == ''){ $barras = 'SEM GTIN'; } } //if (valida_ean($reg_itens->Barra_Produto)){ // $prod->addAttribute('cEAN', $reg_itens->Barra_Produto, false); //}else{ $prod->addAttribute('cEAN', $barras, false); //} $descricao = trim(nfe_retira_texto_excesso($reg_itens->Prod_Descricao,0,120)); if (($reg_nota->Modelo == '65') && ($reg_nota->NFe_Ambiente=='2')){ $descricao = 'NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL'; } //NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL $prod->addAttribute('xProd', $descricao, false); if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //ncm if ($reg_itens->Prod_Depart == 0){ //serviço $prod->addAttribute('NCM', '99', false); }else{ //produto $prod->addAttribute('NCM', limpa_numero($reg_itens->Prod_NCM), false); //cest if (($reg_itens->ICMS_CST=='10')|| ($reg_itens->ICMS_CST=='30')|| ($reg_itens->ICMS_CST=='60')|| ($reg_itens->ICMS_CST=='70')|| ($reg_itens->ICMS_CST=='90')|| ($reg_itens->ICMS_CST=='201')|| ($reg_itens->ICMS_CST=='202')|| ($reg_itens->ICMS_CST=='203')|| ($reg_itens->ICMS_CST=='500')|| ($reg_itens->ICMS_CST=='900')){ $cod_cest = limpa_numero($reg_itens->Prod_CEST); if ($cod_cest!=''){ if (($reg_nota->NFe_Ambiente=='2')|| (data2nr(dataf($reg_nota->DH_Emissao))>= data2nr('01/01/2016')) ){ $prod->addAttribute('CEST', limpa_numero($reg_itens->Prod_CEST), false); } } } //ICMS_Benif FabricaEscala FabricaCNPJ if ($reg_nota->NFe_Versao == '4.00') { if (nota_fiscal_valida_ncm_escala($reg_itens->Prod_NCM)){ $indEscala = $reg_itens->FabricaEscala; if ($indEscala==''){ $indEscala = 'N'; } if ($indEscala=='R'){ $indEscala = 'S'; } $CNPJEscala = limpa_numero($reg_itens->FabricaCNPJ); if ($indEscala=='S'){ $CNPJEscala = ''; }else{ if ($CNPJEscala==''){ $CNPJEscala = limpa_numero($reg_nota->Emp_CNPJ); } } $prod->addAttribute('indEscala', $indEscala, false); if ($CNPJEscala!=''){ $prod->addAttribute('CNPJFab', $CNPJEscala, false); } } if ($reg_itens->ICMS_Benif!=''){ $prod->addAttribute('cBenef', $reg_itens->ICMS_Benif, false); } } if ($reg_itens->Prod_NCM_Ex != ''){ //ex $prod->addAttribute('EXTIPI', fill_full($reg_itens->Prod_NCM_Ex,2), false); } } }else{ //ncm if ($reg_itens->Prod_Depart != 0){ //é produto if (strlen(limpa_numero($reg_itens->Prod_NCM)) == 8){ $prod->addAttribute('NCM', limpa_numero($reg_itens->Prod_NCM), false); if ($reg_itens->Prod_NCM_Ex != ''){ //ex $prod->addAttribute('EXTIPI', fill_full($reg_itens->Prod_NCM_Ex,2), false); } } if ((strlen(limpa_numero($reg_itens->Prod_NCM)) == 8)|| (strlen(limpa_numero($reg_itens->Prod_NCM)) == 2)){ //genero $prod->addAttribute('genero', substr($reg_itens->Prod_NCM,0,2), false); } } } //cfop $prod->addAttribute('CFOP', limpa_numero($reg_itens->CFOP), false); //unidade de medida $valor_unitario = $reg_itens->Valor_Unitario; $Qtd = $reg_itens->Quantidade_Estoque; $unid_medida = trim($reg_itens->Unidade_Estoque); if($param_unid_fisco=='S'){ $con_uni = 'select Unidade_Fisco from unidade_medida '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Unidade="'.trim($reg_itens->Unidade_Estoque).'"'; $res_uni = consulta_sql($con_uni); $reg_uni = consulta_ler_linha($res_uni); consulta_limpa($res_uni); if($reg_uni[0]!=''){ $unid_medida = $reg_uni[0]; } } $unid_trib = $unid_medida; if($param_unid_kg=='S'){ if (($idDest==3)|| (limpa_numero($reg_itens->CFOP)=='1501')|| (limpa_numero($reg_itens->CFOP)=='2501')|| (limpa_numero($reg_itens->CFOP)=='5501')|| (limpa_numero($reg_itens->CFOP)=='5502')|| (limpa_numero($reg_itens->CFOP)=='5504')|| (limpa_numero($reg_itens->CFOP)=='5505')|| (limpa_numero($reg_itens->CFOP)=='6501')|| (limpa_numero($reg_itens->CFOP)=='6502')|| (limpa_numero($reg_itens->CFOP)=='6504')|| (limpa_numero($reg_itens->CFOP)=='6505')){ if ( (limpa_numero($reg_itens->Prod_NCM)=='12019000')|| (limpa_numero($reg_itens->Prod_NCM)=='15071000')|| (limpa_numero($reg_itens->Prod_NCM)=='15079011')|| (limpa_numero($reg_itens->Prod_NCM)=='15079019')|| (limpa_numero($reg_itens->Prod_NCM)=='15079090')|| (limpa_numero($reg_itens->Prod_NCM)=='17011300')|| (limpa_numero($reg_itens->Prod_NCM)=='17011400')|| (limpa_numero($reg_itens->Prod_NCM)=='17019900')|| (limpa_numero($reg_itens->Prod_NCM)=='18010000')|| (limpa_numero($reg_itens->Prod_NCM)=='18031000')|| (limpa_numero($reg_itens->Prod_NCM)=='18032000')|| (limpa_numero($reg_itens->Prod_NCM)=='18040000')|| (limpa_numero($reg_itens->Prod_NCM)=='18050000')|| (limpa_numero($reg_itens->Prod_NCM)=='21011110')|| (limpa_numero($reg_itens->Prod_NCM)=='21011190')|| (limpa_numero($reg_itens->Prod_NCM)=='21011200')|| (limpa_numero($reg_itens->Prod_NCM)=='23040010')|| (limpa_numero($reg_itens->Prod_NCM)=='23040090')|| (limpa_numero($reg_itens->Prod_NCM)=='52010010')|| (limpa_numero($reg_itens->Prod_NCM)=='52010020')|| (limpa_numero($reg_itens->Prod_NCM)=='52010090')|| (limpa_numero($reg_itens->Prod_NCM)=='74031100')|| (limpa_numero($reg_itens->Prod_NCM)=='74031200')|| (limpa_numero($reg_itens->Prod_NCM)=='74031300')|| (limpa_numero($reg_itens->Prod_NCM)=='74031900')|| (limpa_numero($reg_itens->Prod_NCM)=='75021010')|| (limpa_numero($reg_itens->Prod_NCM)=='75021090')|| (limpa_numero($reg_itens->Prod_NCM)=='76011000')|| (limpa_numero($reg_itens->Prod_NCM)=='78011011')|| (limpa_numero($reg_itens->Prod_NCM)=='78011019')|| (limpa_numero($reg_itens->Prod_NCM)=='78011090')|| (limpa_numero($reg_itens->Prod_NCM)=='78019100')|| (limpa_numero($reg_itens->Prod_NCM)=='78019900')|| (limpa_numero($reg_itens->Prod_NCM)=='79011111')|| (limpa_numero($reg_itens->Prod_NCM)=='79011119')|| (limpa_numero($reg_itens->Prod_NCM)=='79011191')|| (limpa_numero($reg_itens->Prod_NCM)=='79011199')|| (limpa_numero($reg_itens->Prod_NCM)=='79011210')|| (limpa_numero($reg_itens->Prod_NCM)=='79011290')|| (limpa_numero($reg_itens->Prod_NCM)=='79012010')|| (limpa_numero($reg_itens->Prod_NCM)=='79012090')|| (limpa_numero($reg_itens->Prod_NCM)=='80011000')){ $unid_medida = 'TON'; $unid_trib = 'TON'; }else if (trim($reg_itens->Unidade_Estoque)=='TO'){ //passar para KG $unid_medida = 'KG'; $unid_trib = 'KG'; $Qtd = ($reg_itens->Quantidade_Estoque*1000); $valor_unitario = ($reg_itens->Valor_Unitario/1000); } if(trim($reg_itens->Unidade_Estoque)=='UN'){ $unid_medida = 'UN'; $unid_trib = 'UN'; } if(trim($reg_itens->Prod_NCM)=='9027.90.99'){ $unid_trib = 'KG'; } } } $prod->addAttribute('uCom', trim($unid_medida), false); if ($Qtd <= 0){ $valor_unitario = 0; } if (($Qtd==0)&&($finalidade==1)){ $Qtd = 1; $valor_unitario = $reg_itens->Valor_Unitario; } //quantidade $prod->addAttribute('qCom', nfe_numero($Qtd,4), false); //4 digitos //valor unitário $prod->addAttribute('vUnCom', nfe_numero($valor_unitario,4), false); //4 digitos //valor total if (($reg_itens->Compoe_Total != 'N')||($finalidade==1)){ //if (($reg_itens->Quantidade_Estoque > 0 )||($fixacao)) { $prod->addAttribute('vProd', nfe_numero(($reg_itens->Valor_Total+$reg_itens->Valor_Desconto),2), false); $total_produtos+= ($reg_itens->Valor_Total+$reg_itens->Valor_Desconto); }else{ $prod->addAttribute('vProd', nfe_numero(0,2), false); } ///ean da unidade tributável //if (valida_ean($reg_itens->Barra_Produto)){ // $prod->addAttribute('cEANTrib', $reg_itens->Barra_Produto, false); //}else{ $prod->addAttribute('cEANTrib', $barras, false); //} //unidade tributável $prod->addAttribute('uTrib', trim($unid_trib), false); //qauntidade tributável $prod->addAttribute('qTrib', nfe_numero($Qtd,4), false); //unidario tributavel $prod->addAttribute('vUnTrib', nfe_numero($valor_unitario,4), false); //frete if ($reg_itens->Valor_Frete>0){ $prod->addAttribute('vFrete', nfe_numero($reg_itens->Valor_Frete,2), false); } //seguro if ($reg_itens->Valor_Seguro>0){ $prod->addAttribute('vSeg', nfe_numero($reg_itens->Valor_Seguro,2), false); } //desconto if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->Valor_Desconto>0){ $prod->addAttribute('vDesc', nfe_numero($reg_itens->Valor_Desconto,2), false); } }else{ if (($reg_itens->Valor_Desconto+$reg_itens->ICMS_Desonerado_Valor)>0){ $prod->addAttribute('vDesc', nfe_numero(($reg_itens->Valor_Desconto+$reg_itens->ICMS_Desonerado_Valor),2), false); } } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //outros if ($reg_itens->Valor_Outros>0){ $prod->addAttribute('vOutro', nfe_numero($reg_itens->Valor_Outros,2), false); } //Compõe valor total da NF if ($reg_itens->Compoe_Total == 'N'){ $prod->addAttribute('indTot', '0', false); }else{ $prod->addAttribute('indTot', '1', false); } } //se tiver DI if ($reg_itens->Importa_Nr_DI >0){ //consulta DI (se tiver) $consulta_di = 'select * from nota_fiscal_di '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Nr_DI="'.$reg_itens->Importa_Nr_DI.'"'; $res_di = consulta_sql($consulta_di); $reg_di = consulta_ler_objeto($res_di); consulta_limpa($res_di); $dec_imp = &$prod->addChild("DI"); //adiciona dados da DI $dec_imp->addAttribute('nDI', $reg_di->Importa_DI_Nr, false); $dec_imp->addAttribute('dDI', $reg_di->Importa_DI_DT_Registro, false); $dec_imp->addAttribute('xLocDesemb', trim(substr($reg_nota->Importa_Exporta_Local,0,60)), false); $dec_imp->addAttribute('UFDesemb', $reg_nota->Importa_Exporta_UF, false); $dec_imp->addAttribute('dDesemb', $reg_di->Importa_DI_DT_Desembaraco, false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $dec_imp->addAttribute('tpViaTransp', $reg_di->Importa_ViaTransp, false); if ($reg_di->Importa_ViaTransp==1){ $dec_imp->addAttribute('vAFRMM', nfe_numero($reg_itens->Importa_Marinha,2), false); //$dec_imp->addAttribute('vAFRMM', nfe_numero($reg_itens->Valor_Outros,2), false); } $dec_imp->addAttribute('tpIntermedio', $reg_di->Importa_Intermedio, false); if ($reg_di->Importa_Intermedio!='1'){ $dec_imp->addAttribute('CNPJ', limpa_numero($reg_di->Importa_Terceiro_CNPJ), false); $dec_imp->addAttribute('UFTerceiro', $reg_di->Importa_Terceiro_UF, false); } } $dec_imp->addAttribute('cExportador', $reg_di->Importa_DI_Exportador , false); $dec_imp_item = &$dec_imp->addChild("adi"); $dec_imp_item->addAttribute('nAdicao', $reg_itens->Importa_Adicao, false); $dec_imp_item->addAttribute('nSeqAdic', $reg_itens->Seq_Pedido_Dest, false); $dec_imp_item->addAttribute('cFabricante', $reg_itens->Importa_Fabricante, false); if ($reg_itens->Importa_Desconto>0){ $dec_imp_item->addAttribute('vDescDI', $reg_itens->Importa_Desconto, false); } } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->Nr_Pedido_Dest!=''){ $prod->addAttribute('xPed', $reg_itens->Nr_Pedido_Dest, false); if ($reg_itens->Seq_Pedido_Dest >0){ $prod->addAttribute('nItemPed', $reg_itens->Seq_Pedido_Dest, false); } }else if ($reg_nota->Pedido_Dest!=''){ $prod->addAttribute('xPed', $reg_nota->Pedido_Dest, false); if ($reg_itens->Seq_Pedido_Dest >0){ $prod->addAttribute('nItemPed', $reg_itens->Seq_Pedido_Dest, false); } } if ($reg_itens->FCI!=''){ $prod->addAttribute('nFCI', $reg_itens->FCI, false); } } if ($reg_nota->NFe_Versao == '4.00'){ // /*{ rastro nLote qLot dFab dVal cAgreg */ if (($reg_itens->NrLote != '')&& ($reg_itens->DT_Fabricacao != '0000-00-00')&& ($reg_itens->DT_Validade != '0000-00-00')){ $rastro = &$prod->addChild("rastro"); $rastro->addAttribute('nLote', trim(nfe_retira_texto_excesso($reg_itens->NrLote,0,20)), false); $rastro->addAttribute('qLote', nfe_numero($Qtd,3), false); $rastro->addAttribute('dFab', $reg_itens->DT_Fabricacao, false); $rastro->addAttribute('dVal', $reg_itens->DT_Validade, false); //if ($reg_itens->Peneira != ''){ // $rastro->addAttribute('cAgreg', trim(nfe_retira_texto_excesso($reg_itens->Peneira,0,20)), false); //} } } //na primeira fase não vai ter isso //adciona dados epecíficos (carros) //adciona dados epecíficos (med) //adciona dados epecíficos (armas) //adciona dados epecíficos (combustível) if (trim($reg_itens->Comb_ANP) != ''){//tem ANP $comb = &$prod->addChild("comb"); $comb->addAttribute('cProdANP', trim($reg_itens->Comb_ANP), false); if ($reg_nota->NFe_Versao == '4.00'){ $comb->addAttribute('descANP', str_replace($reg_itens->Comb_ANP.' - ','',busca_dados_combo('comb_anp',$reg_itens->Comb_ANP)), false); if ($reg_itens->Comb_ANP == '210203001'){ //$comb->addAttribute('pGLP', nfe_numero($reg_itens->Comb_pGLP,4), false); //$comb->addAttribute('pGNn', nfe_numero($reg_itens->Comb_pGNn,4), false); //$comb->addAttribute('pGNi', nfe_numero($reg_itens->Comb_pGNi,4), false); //$comb->addAttribute('vPart', nfe_numero($reg_itens->Comb_vPart,2), false); if ($reg_itens->Quantidade_Estoque>0){ $comb_vPart = arredonda_numero_menos( (($reg_itens->Valor_Total+$reg_itens->Valor_Desconto-$reg_itens->ICMS_Valor)/$reg_itens->Quantidade_Estoque) *100)/100; }else{ $comb_vPart = arredonda_numero_menos( (($reg_itens->Valor_Total+$reg_itens->Valor_Desconto-$reg_itens->ICMS_Valor)) *100)/100; } $comb->addAttribute('pGLP', nfe_numero(100,4), false); //$comb->addAttribute('pGNn', nfe_numero(0,4), false); //$comb->addAttribute('pGNi', nfe_numero(0,4), false); $comb->addAttribute('vPart', nfe_numero($comb_vPart,2), false); //162b1 LA03 descANP Descrição do produto conforme ANP E //LA01 C 1-1 2-95 Utilizar a descrição de produtos do Sistema de Informações de // Movimentação de Produtos - SIMP (http://www.anp.gov.br/simp/). //162b2 LA03a pGLP Percentual do GLP derivado do // petróleo no produto GLP (cProdANP=210203001) E LA01 N 0-1 3v4 // Informar em número decimal o percentual do GLP derivado de // petróleo no produto GLP. Valores de 0 a 100. //162b3 LA03b pGNn Percentual de Gás Natural Nacional – GLGNn para o produto GLP // (cProdANP=210203001) E LA01 N 0-1 3v4 Informar em número decimal o // percentual do Gás Natural Nacional – GLGNn para o produto GLP. // Valores de 0 a 100. // 162b4 LA03c pGNi Percentual de Gás Natural Importado – GLGNi para o produto // GLP (cProdANP=210203001) E LA01 N 0-1 3v4 Informar em número decimal // o percentual do Gás Natural Importado – GLGNi para o produto GLP. // Valores de 0 a 100. //162b5 LA03d vPart Valor de partida (cProdANP=210203001) E LA01 N 0-1 13v2 // Deve ser informado neste campo o valor por quilograma sem ICMS. } } if (trim($reg_itens->Comb_CODIF) != ''){//tem CODIF $comb->addAttribute('CODIF', trim($reg_itens->Comb_CODIF), false); } if ($reg_itens->Comb_Qtd_TempAbmviente>0){//tem Comb_Qtd_TempAbmviente $comb->addAttribute('qTemp', nfe_numero($reg_itens->Comb_Qtd_TempAbmviente,2), false); } $comb->addAttribute('UFCons', trim($reg_itens->Comb_UFConsumo), false); if ($reg_itens->CIDE_Valor>0){//tem CIDE_Valor $CIDE = &$comb->addChild("CIDE"); $CIDE->addAttribute('qBCProd', nfe_numero($reg_itens->CIDE_BC,4), false); $CIDE->addAttribute('vAliqProd', nfe_numero($reg_itens->CIDE_Percentual,4), false); $CIDE->addAttribute('vCIDE', nfe_numero($reg_itens->CIDE_Valor,2), false); } } //adiciona dados dos impostos (ICMS,IPI,PIS,COFINS,ISS) $imposto = &$det->addChild("imposto"); if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->Perc_Tributos>0){ $total_item = $reg_itens->Valor_Total - $reg_itens->ICMS_Desonerado_Valor; if ((substr($reg_itens->CFOP,0,1)=='3')&& ($reg_itens->Valor_Agregado > 0 )){ $total_item = $reg_itens->Valor_Agregado; }else{ $total_item+= $reg_itens->ICMSST_Valor; //if ($reg_itens->ICMS_BC_Adic_Frete=='S') { $total_item+= $reg_itens->Valor_Frete; } $total_item+= $reg_itens->Valor_Frete; $total_item+= $reg_itens->Valor_Outros; //if ($reg_itens->ICMS_BC_Adic_IPI=='S') { $total_item+= $reg_itens->IPI_Valor; } $total_item+= $reg_itens->IPI_Valor; } //$total_nf+= $total_item; //obs_imp //echo 'entrou calcular'; // $val_impo = arredonda_numero_menos( ( ($total_item) * ($reg_itens->Perc_Tributos/100) ) *100)/100; $val_impoF = ($total_item) * ($reg_itens->Perc_TributosF/100); $val_impoE = ($total_item) * ($reg_itens->Perc_TributosE/100); $val_impoM = ($total_item) * ($reg_itens->Perc_TributosM/100); $val_impoF = arredonda_numero_menos($val_impoF*100)/100; $val_impoE = arredonda_numero_menos($val_impoE*100)/100; $val_impoM = arredonda_numero_menos($val_impoM*100)/100; $val_impo = $val_impoF+$val_impoE+$val_impoM; if ($indFinal=='1'){ if ($val_impo>0){ if ($reg_nota->TipoES=='1'){ $imposto->addAttribute('vTotTrib', nfe_numero($val_impo,2), false); $val_impo_total+= $val_impo; } } } } } if ($reg_itens->Prod_Depart == 0){//é serviço //if ($reg_nota->NFe_Versao != '2.00'){ if (($reg_nota->NFe_Versao != '2.00')&&($reg_nota->NFe_Versao != '3.10')&&($reg_nota->NFe_Versao != '4.00')){ $icms = &$imposto->addChild("ICMS"); $icms_cst = &$icms->addChild("ICMS40");//servico não tem icms (isento) $icms_cst->addAttribute('orig', '0', false); $icms_cst->addAttribute('CST', '40', false); } } if ($reg_itens->Prod_Depart != 0){//é produto $icms = &$imposto->addChild("ICMS"); $cst = $reg_itens->ICMS_CST; if ($cst >= 100){ //caso do simples nacional if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if (($cst=='103')|| ($cst=='300')|| ($cst=='400')){ $cst = '102'; }else if ($cst=='203'){ $cst = '202'; } }else{ if (($cst=='201')|| ($cst=='202')|| ($cst=='203')){ $cst = '30'; }else if ($cst=='500'){ $cst = '60'; }else{ $cst = '40'; } } }else{ if (($cst=='50')|| ($cst=='41')){ $cst = '40'; } } if (($reg_nota->NFe_Versao != '3.10')&&($reg_nota->NFe_Versao != '4.00')){ if ($cst=='51'){ if ($reg_itens->ICMS_Valor >0){ $cst = '90'; } } } if ($cst >= 100){ //somente no layout 2.00 $icms_cst = &$icms->addChild("ICMSSN".$cst); }else{ if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ((($cst=='41')||($cst=='60'))&&($reg_itens->ICMS_Partilha_UF != '')){ $icms_cst = &$icms->addChild("ICMSST"); }else if ((($cst=='10')||($cst=='90'))&&($reg_itens->ICMS_Partilha_UF != '')){ $icms_cst = &$icms->addChild("ICMSPart"); }else{ $icms_cst = &$icms->addChild("ICMS".$cst); } }else{ $icms_cst = &$icms->addChild("ICMS".$cst); } } //origem $icms_cst->addAttribute('orig', $reg_itens->Origem, false); //criar campos conforme o tipo de CST if (($cst=='40')&& ($reg_itens->ICMS_CST > 100)){ $cst = '41'; //caso o cst seja 40 ele pode ter sido outro valor por causa do simples nacional }else{ if ($reg_itens->ICMS_CST > 100){ if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $cst = $reg_itens->ICMS_CST; }else{ $cst = '41'; if (($reg_itens->ICMS_CST=='201')|| ($reg_itens->ICMS_CST=='202')|| ($reg_itens->ICMS_CST=='203')){ $cst = '30'; }else if ($reg_itens->ICMS_CST=='500'){ $cst = '60'; }else{ $cst = '40'; } } }else{ $cst = $reg_itens->ICMS_CST; if ($cst=='51'){ if (($reg_nota->NFe_Versao != '3.10')&&($reg_nota->NFe_Versao != '4.00')){ if ($reg_itens->ICMS_Valor >0){ $cst = '90'; } } } } } if ($cst == '900'){ //cst $icms_cst->addAttribute('CSOSN', '900', false); }else if ($cst > 100){ //cst $icms_cst->addAttribute('CSOSN', $cst, false); }else{ //cst $icms_cst->addAttribute('CST', $cst, false); } if ($cst == '00'){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } } if ($cst == '10'){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $base_fcp = $reg_itens->ICMS_BC; $icms_cst->addAttribute('vBCFCP', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } //modalidade st $icms_cst->addAttribute('modBCST', $reg_itens->ICMSST_Modal, false); if ($reg_itens->ICMSST_MVA > 0){ //mva $icms_cst->addAttribute('pMVAST', nfe_numero($reg_itens->ICMSST_MVA), false); } if ($reg_itens->ICMSST_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBCST', nfe_numero($reg_itens->ICMSST_Reducao), false); } //base $icms_cst->addAttribute('vBCST', nfe_numero($reg_itens->ICMSST_BC), false); //aliquota $icms_cst->addAttribute('pICMSST', nfe_numero($reg_itens->ICMSST_Percentual), false); //valor $icms_cst->addAttribute('vICMSST', nfe_numero($reg_itens->ICMSST_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } } if ($cst == '20'){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); if ($reg_itens->ICMS_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBC', nfe_numero($reg_itens->ICMS_Reducao), false); } //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $base_fcp = $reg_itens->ICMS_BC; $icms_cst->addAttribute('vBCFCP', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMSDeson', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } } } if ($cst == '30'){ //modalidade st $icms_cst->addAttribute('modBCST', $reg_itens->ICMSST_Modal, false); if ($reg_itens->ICMSST_MVA > 0){ //mva $icms_cst->addAttribute('pMVAST', nfe_numero($reg_itens->ICMSST_MVA), false); } if ($reg_itens->ICMSST_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBCST', nfe_numero($reg_itens->ICMSST_Reducao), false); } //base $icms_cst->addAttribute('vBCST', nfe_numero($reg_itens->ICMSST_BC), false); //aliquota $icms_cst->addAttribute('pICMSST', nfe_numero($reg_itens->ICMSST_Percentual), false); //valor $icms_cst->addAttribute('vICMSST', nfe_numero($reg_itens->ICMSST_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMSDeson', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } } } if ($cst == '40'){ if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMSDeson', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } }else if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } } if ($cst == '51'){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); if ($reg_itens->ICMS_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBC', nfe_numero($reg_itens->ICMS_Reducao), false); } //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Diferido_Perc>=100){ $total_diferido+= $reg_itens->ICMS_BC; } //valor operacao $icms_cst->addAttribute('vICMSOp', nfe_numero($reg_itens->ICMS_Valor_Op), false); //percentual diferido $icms_cst->addAttribute('pDif', nfe_numero($reg_itens->ICMS_Diferido_Perc,4), false); //valor devido $icms_cst->addAttribute('vICMSDif', nfe_numero($reg_itens->ICMS_Diferido_Valor), false); //valor devido $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); }else{ //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor_Op), false); } if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $base_fcp = $reg_itens->ICMS_BC; $icms_cst->addAttribute('vBCFCP', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } } if ($cst == '60'){ if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ((($cst=='41')||($cst=='60'))&&($reg_itens->ICMS_Partilha_UF != '')){ }else{ //base $icms_cst->addAttribute('vBCSTRet', nfe_numero($reg_itens->ICMSST_Retido_BC), false); if ($reg_nota->NFe_Versao == '4.00'){ $perc_st = $reg_itens->ICMSST_Retido_Percentual+$reg_itens->ICMSST_FCP_Percentual; //if ($perc_st>0){ $icms_cst->addAttribute('pST', nfe_numero($perc_st), false); //} } //valor $icms_cst->addAttribute('vICMSSTRet', nfe_numero($reg_itens->ICMSST_Retido_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_Retido_BC; $icms_cst->addAttribute('vBCFCPSTRet', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPSTRet', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPSTRet', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } } }else{ //base $icms_cst->addAttribute('vBCST', nfe_numero(0), false); //valor $icms_cst->addAttribute('vICMSST', nfe_numero(0), false); } } if ($cst == '70'){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); //reducao $icms_cst->addAttribute('pRedBC', nfe_numero($reg_itens->ICMS_Reducao), false); //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $base_fcp = $reg_itens->ICMS_BC; $icms_cst->addAttribute('vBCFCP', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } //modalidade st $icms_cst->addAttribute('modBCST', $reg_itens->ICMSST_Modal, false); if ($reg_itens->ICMSST_MVA > 0){ //mva $icms_cst->addAttribute('pMVAST', nfe_numero($reg_itens->ICMSST_MVA), false); } if ($reg_itens->ICMSST_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBCST', nfe_numero($reg_itens->ICMSST_Reducao), false); } //base $icms_cst->addAttribute('vBCST', nfe_numero($reg_itens->ICMSST_BC), false); //aliquota $icms_cst->addAttribute('pICMSST', nfe_numero($reg_itens->ICMSST_Percentual), false); //valor $icms_cst->addAttribute('vICMSST', nfe_numero($reg_itens->ICMSST_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMSDeson', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } } } if (($cst == '90')||($cst=='900')){ //modalidade $icms_cst->addAttribute('modBC', $reg_itens->ICMS_Modal, false); //base $icms_cst->addAttribute('vBC', nfe_numero($reg_itens->ICMS_BC), false); if ($reg_itens->ICMS_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBC', nfe_numero($reg_itens->ICMS_Reducao), false); } //aliquota $icms_cst->addAttribute('pICMS', nfe_numero($reg_itens->ICMS_Percentual), false); //valor $icms_cst->addAttribute('vICMS', nfe_numero($reg_itens->ICMS_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMS_FCP_Valor>0){ $base_fcp = $reg_itens->ICMS_BC; $icms_cst->addAttribute('vBCFCP', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCP', nfe_numero($reg_itens->ICMS_FCP_Percentual), false); $icms_cst->addAttribute('vFCP', nfe_numero($reg_itens->ICMS_FCP_Valor), false); } } //modalidade st $icms_cst->addAttribute('modBCST', $reg_itens->ICMSST_Modal, false); if ($reg_itens->ICMSST_MVA > 0){ //mva $icms_cst->addAttribute('pMVAST', nfe_numero($reg_itens->ICMSST_MVA), false); } if ($reg_itens->ICMSST_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBCST', nfe_numero($reg_itens->ICMSST_Reducao), false); } //base //if ($reg_itens->ICMSST_BC>0){ $icms_cst->addAttribute('vBCST', nfe_numero($reg_itens->ICMSST_BC), false); //} //aliquota //if ($reg_itens->ICMSST_Percentual>0){ $icms_cst->addAttribute('pICMSST', nfe_numero($reg_itens->ICMSST_Percentual), false); //} //valor //if ($reg_itens->ICMSST_Valor>0){ $icms_cst->addAttribute('vICMSST', nfe_numero($reg_itens->ICMSST_Valor), false); //} if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Desonerado_Valor > 0){ //valor ICMS desonerado $icms_cst->addAttribute('vICMSDeson', nfe_numero($reg_itens->ICMS_Desonerado_Valor), false); //motivo ICMS desonerado $icms_cst->addAttribute('motDesICMS', $reg_itens->ICMS_Desonerado_Motivo, false); } } } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if ($reg_itens->ICMS_Partilha_UF != ''){ if (($cst=='10')|| ($cst=='90')){ //perc bc $icms_cst->addAttribute('pBCOp', nfe_numero($reg_itens->ICMS_Partilha_BC_Perc), false); $uf = $reg_itens->ICMS_Partilha_UF; if ($uf=='O'){ $uf = $reg_nota->Empresa_UF; }else if ($uf=='D'){ $uf = $reg_nota->Dest_UF; } //valor $icms_cst->addAttribute('UFST', $uf, false); } } if ((($cst=='41')||($cst=='60'))&&($reg_itens->ICMS_Partilha_UF != '')){ //base retida $icms_cst->addAttribute('vBCSTRet', nfe_numero($reg_itens->ICMSST_Retido_BC), false); //valore retido $icms_cst->addAttribute('vICMSSTRet', nfe_numero($reg_itens->ICMSST_Retido_Valor), false); //base destino $icms_cst->addAttribute('vBCSTDest', nfe_numero($reg_itens->ICMSST_Destino_BC), false); //valore destino $icms_cst->addAttribute('vICMSSTDest', nfe_numero($reg_itens->ICMSST_Destino_Valor), false); } if (($cst=='201')||($cst=='202')||($cst=='203')){ //modalidade st $icms_cst->addAttribute('modBCST', $reg_itens->ICMSST_Modal, false); if ($reg_itens->ICMSST_MVA > 0){ //mva $icms_cst->addAttribute('pMVAST', nfe_numero($reg_itens->ICMSST_MVA), false); } if ($reg_itens->ICMSST_Reducao > 0){ //reducao $icms_cst->addAttribute('pRedBCST', nfe_numero($reg_itens->ICMSST_Reducao), false); } //base $icms_cst->addAttribute('vBCST', nfe_numero($reg_itens->ICMSST_BC), false); //aliquota $icms_cst->addAttribute('pICMSST', nfe_numero($reg_itens->ICMSST_Percentual), false); //valor $icms_cst->addAttribute('vICMSST', nfe_numero($reg_itens->ICMSST_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } } if (($cst=='500')||($cst=='901')){ //base $icms_cst->addAttribute('vBCSTRet', nfe_numero($reg_itens->ICMSST_Retido_BC), false); if ($reg_nota->NFe_Versao == '4.00'){ $perc_st = $reg_itens->ICMSST_Retido_Percentual+$reg_itens->ICMSST_FCP_Percentual; //if ($perc_st>0){ $icms_cst->addAttribute('pST', nfe_numero($perc_st), false); // } //valor $icms_cst->addAttribute('vICMSSTRet', nfe_numero($reg_itens->ICMSST_Retido_Valor), false); if ($cst=='500'){ if ($reg_nota->NFe_Versao == '4.00'){ if ($reg_itens->ICMSST_FCP_Valor>0){ $base_fcp = $reg_itens->ICMSST_Retido_BC; $icms_cst->addAttribute('vBCFCPST', nfe_numero($base_fcp), false); $icms_cst->addAttribute('pFCPST', nfe_numero($reg_itens->ICMSST_FCP_Percentual), false); $icms_cst->addAttribute('vFCPST', nfe_numero($reg_itens->ICMSST_FCP_Valor), false); } } } } if (($cst=='101')||($cst=='201')||($cst=='900')){ //aliquota $icms_cst->addAttribute('pCredSN', nfe_numero($reg_itens->ICMSSN_Perc), false); //valor $icms_cst->addAttribute('vCredICMSSN', nfe_numero($reg_itens->ICMSSN_Valor), false); } } //ipi if (($finalidade=='4')&&($regime==1)){ //nao coloca aqui mas no imposto devolvido }else if ($reg_itens->IPI_CST != ''){ $ipi = &$imposto->addChild("IPI"); //classe if ($reg_itens->IPI_Classe!= ''){ $ipi->addAttribute('clEnq', $reg_itens->IPI_Classe, false); } //fabricante if (strlen(limpa_numero($reg_itens->IPI_Fabricante_CNPJ))== 14){ if ($reg_itens->IPI_Fabricante_CNPJ!='00000000000000'){ $ipi->addAttribute('CNPJProd', limpa_numero($reg_itens->IPI_Fabricante_CNPJ), false); } } //selo if ($reg_itens->IPI_Selo_Nr != ''){ $ipi->addAttribute('cSelo', $reg_itens->IPI_Selo_Nr, false); } //qtd if ($reg_itens->IPI_Selo_Qtd>0){ $ipi->addAttribute('qSelo', nfe_numero($reg_itens->IPI_Selo_Qtd,0), false); } //enquadramento legal $enq = $reg_itens->IPI_Codigo_Equad_Legal; if ($enq==''){ $enq='999'; } /*if (($reg_itens->IPI_CST == '00')|| ($reg_itens->IPI_CST == '49')){ if ($enq<600){ $enq = '999'; //so coloca o codigo do enquadramento quando o ipi for zero (Senão é sempre outros) } } */ /* if ($reg_nota->NFe_Ambiente=='2'){ if (data_atual('num')addAttribute('cEnq', fill_full($enq,3), false); $cst_ipi = $reg_itens->IPI_CST; if ($reg_nota->TipoES=='1'){ $cst_ipi+=50; } if (($reg_itens->IPI_CST == '00')|| ($reg_itens->IPI_CST == '49')){ $ipi_cst = &$ipi->addChild("IPITrib"); //cst $ipi_cst->addAttribute('CST', $cst_ipi, false); if ($reg_itens->IPI_ValorUnidade >0){ //quantidade trib $ipi_cst->addAttribute('qUnid', nfe_numero($reg_itens->Quantidade_Estoque,4), false);//4 digitos //valor por unidade $ipi_cst->addAttribute('vUnid', nfe_numero($reg_itens->IPI_ValorUnidade,4), false); }else{ //base de cáculo $ipi_cst->addAttribute('vBC', nfe_numero($reg_itens->IPI_BC), false); //aliquota $ipi_cst->addAttribute('pIPI', nfe_numero($reg_itens->IPI_Aliquota), false); } //valor $ipi_cst->addAttribute('vIPI', nfe_numero($reg_itens->IPI_Valor), false); }else{ $ipi_cst = &$ipi->addChild("IPINT"); //cst $ipi_cst->addAttribute('CST', $cst_ipi, false); } } } //ii if (($reg_itens->II_Valor>0) ||($reg_itens->Importa_Nr_DI >0)){ $iimp = &$imposto->addChild("II"); $iimp->addAttribute('vBC', nfe_numero($reg_itens->II_BC), false); $iimp->addAttribute('vDespAdu', nfe_numero($reg_itens->II_Desp_Aduanerias), false); $iimp->addAttribute('vII', nfe_numero($reg_itens->II_Valor), false); $iimp->addAttribute('vIOF', nfe_numero($reg_itens->II_IOF_Valor), false); } //pis $pis = &$imposto->addChild("PIS"); //por aliquota if (($reg_itens->PIS_CST=='01')|| ($reg_itens->PIS_CST=='02')){ $pis_cst = &$pis->addChild("PISAliq"); //cst $pis_cst->addAttribute('CST', $reg_itens->PIS_CST, false); //base $pis_cst->addAttribute('vBC', nfe_numero($reg_itens->PIS_BC), false); //aliq $pis_cst->addAttribute('pPIS', nfe_numero($reg_itens->PIS_Aliquota), false); //valor $pis_cst->addAttribute('vPIS', nfe_numero($reg_itens->PIS_Valor), false); }else if ($reg_itens->PIS_CST=='03'){ $pis_cst = &$pis->addChild("PISQtde"); //cst $pis_cst->addAttribute('CST', $reg_itens->PIS_CST, false); //qtd trib $pis_cst->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $pis_cst->addAttribute('vAliqProd', nfe_numero($reg_itens->PIS_ValorUnidade,4), false); //4 casas //valor $pis_cst->addAttribute('vPIS', nfe_numero($reg_itens->PIS_Valor), false); }else if ($reg_itens->PIS_CST>=49){ //outros $pis_cst = &$pis->addChild("PISOutr"); //cst $pis_cst->addAttribute('CST', $reg_itens->PIS_CST, false); if ($reg_itens->PIS_ValorUnidade >0){ //qtd trib $pis_cst->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $pis_cst->addAttribute('vAliqProd', nfe_numero($reg_itens->PIS_ValorUnidade,4), false); //4 casas }else{ //base $pis_cst->addAttribute('vBC', nfe_numero($reg_itens->PIS_BC), false); //aliq $pis_cst->addAttribute('pPIS', nfe_numero($reg_itens->PIS_Aliquota), false); }//valor $pis_cst->addAttribute('vPIS', nfe_numero($reg_itens->PIS_Valor), false); }else{ //não tributado $pis_cst = &$pis->addChild("PISNT"); //cst $pis_cst->addAttribute('CST', $reg_itens->PIS_CST, false); } //pis st if (($reg_itens->PIS_ST_ValorUnidade >0)|| ($reg_itens->PIS_ST_Aliquota>0)){ $pis_st = &$imposto->addChild("PISST"); if ($reg_itens->PIS_ST_ValorUnidade >0){ //qtd trib $pis_st->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $pis_st->addAttribute('vAliqProd', nfe_numero($reg_itens->PIS_ST_ValorUnidade,4), false); //4 casas }else{ //base $pis_st->addAttribute('vBC', nfe_numero($reg_itens->PIS_ST_BC), false); //aliq $pis_st->addAttribute('pPIS', nfe_numero($reg_itens->PIS_ST_Aliquota), false); }//valor $pis_st->addAttribute('vPIS', nfe_numero($reg_itens->PIS_ST_Valor), false); } //cofins $cofins = &$imposto->addChild("COFINS"); //por aliquota if (($reg_itens->COFINS_CST=='01')|| ($reg_itens->COFINS_CST=='02')){ $cofins_cst = &$cofins->addChild("COFINSAliq"); //cst $cofins_cst->addAttribute('CST', $reg_itens->COFINS_CST, false); //base $cofins_cst->addAttribute('vBC', nfe_numero($reg_itens->COFINS_BC), false); //aliq $cofins_cst->addAttribute('pCOFINS', nfe_numero($reg_itens->COFINS_Aliquota), false); //valor $cofins_cst->addAttribute('vCOFINS', nfe_numero($reg_itens->COFINS_Valor), false); }else if ($reg_itens->COFINS_CST=='03'){ $cofins_cst = &$cofins->addChild("COFINSQtde"); //cst $cofins_cst->addAttribute('CST', $reg_itens->COFINS_CST, false); //qtd trib $cofins_cst->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $cofins_cst->addAttribute('vAliqProd', nfe_numero($reg_itens->COFINS_ValorUnidade,4), false); //4 casas //valor $cofins_cst->addAttribute('vCOFINS', nfe_numero($reg_itens->COFINS_Valor), false); }else if ($reg_itens->COFINS_CST>=49){ //outros $cofins_cst = &$cofins->addChild("COFINSOutr"); //cst $cofins_cst->addAttribute('CST', $reg_itens->COFINS_CST, false); if ($reg_itens->COFINS_ValorUnidade >0){ //qtd trib $cofins_cst->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $cofins_cst->addAttribute('vAliqProd', nfe_numero($reg_itens->COFINS_ValorUnidade,4), false); //4 casas }else{ //base $cofins_cst->addAttribute('vBC', nfe_numero($reg_itens->COFINS_BC), false); //aliq $cofins_cst->addAttribute('pCOFINS', nfe_numero($reg_itens->COFINS_Aliquota), false); }//valor $cofins_cst->addAttribute('vCOFINS', nfe_numero($reg_itens->COFINS_Valor), false); }else{ //não tributado $cofins_cst = &$cofins->addChild("COFINSNT"); //cst $cofins_cst->addAttribute('CST', $reg_itens->COFINS_CST, false); } //cofins st if (($reg_itens->COFINS_ST_ValorUnidade >0)|| ($reg_itens->COFINS_ST_Aliquota>0)){ $cofins_st = &$imposto->addChild("COFINSST"); if ($reg_itens->COFINS_ST_ValorUnidade >0){ //qtd trib $cofins_st->addAttribute('qBCProd', nfe_numero($reg_itens->Quantidade_Estoque,4), false); //4 casas //valor por unidade $cofins_st->addAttribute('vAliqProd', nfe_numero($reg_itens->COFINS_ST_ValorUnidade,4), false); //4 casas }else{ //base $cofins_st->addAttribute('vBC', nfe_numero($reg_itens->COFINS_ST_BC), false); //aliq $cofins_st->addAttribute('pCOFINS', nfe_numero($reg_itens->COFINS_ST_Aliquota), false); }//valor $cofins_st->addAttribute('vCOFINS', nfe_numero($reg_itens->COFINS_ST_Valor), false); } //iss if ($reg_itens->Prod_Depart == 0){//somente servico tem iss $iss = &$imposto->addChild("ISSQN"); //base $iss->addAttribute('vBC', nfe_numero($reg_itens->ISS_BC), false); //aliquota $iss->addAttribute('vAliq', nfe_numero($reg_itens->ISS_Aliquota), false); //valor $iss->addAttribute('vISSQN', nfe_numero($reg_itens->ISS_Valor), false); //municiopo fato gerador $iss->addAttribute('cMunFG', $reg_itens->ISS_Cidade_FG, false); //servico $iss->addAttribute('cListServ', limpa_numero($reg_itens->Servico_Codigo), false); //cst iss if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $iss->addAttribute('cSitTrib', $reg_itens->ISS_CST, false); } } if (($reg_nota->NFe_Ambiente=='2')|| (data2nr(dataf($reg_nota->DH_Emissao))>= data2nr('01/01/2016')) ){ if ($reg_itens->Prod_Depart == 0){ //serviço nao tem partilha }else if (($dados_partilha)&&($dados_partilha2=='S')&&($reg_itens->ICMS_Dest_Aliquota_Inter>0)){ $icms_dest = &$imposto->addChild("ICMSUFDest"); $icms_dest->addAttribute('vBCUFDest', nfe_numero($reg_itens->ICMS_Dest_BC), false); $icms_dest->addAttribute('vBCFCPUFDest', nfe_numero($reg_itens->ICMS_Dest_BC), false); $icms_dest->addAttribute('pFCPUFDest', nfe_numero($reg_itens->ICMS_Dest_FCP), false); $icms_dest->addAttribute('pICMSUFDest', nfe_numero($reg_itens->ICMS_Dest_Aliquota), false); $icms_dest->addAttribute('pICMSInter', nfe_numero($reg_itens->ICMS_Dest_Aliquota_Inter), false); $icms_dest->addAttribute('pICMSInterPart', nfe_numero($reg_itens->ICMS_Dest_Part), false); $icms_dest->addAttribute('vFCPUFDest', nfe_numero($reg_itens->ICMS_Dest_Valor_FCP), false); $icms_dest->addAttribute('vICMSUFDest', nfe_numero($reg_itens->ICMS_Dest_Valor), false); $icms_dest->addAttribute('vICMSUFRemet', nfe_numero($reg_itens->ICMS_Dest_Valor_Remete), false); } } //devolução de IPI if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ if (($finalidade=='4')&&($regime==1)){ If ($reg_itens->IPI_Valor>0){ $total_qtd = nota_fiscal_busca_ipi_origem($_SESSION["Empresa_Codigo"],$nr_nota,$reg_itens->Id_Produto); if ($total_qtd<=0){ $prec_ipi_dev = 100; }else{ $prec_ipi_dev = arredonda_numero_menos( ($reg_itens->Quantidade_Estoque / $total_qtd) *10000) /100; } if ($prec_ipi_dev>100){ $prec_ipi_dev = 100; } $impostoDevol = &$det->addChild("impostoDevol"); $impostoDevol->addAttribute('pDevol', nfe_numero($prec_ipi_dev), false); $impostoDevolIPI = &$impostoDevol->addChild("IPI"); $impostoDevolIPI->addAttribute('vIPIDevol', nfe_numero($reg_itens->IPI_Valor), false); } } } $obs = nfe_formata_txt($reg_itens->Observacao); //consulta obs do item $con_obs = 'select * from nota_fiscal_obs'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Seq_Item="'.$reg_itens->Seq_Item.'"'. ' and TipoObs="P" '. ' group by Texto_Completo '. ' order by Seq_Obs '; $res_obs = consulta_sql($con_obs); $nrw_obs = consulta_num_registros($res_obs); //para cada obs for($o=0;$o<$nrw_obs;$o++){ $reg_obs = consulta_ler_objeto($res_obs); //adiciona a desc detalhada deste item if ($obs!=''){ $obs.=';'; } $obs.= nfe_formata_txt($reg_obs->Texto_Completo); } consulta_limpa($res_obs); //se tiver desc detalhada if ($obs!=''){ //adiciona as informações adiconadis do item $det->addAttribute('infAdProd', trim(nfe_retira_texto_excesso($obs,0,500)), false); } } consulta_limpa($res_itens); //adiciona os totais da NF $totais = &$nf_inf->addChild("total"); //totias do ICMS $icms_tot = &$totais->addChild("ICMSTot"); //base if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ $icms_tot->addAttribute('vBC', nfe_numero($reg_nota->Total_ICMS_BC+$total_diferido), false); }else{ $icms_tot->addAttribute('vBC', nfe_numero($reg_nota->Total_ICMS_BC), false); } //valor $icms_tot->addAttribute('vICMS', nfe_numero($reg_nota->Total_ICMS_Valor), false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //desconto $icms_tot->addAttribute('vICMSDeson', nfe_numero($reg_nota->Total_Desonerado), false); if (($reg_nota->NFe_Ambiente=='2')|| (data2nr(dataf($reg_nota->DH_Emissao))>= data2nr('01/01/2016')) ){ if ($reg_nota->Total_ICMS_Dest_FCP>0){ $icms_tot->addAttribute('vFCPUFDest', nfe_numero($reg_nota->Total_ICMS_Dest_FCP), false); } if ($reg_nota->Total_ICMS_Dest>0){ $icms_tot->addAttribute('vICMSUFDest', nfe_numero($reg_nota->Total_ICMS_Dest), false); } if ($reg_nota->Total_ICMS_Dest_Remete>0){ $icms_tot->addAttribute('vICMSUFRemet', nfe_numero($reg_nota->Total_ICMS_Dest_Remete), false); } } } if ($reg_nota->NFe_Versao == '4.00'){ $icms_tot->addAttribute('vFCP', nfe_numero($reg_nota->Total_ICMS_FCP), false); } //base st $icms_tot->addAttribute('vBCST', nfe_numero($reg_nota->Total_ICMS_ST_BC), false); //valor st $icms_tot->addAttribute('vST', nfe_numero($reg_nota->Total_ICMS_ST_Valor), false); if ($reg_nota->NFe_Versao == '4.00'){ $icms_tot->addAttribute('vFCPST', nfe_numero($reg_nota->Total_ICMSST_FCP), false); $icms_tot->addAttribute('vFCPSTRet', nfe_numero($reg_nota->Total_ICMSSTRet_FCP), false); } //total pro/serv $icms_tot->addAttribute('vProd', nfe_numero( $total_produtos + $reg_nota->Total_Servicos), false); //frete $icms_tot->addAttribute('vFrete', nfe_numero($reg_nota->Total_Frete), false); //seguro $icms_tot->addAttribute('vSeg', nfe_numero($reg_nota->Total_Seguro), false); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //desconto $icms_tot->addAttribute('vDesc', nfe_numero($reg_nota->Total_Desconto), false); }else{ //desconto $icms_tot->addAttribute('vDesc', nfe_numero($reg_nota->Total_Desconto+$reg_nota->Total_Desonerado), false); } //ii $icms_tot->addAttribute('vII', nfe_numero($reg_nota->Total_II), false); //ipi $vIPI = $reg_nota->Total_IPI; $vIPIDevol = 0; if ($reg_nota->NFe_Versao == '4.00'){ if (($finalidade == '4')&&($regime=='1')){//devolucao $vIPIDevol = $reg_nota->Total_IPI; $vIPI = 0; } } $icms_tot->addAttribute('vIPI', nfe_numero($vIPI), false); if ($reg_nota->NFe_Versao == '4.00'){ $icms_tot->addAttribute('vIPIDevol', nfe_numero($vIPIDevol), false); } //pis $icms_tot->addAttribute('vPIS', nfe_numero($reg_nota->Total_PIS), false); //cofins $icms_tot->addAttribute('vCOFINS', nfe_numero($reg_nota->Total_COFINS), false); //outro $icms_tot->addAttribute('vOutro', nfe_numero($reg_nota->Total_Outros), false); //total NF $icms_tot->addAttribute('vNF', nfe_numero($reg_nota->Total_NF), false); if ($indFinal=='1'){ if ($val_impo_total>0){ $icms_tot->addAttribute('vTotTrib', nfe_numero($val_impo_total), false); } } //totais do ISS (somente se tiver serviços) if ($reg_nota->Total_Servicos > 0){ $iss_tot = &$totais->addChild("ISSQNtot"); //total dos servicos $iss_tot->addAttribute('vServ', nfe_numero($reg_nota->Total_Servicos), false); //base $iss_tot->addAttribute('vBC', nfe_numero($reg_nota->Total_ISS_BC), false); //valor $iss_tot->addAttribute('vISS', nfe_numero($reg_nota->Total_ISS_Valor), false); //pis $iss_tot->addAttribute('vPIS', nfe_numero($reg_nota->Total_ISS_PIS_Valor), false); //cofins $iss_tot->addAttribute('vCOFINS', nfe_numero($reg_nota->Total_ISS_COFINS_Valor), false); } //totais retidos if (($reg_nota->Total_Retido_PIS > 0)|| ($reg_nota->Total_Retido_COFINS > 0)|| ($reg_nota->Total_Retido_CSLL_Valor > 0)|| ($reg_nota->Total_Retido_IRRF_Valor > 0)|| ($reg_nota->Total_Retido_PrevSocial_Valor > 0)){ $ret_tot = &$totais->addChild("retTrib"); } if ($reg_nota->Total_Retido_PIS > 0){ //pis $ret_tot->addAttribute('vRetPIS', nfe_numero($reg_nota->Total_Retido_PIS), false); } if ($reg_nota->Total_Retido_COFINS > 0){ //cofins $ret_tot->addAttribute('vRetCOFINS', nfe_numero($reg_nota->Total_Retido_COFINS), false); } if ($reg_nota->Total_Retido_CSLL_Valor > 0){ //csll $ret_tot->addAttribute('vRetCSLL', nfe_numero($reg_nota->Total_Retido_CSLL_Valor), false); } if ($reg_nota->Total_Retido_IRRF_Valor > 0){ //irrf base $ret_tot->addAttribute('vBCIRRF', nfe_numero($reg_nota->Total_Retido_IRRF_BC), false); //irrf valor $ret_tot->addAttribute('vIRRF', nfe_numero($reg_nota->Total_Retido_IRRF_Valor), false); } if ($reg_nota->Total_Retido_PrevSocial_Valor > 0){ //base prev $ret_tot->addAttribute('vBCRetPrev', nfe_numero($reg_nota->Total_Retido_PrevSocial_BC), false); //valor prev $ret_tot->addAttribute('vRetPrev', nfe_numero($reg_nota->Total_Retido_PrevSocial_Valor), false); } //dados do frete $transp = &$nf_inf->addChild("transp"); //modalidade de frete $tp_frete = $reg_nota->FretePor; if ($tp_frete == '0'){ //terceiros $tp_frete ='2'; }else if ($tp_frete == '1'){ //emitente $tp_frete = '0'; }else if ($tp_frete == '2'){ //dest $tp_frete = '1'; } //9 é sem frete if ($reg_nota->Modelo == '65'){ $tp_frete = '9'; } $transp->addAttribute('modFrete', $tp_frete, false); //se tiver transportadora if ($reg_nota->Transportadora > 0){ //adiciona dados da transportadora $transporta = &$transp->addChild("transporta"); //cfp/ccnpj if (strlen(limpa_numero($reg_nota->Transp_CPF_CNPJ)) == 11){ if (limpa_numero($reg_nota->Transp_CPF_CNPJ) != '00000000000'){ $transporta->addAttribute('CPF', limpa_numero($reg_nota->Transp_CPF_CNPJ), false); } } if (strlen(limpa_numero($reg_nota->Transp_CPF_CNPJ)) == 14){ if (limpa_numero($reg_nota->Transp_CPF_CNPJ) != '00000000000000'){ $transporta->addAttribute('CNPJ', limpa_numero($reg_nota->Transp_CPF_CNPJ), false); } } if (trim(substr($reg_nota->Transp_Nome,0,60))!= ''){ $transporta->addAttribute('xNome', trim(nfe_retira_texto_excesso($reg_nota->Transp_Nome,0,60)), false); } if ( (strlen(limpa_numero($reg_nota->Transp_CPF_CNPJ)) == 14)&& ($reg_nota->Transp_UF != '')&& (limpa_numero($reg_nota->Transp_CPF_CNPJ) != '00000000000000')){ if ((($reg_nota->NFe_Versao == '2.00')|| ($reg_nota->NFe_Versao == '3.10')|| ($reg_nota->NFe_Versao == '4.00'))&& (trim(substr(limpa_numero2($reg_nota->Transp_IE),0,14)) != '')){ $transporta->addAttribute('IE', trim(substr(limpa_numero2($reg_nota->Transp_IE),0,14)), false); } } if (trim($reg_nota->Transp_Endereco)!=''){ $ender = trim($reg_nota->Transp_Logradouro); if (trim($reg_nota->Transp_Numero) != ''){ $ender.= ', '.trim($reg_nota->Transp_Numero); }else{ $ender.= ', S/N'; } if (trim($reg_nota->Transp_Complemento) != ''){ $ender.= ' '.trim($reg_nota->Transp_Complemento); } $transporta->addAttribute('xEnder', trim(nfe_retira_texto_excesso($ender,0,60)), false); } if (trim($reg_nota->Transp_Cidade_Nome)!=''){ $transporta->addAttribute('xMun', trim(nfe_retira_texto_excesso($reg_nota->Transp_Cidade_Nome,0,60)), false); } if (trim($reg_nota->Transp_UF)!=''){ $transporta->addAttribute('UF', $reg_nota->Transp_UF, false); } } //se tiver retenção do frete if ($reg_nota->Frete_Valor_Serv >0){ //adiciona dados dessa retenção $ret_transp = &$transp->addChild("retTransp"); //valor servico $ret_transp->addAttribute('vServ', nfe_numero($reg_nota->Frete_Valor_Serv), false); //base $ret_transp->addAttribute('vBCRet', nfe_numero($reg_nota->Frete_Retido_ICMS_BC), false); //aliq $ret_transp->addAttribute('pICMSRet', nfe_numero($reg_nota->Frete_Retido_ICMS_Aliquota), false); //valor $ret_transp->addAttribute('vICMSRet', nfe_numero($reg_nota->Frete_Retido_ICMS_Valor), false); //cfop $ret_transp->addAttribute('CFOP', $reg_nota->Frete_CFOP, false); //cidade $ret_transp->addAttribute('cMunFG', $reg_nota->Frete_Codigo_Cidade, false); } //se tiver veículo if (($reg_nota->NFe_Versao == '4.00') && ($idDest==2)){ //interestadual nao pode apresentar placa e reboque }else if ($reg_nota->Veiculo_Tipo == 'C'){ //caminhão if (strlen(limpa_numero2($reg_nota->Veiculo_Placa))==7){ //adiciona dados desse veículo $veic_transp = &$transp->addChild("veicTransp"); //placa $veic_transp->addAttribute('placa', limpa_numero2($reg_nota->Veiculo_Placa), false); //uf $veic_transp->addAttribute('UF', $reg_nota->Veiculo_Placa_UF, false); //antt if (limpa_numero2($reg_nota->Veiculo_ANTT) != ''){ $veic_transp->addAttribute('RNTC', limpa_numero2($reg_nota->Veiculo_ANTT), false); } } //se tiver reboque if (strlen(limpa_numero2($reg_nota->Veiculo_Reboque_Placa))==7){ //adciona dados do reboque $reboque = &$transp->addChild("reboque"); //placa $reboque->addAttribute('placa', limpa_numero2($reg_nota->Veiculo_Reboque_Placa), false); //uf $reboque->addAttribute('UF', $reg_nota->Veiculo_Reboque_UF, false); //antt if (limpa_numero2($reg_nota->Veiculo_Reboque_ANTT ) != ''){ $reboque->addAttribute('RNTC', limpa_numero2($reg_nota->Veiculo_Reboque_ANTT), false); } } } if (($reg_nota->NFe_Versao == '2.00')||($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //se for vagão/balsa if (($reg_nota->Veiculo_Tipo == 'V')&& (limpa_numero2($reg_nota->Veiculo_Placa)!= '')){ //placa do vagao $transp->addAttribute('vagao', limpa_numero2($reg_nota->Veiculo_Placa), false); } if (($reg_nota->Veiculo_Tipo == 'B')&& (limpa_numero2($reg_nota->Veiculo_Placa)!= '')){ //placa do vagao $transp->addAttribute('balsa', limpa_numero2($reg_nota->Veiculo_Placa), false); } } //se tive informações do volume if (($reg_nota->Volumes_Qtd > 0)|| (trim($reg_nota->Volumes_Nr) != '')|| ($reg_nota->Peso_Liquido > 0)|| ($reg_nota->Peso_Bruto > 0)){ //adicona dados do volume $vol = &$transp->addChild("vol"); $tem_vol = false; //qtd de volumes if ($reg_nota->Volumes_Qtd > 0){ $vol->addAttribute('qVol', nfe_numero($reg_nota->Volumes_Qtd,0), false); $tem_vol = true; }else{ $vol->addAttribute('qVol', '0', false); $tem_vol = true; } if ($tem_vol){ if (trim($reg_nota->Volumes_Especie) != ''){ $vol->addAttribute('esp', trim($reg_nota->Volumes_Especie), false); } if (trim($reg_nota->Volumes_Marca) != ''){ $vol->addAttribute('marca', trim($reg_nota->Volumes_Marca), false); } } if (trim($reg_nota->Volumes_Nr) != ''){ $vol->addAttribute('nVol', trim($reg_nota->Volumes_Nr), false); } if ($reg_nota->Peso_Liquido>0){ $vol->addAttribute('pesoL', nfe_numero($reg_nota->Peso_Liquido,3), false); } if ($reg_nota->Peso_Bruto>0){ $vol->addAttribute('pesoB', nfe_numero($reg_nota->Peso_Bruto,3), false); } } //dados dos lacres (não possui) //consulta faturas da nota fiscal if ($reg_nota->Modelo != '65'){ $con_parc = 'select * from nota_fiscal_parcela'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Parcela>0 '. ' order by Parcela '; $res_parc = consulta_sql($con_parc); $nrw_parc = consulta_num_registros($res_parc); if ($reg_nota->NFe_Versao == '4.00'){ if (($finalidade==4)||($finalidade==3)||($nrw_parc==0)||($reg_nota->Total_NF==0)){ $pag_tPag = '90'; $nrw_parc = 0; }else{ if($nrw_parc==1){ if ($reg_nota->Fatura_Tipo=='M'){ $pag_tPag = '01'; //dinheiro $nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='B'){ $pag_tPag = '14'; //15-boleto //$nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='A'){ $pag_tPag = '05'; //carne/credito loja $nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='C'){ $pag_tPag = '02'; //Cheque $nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='1'){ $pag_tPag = '04'; //cartao de debito $nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='2'){ $pag_tPag = '03'; //cartao de credio $nrw_parc = 0; }else if ($reg_nota->Fatura_Tipo=='3'){ $pag_tPag = '03'; //cartao de credio $nrw_parc = 0; }else if (($reg_nota->Fatura_Tipo=='E')||($reg_nota->Fatura_Tipo=='O')||($reg_nota->Fatura_Tipo=='R')||($reg_nota->Fatura_Tipo=='P')){ $pag_tPag = '99'; //outros $nrw_parc = 0; }else{ $pag_tPag = '14'; //14duplicata } }else{ $pag_tPag = '14'; //duplicata if ($reg_nota->Fatura_Tipo=='B'){ //$pag_tPag = '15'; //boleto //$nrw_parc = 0; } } } } $v_liquido = 0; if ($nrw_parc >0){ $con_sumparc = 'select SUM(Valor_Parcela) from nota_fiscal_parcela'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Parcela>0 '; $res_sumparc = consulta_sql($con_sumparc); $reg_sumparc = consulta_ler_linha($res_sumparc); consulta_limpa($res_sumparc); if($reg_sumparc[0] > 0.001){ $v_liquido = $reg_sumparc[0]; } $diferenca = $reg_nota->Total_NF - $v_liquido; }else{ $v_liquido = $reg_nota->Total_NF; $diferenca = 0; } if ($pag_tPag=='90'){ $v_liquido = 0; $diferenca =0; } //se tiver faturas if ($nrw_parc >0){ //adciona dados da cobraça $cobr = &$nf_inf->addChild("cobr"); //para cada fatura $fat = &$cobr->addChild("fat"); $fat->addAttribute('nFat',$reg_nota->NrDoc.'/'.$reg_nota->Serie , false); $fat->addAttribute('vOrig', nfe_numero($v_liquido,2), false); $fat->addAttribute('vDesc', nfe_numero(0,2), false); $fat->addAttribute('vLiq', nfe_numero($v_liquido,2), false); for($f=0;$f<$nrw_parc;$f++){ $reg_parc = consulta_ler_objeto($res_parc); //adiciona os vencimentos $dup = &$cobr->addChild("dup"); //numero //$reg_nota->NrDoc.'/'.$reg_nota->Serie.'-'.$reg_parc->Parcela $dup->addAttribute('nDup',fill_full($reg_parc->Parcela,3) , false); //vencimento $dup->addAttribute('dVenc', $reg_parc->DT_Vencimento, false); //valor $dup->addAttribute('vDup', $reg_parc->Valor_Parcela, false); } } consulta_limpa($res_parc); if ($reg_nota->NFe_Versao == '4.00'){ $pag = &$nf_inf->addChild("pag"); $detPag = &$pag->addChild("detPag"); $detPag->addAttribute('tPag', fill_full($pag_tPag,2), false); $detPag->addAttribute('vPag', nfe_numero($v_liquido,2), false); if($diferenca > 0.001){ $detPag = &$pag->addChild("detPag"); $detPag->addAttribute('tPag', fill_full('01',2), false); $detPag->addAttribute('vPag', nfe_numero($diferenca,2), false); } } } $valor_troco = 0; if ($reg_nota->Modelo=='65'){ //consulta meios pagamentos da nota fiscal $con_parc = 'select * from nota_fiscal_finaliza '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' order by Seq'; $res_parc = consulta_sql($con_parc); $nrw_parc = consulta_num_registros($res_parc); //se tiver faturas if ($nrw_parc >0){ //para cada fatura for($f=0;$f<$nrw_parc;$f++){ $reg_parc = consulta_ler_objeto($res_parc); //adiciona os vencimentos $pag = &$nf_inf->addChild("pag"); $meio_pagto = $reg_parc->Finaliza; if ($meio_pagto==4){ $meio_pagto = 5; }else if ($meio_pagto==3){ if ($reg_parc->CartaoTipo=='DEB'){ $meio_pagto = 4; } }else if ($meio_pagto>13){ $meio_pagto = 99; } if ($reg_nota->NFe_Versao == '4.00'){ $valor_pag = arredonda_numero_menos( ($reg_parc->Valor)*100)/100; }else{ $valor_pag = arredonda_numero_menos( ($reg_parc->Valor - $reg_parc->Troco)*100)/100; } $valor_troco = $reg_parc->Troco; if ($reg_nota->NFe_Versao == '4.00'){ $detPag = &$pag->addChild("detPag"); //meio $detPag->addAttribute('tPag', fill_full($meio_pagto,2), false); //valor $detPag->addAttribute('vPag', nfe_numero($valor_pag,2), false); }else{ //meio $pag->addAttribute('tPag', fill_full($meio_pagto,2), false); //valor $pag->addAttribute('vPag', nfe_numero($valor_pag,2), false); } if ($reg_parc->Finaliza==3){ $bandeira = 99; if (strtoupper($reg_parc->CartaoBandeira)=='VISA'){ $bandeira = 1; }else if (strtoupper($reg_parc->CartaoBandeira)=='DEMOCARD'){ $bandeira = 1; }else if (strtoupper($reg_parc->CartaoBandeira)=='CIELO'){ $bandeira = 1; }else if (strtoupper($reg_parc->CartaoBandeira)=='VISANET'){ $bandeira = 1; }else if (strtoupper($reg_parc->CartaoBandeira)=='MASTERCARD'){ $bandeira = 2; }else if (strtoupper($reg_parc->CartaoBandeira)=='MASTER CARD'){ $bandeira = 2; }else if (strtoupper($reg_parc->CartaoBandeira)=='MASTER'){ $bandeira = 2; }else if (strtoupper($reg_parc->CartaoBandeira)=='AMERICAN EXPRESS'){ $bandeira = 3; }else if (strtoupper($reg_parc->CartaoBandeira)=='AMEX'){ $bandeira = 3; }else if (strtoupper($reg_parc->CartaoBandeira)=='SOROCRED'){ $bandeira = 4; }else if (strtoupper($reg_parc->CartaoBandeira)=='DINERS CLUB'){ $bandeira = 5; }else if (strtoupper($reg_parc->CartaoBandeira)=='DINERSCLUB'){ $bandeira = 5; }else if (strtoupper($reg_parc->CartaoBandeira)=='DINERS'){ $bandeira = 5; }else if (strtoupper($reg_parc->CartaoBandeira)=='ELO'){ $bandeira = 6; }else if (strtoupper($reg_parc->CartaoBandeira)=='HIPERCARD'){ $bandeira = 7; }else if (strtoupper($reg_parc->CartaoBandeira)=='HIPER'){ $bandeira = 7; }else if (strtoupper($reg_parc->CartaoBandeira)=='AURA'){ $bandeira = 8; }else if (strtoupper($reg_parc->CartaoBandeira)=='CABAL'){ $bandeira = 9; } if ($reg_nota->NFe_Versao == '4.00'){ $card = &$detPag->addChild("card"); }else{ $card = &$pag->addChild("card"); } $con_cartao = 'select * from cartao_tef '. ' where Operadora="'.$reg_parc->Cartao.'"'. ' and Dominio="'.$_SESSION["Dominio"].'"'; $res_cartao = consulta_sql($con_cartao); $reg_cartao = consulta_ler_objeto($res_cartao); consulta_limpa($res_cartao); $con_empresa_cartao = 'select * from pessoa '. ' where Pessoa="'.$reg_cartao->Pessoa.'"'. ' and Dominio="'.$_SESSION["Dominio"].'"'; $res_empresa_cartao = consulta_sql($con_empresa_cartao); $reg_empresa_cartao = consulta_ler_objeto($res_empresa_cartao); consulta_limpa($res_empresa_cartao); if (($reg_nota->NFe_Ambiente=='2')|| (data2nr(dataf($reg_nota->DH_Emissao))>= data2nr('01/01/2016')) ){ $card->addAttribute('tpIntegra', '2', false);//1-TEF - 2-POS } $card->addAttribute('CNPJ', limpa_numero($reg_empresa_cartao->CPF_CNPJ), false); $card->addAttribute('tBand', fill_full($bandeira,2), false); $card->addAttribute('cAut', $reg_parc->NrAutorizacao, false); } if ($reg_nota->NFe_Versao == '4.00'){ if ($valor_troco>0){ $pag->addAttribute('vTroco', nfe_numero($valor_troco,2), false); $valor_troco = 0; } } } } consulta_limpa($res_parc); } //consulta observações da nota e dos itens //agrupada por descrição completa //ordenado por seq item e seq_obs $obs = ''; if ($valor_troco>0){ $obs = 'Troco: '.str_replace('"','',to_money($valor_troco)); } $processos_ref = array(); $nr_proc_ref = 0; $con_obs = 'select * from nota_fiscal_obs'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and TipoObs="A" '. ' group by Texto_Completo '. ' order by Seq_Item, Seq_Obs'; $res_obs = consulta_sql($con_obs); $nrw_obs = consulta_num_registros($res_obs); //para cada obs for($o=0;$o<$nrw_obs;$o++){ $reg_obs = consulta_ler_objeto($res_obs); //adicona à obs do corpo da nota if ($obs!=''){ $obs.=';'; } if( ($reg_obs->Seq_Item==0) && ($reg_obs->Seq_Obs==15) && ($diferente) ) { //$obs.= nfe_formata_txt($reg_obs->Texto_Completo); }else{ $obs.= nfe_formata_txt($reg_obs->Texto_Completo); if (trim($reg_obs->Processo_Nr) != ''){ $processos_ref[$nr_proc_ref]['nr'] = trim($reg_obs->Processo_Nr); $processos_ref[$nr_proc_ref]['or'] = trim($reg_obs->Processo_Origem); $nr_proc_ref++; } } } consulta_limpa($res_obs); //se tem obs do corpo da nota if ($obs!=''){ //adicona à obs da nfe $inf_adic = &$nf_inf->addChild("infAdic"); //$inf_adic->addAttribute('infAdFisco', 'MD-5:593a30b3a58302b2375e947e7d36fefd', false); //texto na obs $inf_adic->addAttribute('infCpl', trim(nfe_retira_texto_excesso($obs,0,5000)), false); for($prc_ref=0;$prc_ref<$nr_proc_ref;$prc_ref++){ $inf_adic_proc = &$inf_adic->addChild("procRef"); $inf_adic_proc->addAttribute('nProc', trim(nfe_retira_texto_excesso($processos_ref[$prc_ref]['nr'],0,60)), false); $inf_adic_proc->addAttribute('indProc', trim(nfe_retira_texto_excesso($processos_ref[$prc_ref]['or'],0,1)), false); } } //exportação $cfop = $reg_nota->Nat_Op_CFOP; if (($cfop[0] == '7')|| ($cfop[0] == '8')){ if (trim($reg_nota->Importa_Exporta_Local) != ''){ $exporta = &$nf_inf->addChild("exporta"); if (($reg_nota->NFe_Versao == '3.10')||($reg_nota->NFe_Versao == '4.00')){ //uf $exporta->addAttribute('UFSaidaPais', $reg_nota->Importa_Exporta_UF, false); //local $exporta->addAttribute('xLocExporta', trim($reg_nota->Importa_Exporta_Local), false); //local if (trim($reg_nota->Importa_Exporta_Despacho)!=''){ $exporta->addAttribute('xLocDespacho', trim($reg_nota->Importa_Exporta_Despacho), false); } }else{ //uf $exporta->addAttribute('UFEmbarq', $reg_nota->Importa_Exporta_UF, false); //local $exporta->addAttribute('xLocEmbarq', trim($reg_nota->Importa_Exporta_Local), false); } } } //valida empenho/pedido//contrato if ((trim($reg_nota->Nr_Nota_Empenho) != '')|| (trim($reg_nota->Nr_Pedido_Dest) != '')|| (trim($reg_nota->Nr_Contrato) != '')){ $compra = &$nf_inf->addChild("compra"); //se tem nr nota emprenho (setor público) if (trim($reg_nota->Nr_Nota_Empenho) != ''){ //adicona dadso da nota de empenho $compra->addAttribute('xNEmp', $reg_nota->Nr_Nota_Empenho, false); } //se tem pedido de venda if (trim($reg_nota->Nr_Pedido_Dest) != ''){ //adicona dados do pedido de venda $compra->addAttribute('xPed', $reg_nota->Nr_Pedido_Dest, false); } //se tem contrato if (trim($reg_nota->Nr_Contrato) != ''){ //adicona dados do contrato $compra->addAttribute('xCont', $reg_nota->Nr_Contrato, false); } } //finaliza arquivo na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $reg_nota->NFe_Chave."-nfe.xml"); $retorno = ''; $salvou = file_exists(nfe_pasta_raiz().'tmp/'.$reg_nota->NFe_Chave."-nfe.xml"); //se consegui salvar if ($salvou){ $retorno = $reg_nota->NFe_Chave; //$retorno = ''; //echo 'gerou arquivo'; }else{ nfe_exibe_erro('FRE-002','Falha na geração do arquvo "'.$reg_nota->NFe_Chave.'-nfe.xml" na pasta "tmp"!
'. 'Verifique a estrutura de pastas no servidor!',$nr_nota); } return $retorno; } ///////////////////////////////////////////// ////////////////NOTA FISCAL////////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////CONSULTA DE RECIBO//////////////// ///////////////////////////////////////////// function nfe_gera_arquivo_consulta($nr_nota){ $con_nfe = 'select * from nota_fiscal '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; $res_nfe = consulta_sql($con_nfe); $reg_nfe = consulta_ler_objeto($res_nfe); consulta_limpa($res_nfe); $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("consReciNFe"); //$nf_inf->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance', true); //$nf_inf->addAttribute('xmlns:xsd', 'http://www.portalfiscal.inf.br/nfe', true); $nf_inf->addAttribute('versao', $reg_nfe->NFe_Versao, true); $nf_inf->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe', true); $nf_inf->addAttribute('tpAmb', $reg_nfe->NFe_Ambiente, false); $nf_inf->addAttribute('nRec', $reg_nfe->NFe_Recibo, false); //$nf_inf->addAttribute('cUf', substr($reg_nfe->NFe_Chave,0,2), false); //$nf_inf->addAttribute('tpEmis', $reg_nfe->NFe_TipoEmissao, false); //cria arquivo de consulta do lote da NF-e na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $reg_nfe->NFe_Recibo."-ped-rec.xml"); } ///////////////////////////////////////////// ///////////CONSULTA DE RECIBO//////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// /////////////////ARQUIVO AUXILIAR//////////// ///////////////////////////////////////////// function nfe_gera_arquivo_auxiliar($nr_nota){ $con_nfe = 'select * from nota_fiscal '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; $res_nfe = consulta_sql($con_nfe); $reg_nfe = consulta_ler_objeto($res_nfe); consulta_limpa($res_nfe); $ano_mes = nfe_ano_mes($reg_nfe->DH_Emissao); $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("outrasInfDANFe"); if (dataf($reg_nfe->DH_SaidaNota)=='00/00/0000'){ $data = data_atual('date'); //se tiver vazio realmente então vai pegar apenas quando emitir o danf-e $hora = nr2hora(hora_atual()); }else{ $data = substr($reg_nfe->DH_SaidaNota,0,10); $hora = substr($reg_nfe->DH_SaidaNota,11); } $nf_inf->addAttribute('horasaida', $hora , false); $nf_inf->addAttribute('dSaiEnt', $data , false); //cria arquivo de consulta do lote da NF-e na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $reg_nfe->NFe_Protocolo.'_v'.fill_full($reg_nfe->NFe_Versao,5).'-auxNFe.xml'); nfe_copia_arquivo('tmp','danfe/'.$ano_mes,$reg_nfe->NFe_Protocolo.'_v'.fill_full($reg_nfe->NFe_Versao,5).'-auxNFe.xml','',false); return (nfe_pasta_raiz().'danfe/'.$ano_mes.'/'.$reg_nfe->NFe_Protocolo.'_v'.fill_full($reg_nfe->NFe_Versao,5).'-auxNFe.xml'); } ///////////////////////////////////////////// /////////////////ARQUIVO AUXILIAR//////////// ///////////////////////////////////////////// ///////////////////////////////////////////// /////////////////INUTILIZAÇÃO//////////////// ///////////////////////////////////////////// function nfe_gera_arquivo_inutiliza($nr_nota){ $con_nfe = 'select * from nota_fiscal '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; $res_nfe = consulta_sql($con_nfe); $reg_nfe = consulta_ler_objeto($res_nfe); consulta_limpa($res_nfe); //if ($reg_nfe->Situacao $ano_mes = nfe_ano_mes(); $versao_c = '1.07'; if ($reg_nfe->NFe_Versao == '2.00'){ $versao_c = '2.00'; } if ($reg_nfe->NFe_Versao == '3.10'){ $versao_c = '3.10'; } if ($reg_nfe->NFe_Versao == '4.00'){ $versao_c = '4.00'; } if (($versao_c=='2.00')||($versao_c=='3.10')||($versao_c=='4.00')){ $chave_cancela = substr($reg_nfe->NFe_Chave,0,2). substr($reg_nfe->NFe_Chave,2,2). substr($reg_nfe->NFe_Chave,6,14). substr($reg_nfe->NFe_Chave,20,2). fill_full($reg_nfe->Serie,3). fill_full($reg_nfe->NrDoc,9). fill_full($reg_nfe->NrDoc,9); }else{ $chave_cancela = substr($reg_nfe->NFe_Chave,0,2). substr($reg_nfe->NFe_Chave,6,14). substr($reg_nfe->NFe_Chave,20,2). fill_full($reg_nfe->Serie,3). fill_full($reg_nfe->NrDoc,9). fill_full($reg_nfe->NrDoc,9); } if (!(file_exists(nfe_pasta_raiz().'retorno/'.$chave_cancela.'-inu.xml'))){ $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("inutNFe"); //$nf_inf->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance' , True); //$nf_inf->addAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema' , True); $nf_inf->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , True); $nf_inf->addAttribute('versao', $versao_c , True); $tpEmis = $reg_nfe->NFe_TipoEmissao; if (($tpEmis==6)||($tpEmis==7)){ $tpEmis = 1; } $inf_canc = &$nf_inf->addChild("infInut"); $inf_canc->addAttribute('Id', 'ID'.$chave_cancela, True); $inf_canc->addAttribute('tpAmb', $reg_nfe->NFe_Ambiente, False); $inf_canc->addAttribute('xServ', 'INUTILIZAR', False); $inf_canc->addAttribute('cUF', substr($reg_nfe->NFe_Chave,0,2), False); $inf_canc->addAttribute('ano', substr($reg_nfe->NFe_Chave,2,2), False); $inf_canc->addAttribute('CNPJ', substr($reg_nfe->NFe_Chave,6,14), False); $inf_canc->addAttribute('mod', substr($reg_nfe->NFe_Chave,20,2), False); $inf_canc->addAttribute('serie', $reg_nfe->Serie, False); $inf_canc->addAttribute('nNFIni', $reg_nfe->NrDoc, False); $inf_canc->addAttribute('nNFFin', $reg_nfe->NrDoc, False); $inf_canc->addAttribute('xJust', $reg_nfe->Cancela_Motivo_Descricao, False); $inf_canc->addAttribute('tpEmis', $tpEmis, False); //cria arquivo de consulta do lote da NF-e na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $chave_cancela.'-ped-inu.xml'); nfe_copia_arquivo('tmp','envio',$chave_cancela.'-ped-inu.xml','',false); } $ok = false; while (!($ok)){ set_time_limit(30); if ((file_exists(nfe_pasta_raiz().'retorno/'.$chave_cancela.'-inu.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$chave_cancela.'-inu.err'))){ $ok = true; sleep(5); if (file_exists(nfe_pasta_raiz().'retorno/'.$chave_cancela.'-inu.xml')){ $status = ''; $motivo = ''; $protocolo_nr = ''; $protocolo_dh = ''; $protocolo_pr = ''; $protocolo_dv = ''; $xml = new XML(); $xml->fromFile(nfe_pasta_raiz().'retorno/', $chave_cancela.'-inu.xml', true); //le nr do lote no arquivo if ($xml->root->name == 'retInutNFe'){ $status = '2'; foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'infInut'){ $txt_inf_prot = $xml->root->childs[$key]->toString(); $prot_nfe = &$xml->root->childs[$key]; $status = '1'; } } } if ($status == '1'){ $status = ''; foreach($prot_nfe->atts as $key => $value){ if ($prot_nfe->atts[$key]->name == 'cStat'){ $status = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'xMotivo'){ $motivo = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'verAplic'){ $protocolo_pr = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'dhRecbto'){ $protocolo_dh = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'nProt'){ $protocolo_nr = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'digVal'){ $protocolo_dv = $prot_nfe->atts[$key]->value; } } } if ($status == '102'){ //copia arquivo para a pasta autorizada nfe_copia_arquivo('retorno','SEFAZ/Inutilizacao/'.$ano_mes,$chave_cancela.'-inu.xml','',false); //cria arquivo de distribuição da Nfe cancelada $texto_nfe = xml_fromFile( nfe_pasta_raiz().'backup/Autorizados/'.$ano_mes, $chave_cancela.'-ped-inu.xml'); $string = ''. ''. $texto_nfe. ''. $txt_inf_prot. ''. ''; $Handle = fopen(nfe_pasta_raiz().'tmp/'.$protocolo_nr.'_v'.fill_full($versao_c,5).'-procInutNFe.xml', 'w'); $Data = utf8_encode($string); fwrite($Handle, $Data); fclose($Handle); //salva dados da autorização na tabela de NF nfe_copia_arquivo('tmp','SEFAZ/NF-es/'.$ano_mes.'/Inutilizadas',$protocolo_nr.'_v'.fill_full($versao_c,5).'-procInutNFe.xml','',false); $upt_nota = 'Update nota_fiscal set'. ' NFe_Protocolo_C="'.$protocolo_nr.'", '. ' NFe_Protocolo_C_DH="'.$protocolo_dh.'", '. ' NFe_Protocolo_C_Sig="'.$protocolo_pr.'", '. ' NFe_Situacao="'.$status.'", '. ' NFe_Protocolo_C_Motivo="'.$motivo.'" '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; consulta_sql($upt_nota); return true; }else { //salva arquivo na pasta de erros nfe_copia_arquivo('retorno','erros/'.$ano_mes,$chave_cancela.'-inu.xml','',true); //exibe motivo da Denegação da Autorização nfe_exibe_erro('FRE-104','A SEFAZ não autorizou a Inutilização da Numeração desta NF-e!'. '"'.$status.'" - '.$motivo,''); return false; } }else if (file_exists(nfe_pasta_raiz().'retorno/'.$chave_cancela.'-inu.err')){ //exibe mensagem do arquivo de erro $conteudo_arquivo = nfe_abre_arquivo_err($chave_cancela.'-inu.err'); nfe_exibe_erro('FRE-105','Falha no Processamento do Arquivo "'.$chave_cancela.'-inu.err"!'. $conteudo_arquivo,''); nfe_copia_arquivo('retorno','erros/'.$ano_mes,$chave_cancela.'-inu.err','',true); return false; }else{ nfe_exibe_erro('FRE-106','Falha no Processamento do Arquivo "'.$chave_cancela.'-inu.xml"!',''); return false; } } } } ///////////////////////////////////////////// /////////////////INUTILIZAÇÃO//////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// /////////////////CANCELAMENTO//////////////// ///////////////////////////////////////////// function nfe_gera_arquivo_cancela($nr_nota){ $con_nfe = 'select * from nota_fiscal '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; $res_nfe = consulta_sql($con_nfe); $reg_nfe = consulta_ler_objeto($res_nfe); consulta_limpa($res_nfe); $ano_mes = nfe_ano_mes(); $versao_c = '1.07'; if ($reg_nfe->NFe_Versao == '2.00'){ $versao_c = '2.00'; } if ($reg_nfe->NFe_Versao == '3.10'){ $versao_c = '3.10'; } if ($reg_nfe->NFe_Versao == '4.00'){ $versao_c = '4.00'; } $tp_cancela = config_pad('nfe_cancela'); /*if (substr($reg_nfe->NFe_Chave,0,2)=='41'){ $tp_cancela = 'normal'; } if ( substr($reg_nfe->NFe_Chave,34,1)=='7'){ $tp_cancela = 'normal'; } */ if ($tp_cancela=='evento'){ //precisa ver a variável anoMes (acho que vai com a data/hora do cancelamento) if (!(file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-ret-env-canc.xml'))){ $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("envEvento"); //$nf_inf->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance' , True); //$nf_inf->addAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema' , True); $nf_inf->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , True); $nf_inf->addAttribute('versao', '1.00' , True); $nf_inf->addAttribute('idLote', '1', False);//TODO: precisa clacular o lote do cancelamento $evento = &$nf_inf->addChild("evento"); $evento->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , True); $evento->addAttribute('versao', '1.00' , True); $cdOrgao = substr($reg_nfe->NFe_Chave,0,2); //if ( substr($reg_nfe->NFe_Chave,34,1)=='3'){ // $cdOrgao = '91'; //} $uf = substr($reg_nfe->NFe_Chave,0,2); $data = substr($reg_nfe->NFe_Protocolo_C_DH,0,10); $dif_UTC = calcula_horario_verao($data,$uf); $inf_canc = &$evento->addChild("infEvento"); $inf_canc->addAttribute('Id', 'ID110111'.$reg_nfe->NFe_Chave.'01', True); $inf_canc->addAttribute('cOrgao', $cdOrgao, False); $inf_canc->addAttribute('tpAmb', $reg_nfe->NFe_Ambiente, False); $inf_canc->addAttribute('CNPJ', substr($reg_nfe->NFe_Chave,6,14), False); $inf_canc->addAttribute('chNFe', $reg_nfe->NFe_Chave, False); $inf_canc->addAttribute('dhEvento', str_replace(' ','T',$reg_nfe->NFe_Protocolo_C_DH).$dif_UTC, False); $inf_canc->addAttribute('tpEvento', '110111', False); $inf_canc->addAttribute('nSeqEvento', '1', False); $inf_canc->addAttribute('verEvento', '1.00', False); $det_evento = &$inf_canc->addChild("detEvento"); $det_evento->addAttribute('versao', '1.00' , True); $det_evento->addAttribute('descEvento', 'Cancelamento', False); $det_evento->addAttribute('nProt', $reg_nfe->NFe_Protocolo, False); $det_evento->addAttribute('xJust', $reg_nfe->Cancela_Motivo_Descricao, False); //cria arquivo de consulta do lote da NF-e na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $reg_nfe->NFe_Chave.'-env-canc.xml'); nfe_copia_arquivo('tmp','envio',$reg_nfe->NFe_Chave.'-env-canc.xml','',false); } $retorno = false; $ok = false; while (!($ok)){ set_time_limit(60); if ((file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-ret-env-canc.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-ret-env-canc.err'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-env-canc.err'))){ $ok = true; sleep(10); if (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-ret-env-canc.xml')){ $retorno = true; $status = 'e'; $motivo = ''; $protocolo_nr = ''; $protocolo_dh = ''; $protocolo_pr = ''; $protocolo_dv = ''; $xml = new XML(); $xml->fromFile(nfe_pasta_raiz().'retorno/', $reg_nfe->NFe_Chave.'-ret-env-canc.xml', true); //le nr do lote no arquivo if ($xml->root->name == 'retEnvEvento'){ $status = '2'; foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'retEvento'){ //$txt_inf_prot = $xml->root->childs[$key]->toString(); $ret_cce = &$xml->root->childs[$key]; $status = '1'; } } } if ($status == '1'){ $status = ''; foreach($ret_cce->childs as $key => $value){ if ($ret_cce->childs[$key]->name== 'infEvento'){ $inf_cce = &$ret_cce->childs[$key]; $txt_inf_prot = $ret_cce->childs[$key]->toString(); $status = '1'; } } if ($status == '1'){ $status = ''; foreach($inf_cce->atts as $key => $value){ if ($inf_cce->atts[$key]->name == 'cStat'){ $status = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'xMotivo'){ $motivo = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'nProt'){ $protocolo_nr = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'dhRegEvento'){ $protocolo_dh = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'verAplic'){ $protocolo_pr = $inf_cce->atts[$key]->value; } } if (($status!='135')&& ($status!='136')&& ($status!='155')){ $retorno = false; } }else{ $status = 'ERR'; $motivo = 'Informações da Autorização do Cancelamento não Encontradas!'; $retorno = false; } }else{ $status = ''; foreach($xml->root->atts as $key => $value){ if ($xml->root->atts[$key]->name == 'cStat'){ $status = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'xMotivo'){ $motivo = $xml->root->atts[$key]->value; } } $retorno = false; } if($retorno){ //remove arquivo da pasta e coloca na pasta de CCes nfe_copia_arquivo('retorno','SEFAZ/Cancelamento/'.$ano_mes,$reg_nfe->NFe_Chave.'-ret-env-canc.xml','',false); //monta arquivo distribuição CC-e set_time_limit(30); sleep(5); $Versao_Evento = '1.00'; $ano_mes_aut = nfe_ano_mes($reg_nfe->DH_Emissao); $texto_cce = xml_fromFile( nfe_pasta_raiz().'backup/Autorizados/'.$ano_mes_aut, $reg_nfe->NFe_Chave.'_110111_01-procEventoNFe.xml'); $string = ''. //''. $texto_cce; //''; $Handle = fopen(nfe_pasta_raiz().'tmp/'.$protocolo_nr.'_v'.fill_full($Versao_Evento,5).'-procEventoNFe.xml', 'w'); $Data = utf8_encode($string); fwrite($Handle, $Data); fclose($Handle); //coloca arquivo ditribuição CCe na pasta de CCe do Mês nfe_copia_arquivo('tmp','SEFAZ/NF-es/'.$ano_mes.'/Canceladas',$protocolo_nr.'_v'.fill_full($Versao_Evento,5).'-procEventoNFe.xml','',false); //faz update com o protocolo e dh no evento da NF-e set_time_limit(30); if ($status!='155'){ $motivo = 'Cancelamento - '.$motivo; } $upt_nota = 'Update nota_fiscal set'. ' NFe_Protocolo_C="'.$protocolo_nr.'", '. ' NFe_Protocolo_C_DH="'.$protocolo_dh.'", '. ' NFe_Protocolo_C_Sig="'.$protocolo_pr.'", '. ' NFe_Situacao="'.$status.'", '. ' NFe_Protocolo_C_Motivo="'.$motivo.'" '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; //echo $upt_nota; consulta_sql($upt_nota); //$retorno = false; }else{ echo '
Rejeição do Arquivo da NF-e pela SEFAZ!'. $status.'-'.$motivo.'
'; //remove arquivo da pasta e coloca na pasta de erros nfe_copia_arquivo('retorno','erros/'.$ano_mes,$reg_nfe->NFe_Chave.'-ret-env-canc.xml','',true); } }else{ //exibe mensagem do arquivo de erro if (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-ret-env-canc.err')){ $conteudo_arquivo = nfe_abre_arquivo_err($reg_nfe->NFe_Chave.'-ret-env-canc.err'); echo '
Falha no Processamento do Arquivo "'.$reg_nfe->NFe_Chave.'-ret-env-canc.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$reg_nfe->NFe_Chave.'-ret-env-canc.err','',true); }else{ $conteudo_arquivo = nfe_abre_arquivo_err($reg_nfe->NFe_Chave.'-env-canc.err'); echo '
Falha no Processamento do Arquivo "'.$reg_nfe->NFe_Chave.'-env-canc.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$reg_nfe->NFe_Chave.'-env-canc.err','',true); } $retorno = false; } } }//fim while return $retorno; }else{//cancelamento sem ser por evento if (!(file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-can.xml'))){ $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("cancNFe"); //$nf_inf->addAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance' , True); //$nf_inf->addAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema' , True); $nf_inf->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , True); $nf_inf->addAttribute('versao', $versao_c , True); $inf_canc = &$nf_inf->addChild("infCanc"); $inf_canc->addAttribute('Id', 'ID'.$reg_nfe->NFe_Chave, True); $inf_canc->addAttribute('tpAmb', $reg_nfe->NFe_Ambiente, False); $inf_canc->addAttribute('xServ', 'CANCELAR', False); $inf_canc->addAttribute('chNFe', $reg_nfe->NFe_Chave, False); $inf_canc->addAttribute('nProt', $reg_nfe->NFe_Protocolo, False); $inf_canc->addAttribute('xJust', $reg_nfe->Cancela_Motivo_Descricao, False); $inf_canc->addAttribute('tpEmis', $reg_nfe->NFe_TipoEmissao, False); //cria arquivo de consulta do lote da NF-e na pasta tmp $xml->toFile(nfe_pasta_raiz().'tmp/', $reg_nfe->NFe_Chave.'-ped-can.xml'); nfe_copia_arquivo('tmp','envio',$reg_nfe->NFe_Chave.'-ped-can.xml','',false); } $ok = false; while (!($ok)){ set_time_limit(60); if ((file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-can.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-can.err'))){ $ok = true; sleep(10); if (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-can.xml')){ $status = 'e'; $motivo = ''; $protocolo_nr = ''; $protocolo_dh = ''; $protocolo_pr = ''; $protocolo_dv = ''; $xml = new XML(); $xml->fromFile(nfe_pasta_raiz().'retorno/', $reg_nfe->NFe_Chave.'-can.xml', true); //le nr do lote no arquivo if ($xml->root->name == 'retCancNFe'){ foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'infCanc'){ $txt_inf_prot = $xml->root->childs[$key]->toString(); $prot_nfe = &$xml->root->childs[$key]; $status = '1'; } } } if ($status == '1'){ $status = ''; foreach($prot_nfe->atts as $key => $value){ if ($prot_nfe->atts[$key]->name == 'cStat'){ $status = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'xMotivo'){ $motivo = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'verAplic'){ $protocolo_pr = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'dhRecbto'){ $protocolo_dh = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'nProt'){ $protocolo_nr = $prot_nfe->atts[$key]->value; } if ($prot_nfe->atts[$key]->name == 'digVal'){ $protocolo_dv = $prot_nfe->atts[$key]->value; } } } if (($status == '101')||($status == '151')){ //copia arquivo para a pasta autorizada nfe_copia_arquivo('retorno','SEFAZ/Cancelamento/'.$ano_mes,$reg_nfe->NFe_Chave.'-can.xml','',false); //cria arquivo de distribuição da Nfe cancelada $texto_nfe = xml_fromFile( nfe_pasta_raiz().'backup/Autorizados/'.$ano_mes, $reg_nfe->NFe_Chave.'-ped-can.xml'); $string = ''. ''. $texto_nfe. ''. $txt_inf_prot. ''. ''; $Handle = fopen(nfe_pasta_raiz().'tmp/'.$protocolo_nr.'_v'.fill_full($versao_c,5).'-procCancNFe.xml', 'w'); $Data = utf8_encode($string); fwrite($Handle, $Data); fclose($Handle); //salva dados da autorização na tabela de NF nfe_copia_arquivo('tmp','SEFAZ/NF-es/'.$ano_mes.'/Canceladas',$protocolo_nr.'_v'.fill_full($versao_c,5).'-procCancNFe.xml','',false); $upt_nota = 'Update nota_fiscal set'. ' NFe_Protocolo_C="'.$protocolo_nr.'", '. ' NFe_Protocolo_C_DH="'.$protocolo_dh.'", '. ' NFe_Protocolo_C_Sig="'.$protocolo_pr.'", '. ' NFe_Situacao="'.$status.'", '. ' NFe_Protocolo_C_Motivo="'.$motivo.'" '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; consulta_sql($upt_nota); return true; }else { //salva arquivo na pasta de erros nfe_copia_arquivo('retorno','erros/'.$ano_mes,$reg_nfe->NFe_Chave.'-can.xml','',true); //exibe motivo da Denegação da Autorização nfe_exibe_erro('FRE-101','A SEFAZ não autorizou o Cancelamento desta NF-e!'. '"'.$status.'" - '.$motivo,''); return false; } }else if (file_exists(nfe_pasta_raiz().'retorno/'.$reg_nfe->NFe_Chave.'-can.err')){ //exibe mensagem do arquivo de erro $conteudo_arquivo = nfe_abre_arquivo_err($reg_nfe->NFe_Chave.'-can.err'); nfe_exibe_erro('FRE-102','Falha no Processamento do Arquivo "'.$reg_nfe->NFe_Chave.'-can.err"!'. $conteudo_arquivo,''); nfe_copia_arquivo('retorno','erros/'.$ano_mes,$reg_nfe->NFe_Chave.'-can.err','',true); return false; }else{ nfe_exibe_erro('FRE-103','Falha no Processamento do Arquivo "'.$reg_nfe->NFe_Chave.'-can.xml"!',''); return false; } } } }//fim cancelamento sem ser por evento } ///////////////////////////////////////////// /////////////////CANCELAMENTO//////////////// ///////////////////////////////////////////// ///////////////////////////////////////////// /////////////LOTE DE NOTA FISCAL///////////// ///////////////////////////////////////////// function nfe_gera_arquivo_lote($lista_nfs){ $nrand = rand(500,1500); $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("MontarLoteNFe"); foreach($lista_nfs as $key => $nr_nota){ $nf_inf->addAttribute('ArquivoNFe', $nr_nota.'-nfe.xml' , false); } $xml->toFile(nfe_pasta_raiz().'tmp/', $nrand.'-montar-lote.xml'); //$copiou = nfe_copia_arquivo('tmp','envio_lote',$nrand.'-montar-lote.xml','',false); //if ($copiou){ return $nrand; //}else{ // return 0; //} } ///////////////////////////////////////////// /////////////LOTE DE NOTA FISCAL///////////// ///////////////////////////////////////////// ///////////////////////////////////////////// ///////////CONSULTA SIT SEM RECIBO/////////// ///////////////////////////////////////////// function nfe_gera_arquivo_sit_nfe($chave_nfe,$tpAmb){ $xml = new XML(); //adiciona dados da nota $nf_inf = &$xml->createRoot("consSitNFe"); $nf_inf->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $versao = config_pad('nfe_versao'); //if (data2nr(data_atual('data'))>=data2nr('01/07/2012')){ //if (substr($chave_nfe,0,2) != '41'){ // $versao = '2.01'; //} //} $nf_inf->addAttribute('versao', $versao , true); $nf_inf->addAttribute('tpAmb', $tpAmb , false); $nf_inf->addAttribute('xServ', 'CONSULTAR' , false); $nf_inf->addAttribute('chNFe', $chave_nfe , false); $xml->toFile(nfe_pasta_raiz().'tmp/', $chave_nfe.'-ped-sit.xml'); return nfe_copia_arquivo('tmp','envio',$chave_nfe.'-ped-sit.xml','',false); } ///////////////////////////////////////////// ///////////CONSULTA SIT SEM RECIBO/////////// ///////////////////////////////////////////// ///////////////////////////////////////////// /////////// CC-E ENVIO /////////// ///////////////////////////////////////////// function cce_gera_arquivo_envio($nr_nota,$evento){ $con_nota = 'select * from nota_fiscal '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'; $res_nota = consulta_sql($con_nota); $reg_nota = consulta_ler_objeto($res_nota); consulta_limpa($res_nota); $con_evento = 'select * from nota_fiscal_evento '. ' where Nr_Nota="'.$nr_nota.'" '. ' and Dominio ="'.$_SESSION['Dominio'].'"'. ' and Empresa="'.$_SESSION["Empresa_Codigo"].'"'. ' and Seq_Evento="'.$evento.'"'; $res_evento = consulta_sql($con_evento); $reg_evento = consulta_ler_objeto($res_evento); consulta_limpa($res_evento); $nome_arq_cce = substr($reg_evento->Id_Evento,6,44).'-'.substr($reg_evento->Id_Evento,50,2); $xml = new XML(); //adiciona dados da nota $env_evento = &$xml->createRoot("envEvento"); $env_evento->addAttribute('versao', $reg_evento->Versao_Evento, true); $env_evento->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $env_evento->addAttribute('idLote', $reg_evento->CCe_Lote , false); $e_evento = &$env_evento->addChild("evento"); //$e_evento = &$xml->createRoot("evento"); $e_evento->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $e_evento->addAttribute('versao', $reg_evento->Versao_Evento, true); $inf_evento = &$e_evento->addChild("infEvento"); $inf_evento->addAttribute('Id', 'ID'.$reg_evento->Id_Evento, True); $inf_evento->addAttribute('cOrgao', $reg_evento->Cod_Orgao , false); $inf_evento->addAttribute('tpAmb', $reg_nota->NFe_Ambiente , false); $inf_evento->addAttribute('CNPJ', limpa_numero($reg_nota->Empresa_CNPJ) , false); $inf_evento->addAttribute('chNFe', $reg_nota->NFe_Chave , false); //$dif_UTC = '-03:00'; /*$ver_php = phpversion(); if ($ver_php[0]!='4'){ date_default_timezone_set('America/Sao_Paulo'); //só faz isso no php 5 }*/ $uf = substr($reg_nota->NFe_Chave,0,2); $data = substr($reg_evento->DH_Evento,0,10); $dif_UTC = calcula_horario_verao($data,$uf);/*date('O', mktime( 12, 00 , 00 , substr($reg_evento->DH_Evento,5,2) , substr($reg_evento->DH_Evento,8,2) , substr($reg_evento->DH_Evento,0,4) ) );*/ //$dif_UTC = '-2000'; // 01234 //$dif_UTC = substr($dif_UTC,0,3).':'.substr($dif_UTC,3,2); $inf_evento->addAttribute('dhEvento', str_replace(' ','T',$reg_evento->DH_Evento).$dif_UTC , false); $inf_evento->addAttribute('tpEvento','110110' , false); $inf_evento->addAttribute('nSeqEvento', $reg_evento->Seq_Evento , false); $inf_evento->addAttribute('verEvento', $reg_evento->Versao_Evento , false); $det_evento = &$inf_evento->addChild("detEvento"); $det_evento->addAttribute('versao', $reg_evento->Versao_Evento, true); $det_evento->addAttribute('descEvento', 'Carta de Correcao' , false); $obs= nfe_formata_txt($reg_evento->Texto_Completo); $det_evento->addAttribute('xCorrecao', trim(nfe_retira_texto_excesso($obs,0,1000)) , false); $obs= $reg_evento->Texto_Lei; $det_evento->addAttribute('xCondUso', trim($obs) , false); $xml->toFile(nfe_pasta_raiz().'tmp/', $nome_arq_cce.'-env-cce.xml'); return nfe_copia_arquivo('tmp','envio',$nome_arq_cce.'-env-cce.xml','',false); } function cce_envio($nr_nota,$evento){ $retorno = true; //verifica se já tem os dados da CC-e preenchidos, senão coloca eles cce_gera_chave($nr_nota,$evento); $con_evento = 'select * from nota_fiscal_evento '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Seq_Evento = "'.$evento.'"'; $res_evento = consulta_sql($con_evento); $reg_evento = consulta_ler_objeto($res_evento); consulta_limpa($res_evento); $protocolo_nr = $reg_evento->CCe_Protocolo; $ano_mes = nfe_ano_mes($reg_evento->DH_Evento); $chave_cce = $reg_evento->Id_Evento; $nome_arq_cce = substr($chave_cce,6,44).'-'.substr($chave_cce,50,2); if ($protocolo_nr==''){ //apaga os erros antigos pra não ficar lixo antigo if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.err')){ unlink(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.err'); } if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-env-cce.err')){ unlink(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-env-cce.err'); } //cria o arquivo e envia caso o retrono ainda não exista if (!(file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.xml'))) { $retorno = cce_gera_arquivo_envio($nr_nota,$evento); } if ($retorno){ $ok = false; while (!($ok)){ set_time_limit(30); if ((file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.err'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-env-cce.err'))){ $ok = true; sleep(5); if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.xml')){ $status = ''; $motivo = ''; $protocolo_nr = ''; $protocolo_dh = ''; $xml = new XML(); $xml->fromFile(nfe_pasta_raiz().'retorno/', $nome_arq_cce.'-ret-env-cce.xml', true); //le nr do lote no arquivo if ($xml->root->name == 'retEnvEvento'){ $status = '2'; foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'retEvento'){ //$txt_inf_prot = $xml->root->childs[$key]->toString(); $ret_cce = &$xml->root->childs[$key]; $status = '1'; } } } if ($status == '1'){ $status = ''; foreach($ret_cce->childs as $key => $value){ if ($ret_cce->childs[$key]->name== 'infEvento'){ $inf_cce = &$ret_cce->childs[$key]; $txt_inf_prot = $ret_cce->childs[$key]->toString(); $status = '1'; } } if ($status == '1'){ $status = ''; foreach($inf_cce->atts as $key => $value){ if ($inf_cce->atts[$key]->name == 'cStat'){ $status = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'xMotivo'){ $motivo = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'nProt'){ $protocolo_nr = $inf_cce->atts[$key]->value; } if ($inf_cce->atts[$key]->name == 'dhRegEvento'){ $protocolo_dh = $inf_cce->atts[$key]->value; } } if (($status!='135')&& ($status!='136')){ $retorno = false; } }else{ $status = 'ERR'; $motivo = 'Informações da Autorização do Evento não Encontradas!'; $retorno = false; } }else{ $status = ''; foreach($xml->root->atts as $key => $value){ if ($xml->root->atts[$key]->name == 'cStat'){ $status = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'xMotivo'){ $motivo = $xml->root->atts[$key]->value; } } $retorno = false; } if($retorno){ //remove arquivo da pasta e coloca na pasta de CCes nfe_copia_arquivo('retorno','SEFAZ/CCe/'.$ano_mes,$nome_arq_cce.'-ret-env-cce.xml','',false); //monta arquivo distribuição CC-e set_time_limit(30); sleep(5); $ano_mes2 = '20'.substr($nome_arq_cce,2,4); $texto_cce = xml_fromFile( nfe_pasta_raiz().'backup/Autorizados/'.$ano_mes2, str_replace('-','_',$nome_arq_cce).'-procEventoNFe.xml'); $string = ''. // ''. $texto_cce; //''; $Handle = fopen(nfe_pasta_raiz().'tmp/'.$protocolo_nr.'_v'.fill_full($reg_evento->Versao_Evento,5).'-procEventoNFe.xml', 'w'); $Data = utf8_encode($string); fwrite($Handle, $Data); fclose($Handle); //coloca arquivo ditribuição CCe na pasta de CCe do Mês nfe_copia_arquivo('tmp','SEFAZ/NF-es/'.$ano_mes.'/CCe',$protocolo_nr.'_v'.fill_full($reg_evento->Versao_Evento,5).'-procEventoNFe.xml','',false); //faz update com o protocolo e dh no evento da NF-e set_time_limit(30); $upd_evento = 'Update nota_fiscal_evento set '. ' CCe_Protocolo = "'.$protocolo_nr.'", '. ' CCe_Protocolo_DH = "'.$protocolo_dh.'", '. ' CCe_Situacao = "'.$status.'", '. ' CCe_Protocolo_Motivo = "'.$motivo.'" '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and Nr_Nota = "'.$nr_nota.'"'. ' and Seq_Evento = "'.$evento.'"'. ' and CCe_Protocolo = ""'; $res = consulta_sql($upd_evento, true, 1); }else{ echo '
Rejeição do Arquivo da NF-e pela SEFAZ!'. $status.'-'.$motivo.'
'; //remove arquivo da pasta e coloca na pasta de erros nfe_copia_arquivo('retorno','erros/'.$ano_mes,$nome_arq_cce.'-ret-env-cce.xml','',true); } }else{ //exibe mensagem do arquivo de erro if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_cce.'-ret-env-cce.err')){ $conteudo_arquivo = nfe_abre_arquivo_err($nome_arq_cce.'-ret-env-cce.err'); echo '
Falha no Processamento do Arquivo "'.$nome_arq_cce.'-ret-env-cce.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$nome_arq_cce.'-ret-env-cce.err','',true); }else{ $conteudo_arquivo = nfe_abre_arquivo_err($nome_arq_cce.'-env-cce.err'); echo '
Falha no Processamento do Arquivo "'.$nome_arq_cce.'-env-cce.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$nome_arq_cce.'-env-cce.err','',true); } $retorno = false; } }//fim tem arquivos na pasta }//fi9m while não tem arquivo de retorno }//fim se não gerou arquivo corretamente }//fim não tem nr de protocolo return $retorno; } ///////////////////////////////////////////// /////////// CC-E ENVIO /////////// ///////////////////////////////////////////// function nfe_manifestacao_consulta($tentativa=1){ //consulta if ($tentativa>1){ echo '
Consulta Nr '.$tentativa.'...
'; } $repetir = false; $con_empresa = 'select CPF_CNPJ from pessoa'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa = "'.$_SESSION['Empresa_Codigo'].'"'; $res_empresa = consulta_sql($con_empresa); $reg_empresa = consulta_ler_linha($res_empresa); consulta_limpa($res_empresa); $res_ender = 'select Codigo_Cidade from pessoa_endereco '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and Situacao="A" '. ' order by Seq_Endereco'; $res_ender = consulta_sql($res_ender); $reg_ender = consulta_ler_linha($res_ender); consulta_limpa($res_ender); $cnpj_empresa = limpa_numero($reg_empresa[0]); if (!(file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.xml'))){ //escluir o arquivo err que pode existir na pasta if (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.err')){ unlink(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.err'); } if (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-con-dist-dfe.err')){ unlink(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-con-dist-dfe.err'); } //cria nova arquivo de consulta $xml = new XML(); //adiciona dados da nota /*$env_cons_dest = &$xml->createRoot("consNFeDest"); $env_cons_dest->addAttribute('versao', '1.01', true); $env_cons_dest->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $env_cons_dest->addAttribute('tpAmb', nfe_busca_ambiente_evento() , false); $env_cons_dest->addAttribute('xServ', 'CONSULTAR NFE DEST', false); $env_cons_dest->addAttribute('CNPJ', $cnpj_empresa, false); $env_cons_dest->addAttribute('indNFe', '0',false); $env_cons_dest->addAttribute('indEmi', '0',false); */ $env_cons_dest = &$xml->createRoot("distDFeInt"); $env_cons_dest->addAttribute('versao', '1.00', true); $env_cons_dest->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); //$env_cons_dest->addAttribute('tpAmb', '1' , false); $env_cons_dest->addAttribute('tpAmb', nfe_busca_ambiente_evento() , false); $env_cons_dest->addAttribute('cUFAutor', substr($reg_ender[0],0,2), false); $env_cons_dest->addAttribute('CNPJ', $cnpj_empresa, false); $con_nsu = 'select NFe_Chave from nota_fiscal_manifestacao '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and NSU =-1'; $res_nsu = consulta_sql($con_nsu); $reg_nsu = consulta_ler_linha($res_nsu); consulta_limpa($res_nsu); $distNSU = &$env_cons_dest->addChild("distNSU"); $distNSU->addAttribute('ultNSU', fill_full($reg_nsu[0],15),false); $xml->toFile(nfe_pasta_raiz().'tmp/', $cnpj_empresa.'-con-dist-dfe.xml'); nfe_copia_arquivo('tmp','envio',$cnpj_empresa.'-con-dist-dfe.xml','',false); } $ok = false; $ano_mes = nfe_ano_mes(data_atual('date')); sleep(1); //echo $cnpj_empresa.'-ret-cons-nfe-dest.xml'; flush(); @ob_flush(); flush(); @ob_flush(); while (!($ok)){ set_time_limit(30); if ((file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.err'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-con-dist-dfe.err'))){ $ok = true; sleep(1); if (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.xml')){ $status = ''; $motivo = ''; $ult_nsu = 0; $max_nsu = 0; $continua = 0; $xml = new XML(); $XML_lote = $xml->fromFile(nfe_pasta_raiz().'retorno/', $cnpj_empresa.'-dist-dfe.xml', true); $posF = strpos($XML_lote,''); $XML_lote = substr($XML_lote,0,$posF); $posI = strpos($XML_lote,'')+16; $XML_lote = substr($XML_lote,$posI); //le nr do lote no arquivo if ($xml->root->name == 'retDistDFeInt'){ foreach($xml->root->atts as $key => $value){ if ($xml->root->atts[$key]->name == 'cStat'){ $status = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'xMotivo'){ $motivo = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'indCont'){ $continua = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'ultNSU'){ $ult_nsu = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'maxNSU'){ $max_nsu = $xml->root->atts[$key]->value; } } } if ($status=='138'){ echo '
'.$status.'-'.$motivo.'
'; }else{ echo '
'.$status.'-'.$motivo.'
'; } if ($status=='138'){ //se tem documentos no arquivo processa eles foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'loteDistDFeInt'){ //echo '
'; $lote = &$xml->root->childs[$key]; foreach($lote->childs as $key2 => $value2){ if ($lote->childs[$key2]->name== 'docZip'){ //echo '
'; $dados_Zip[' NSU'] = 0; $dados_Zip[' schema'] = ''; $docZip = &$lote->childs[$key2]; foreach($docZip->atts as $key3 => $value3){ $dados_Zip[$docZip->atts[$key3]->name]=$docZip->atts[$key3]->value; } $tipoZip = explode('_',$dados_Zip[' schema']); $arquivo = $cnpj_empresa.'-'.$dados_Zip[' NSU']; $xmlZ = $XML_lote; $posI = strpos($xmlZ,'NSU="'.$dados_Zip[' NSU'].'"'); $xmlZ = substr($xmlZ,$posI); $posI2 = strpos($xmlZ,'>'); $xmlZ = substr($xmlZ,$posI2+1); $posF = strpos($xmlZ,''); $xmlZ = substr($xmlZ,0,$posF); //gzuncompress( //echo 'posF'.$posF; $xml = gzdecodeFree(base64_decode($xmlZ)); $dados_NFe[' NSU'] = $dados_Zip[' NSU']; $dados_NFe['arquivo'] = ''; $dados_NFe['chNFe'] =''; $dados_NFe['CNPJ'] =''; $dados_NFe['CPF'] =''; $dados_NFe['xNome'] =''; $dados_NFe['IE'] =''; $dados_NFe['dEmi'] =''; $dados_NFe['tpNF'] =''; $dados_NFe['vNF'] =''; $dados_NFe['digVal'] =''; $dados_NFe['dhRecbto'] =''; $dados_NFe['cSitNFe'] =''; $dados_NFe['cSitConf'] =''; $ok_ins = false; if ($tipoZip[0]=='procNFe'){ // //consulta XML na pata Docs e coloca em Download com o nome correto $arquivo.= '-procNFe.xml'; $dados_NFe['chNFe'] = substr(XML_BuscaTag($xml,'Id',false),3); $dados_NFe['CNPJ'] = XML_BuscaTag(' '.XML_BuscaTag($xml,'emit'),'CNPJ'); $dados_NFe['CPF'] = XML_BuscaTag(' '.XML_BuscaTag($xml,'emit'),'CPF'); $dados_NFe['xNome'] = XML_BuscaTag(XML_BuscaTag($xml,'emit'),'xNome'); $dados_NFe['IE'] = XML_BuscaTag(XML_BuscaTag($xml,'emit'),'IE'); $dados_NFe['dEmi'] = XML_BuscaTag($xml,'dhEmi'); $dados_NFe['tpNF'] = XML_BuscaTag($xml,'tpNF'); $dados_NFe['vNF'] = XML_BuscaTag(XML_BuscaTag($xml,'total'),'vNF'); $dados_NFe['cSitNFe']= '1'; $dados_NFe['CNPJD'] = XML_BuscaTag(' '.XML_BuscaTag($xml,'dest'),'CNPJ'); if ($cnpj_empresa!=$dados_NFe['CNPJD']){ $dados_NFe['cSitNFe']= '4'; } if (file_exists(nfe_pasta_raiz().'retorno/dfe/'.$cnpj_empresa.'-'.$dados_NFe[' NSU'].'-procNFe.xml')){ nfe_copia_arquivo_renomeia('retorno/dfe/', $cnpj_empresa.'-'.$dados_NFe[' NSU'].'-procNFe.xml', $dados_NFe['chNFe'].'-nfe.xml'); } if (file_exists(nfe_pasta_raiz().'retorno/dfe/'.$dados_NFe['chNFe'].'-procNFe.xml')){ nfe_copia_arquivo_renomeia('retorno/dfe/', $dados_NFe['chNFe'].'-procNFe.xml', $dados_NFe['chNFe'].'-nfe.xml'); } if (file_exists(nfe_pasta_raiz().'retorno/dfe/'.$dados_NFe['chNFe'].'-nfe.xml')){ $ano_mes = nfe_ano_mes($dados_NFe['dEmi']); nfe_copia_arquivo('retorno/dfe/','SEFAZ/NF-es/'.$ano_mes.'/Recebidas/',$dados_NFe['chNFe'].'-nfe.xml'); } $ok_ins = true; }else if ($tipoZip[0]=='resNFe'){ //sem protocolo (não sei quais casos) //somente cabeçalho $arquivo.= '-nfe.xml'; $dados_NFe['chNFe'] = XML_BuscaTag($xml,'chNFe'); $dados_NFe['CNPJ'] = XML_BuscaTag($xml,'CNPJ'); $dados_NFe['CPF'] = XML_BuscaTag($xml,'CPF'); $dados_NFe['xNome'] = XML_BuscaTag($xml,'xNome'); $dados_NFe['IE'] = XML_BuscaTag($xml,'IE'); $dados_NFe['dEmi'] = XML_BuscaTag($xml,'dhEmi'); $dados_NFe['tpNF'] = XML_BuscaTag($xml,'tpNF'); $dados_NFe['vNF'] = XML_BuscaTag($xml,'vNF'); $dados_NFe['cSitNFe']= XML_BuscaTag($xml,'cSitNFe'); $ok_ins = true; }else if (($tipoZip[0]=='resEvento')||($tipoZip[0]=='procEventoNFe')){ //evento vinculado a NF-e $arquivo.= '-eve.xml'; $dados_NFe['chNFe'] = XML_BuscaTag($xml,'chNFe'); $dados_NFe['cSitNFe']= XML_BuscaTag($xml,'tpEvento'); //cancalamento 110111 //print_r($dados_NFe); $updt = ''; if ($dados_NFe['cSitNFe']=='110111'){ $updt = ' NFe_Situacao="C" '; }else if ($dados_NFe['cSitNFe']=='210210'){ $updt = ' Evento_Situacao="I",'. ' Evento_Ciencia="S" '; }else if ($dados_NFe['cSitNFe']=='210200'){ $updt = ' Evento_Situacao="C",'. ' Evento_Confirmacao="S" '; }else if ($dados_NFe['cSitNFe']=='210220'){ $updt = ' Evento_Situacao="D",'. ' Evento_Desconhecida="S" '; }else if ($dados_NFe['cSitNFe']=='210240'){ $updt = ' Evento_Situacao="N",'. ' Evento_NaoRealizada="S" '; } if ($updt!=''){ $res_ins = nota_fiscal_busca_nsu($_SESSION['Empresa_Codigo'],$dados_NFe['chNFe']); if ($res_ins!=0){ $con_ins = 'Update nota_fiscal_manifestacao set '. $updt. ' where Dominio="'.$_SESSION['Dominio'].'" '. ' and Empresa="'.$_SESSION['Empresa_Codigo'].'" '. ' and NSU="'.$res_ins.'"'; consulta_sql($con_ins); } } } //echo ''; $dados_NFe['arquivo'] = $arquivo; if ($ok_ins){ $cnpj = $dados_NFe['CNPJ']; if ($cnpj==''){ $cnpj = $dados_NFe['CPF']; } $cnpj = mcpf($cnpj); $serie = ((substr($dados_NFe['chNFe'],22,3)+1)-1); $nr_doc = substr($dados_NFe['chNFe'],25,9); $situacao = 'F'; if ( $dados_NFe['cSitNFe']==2){ $situacao = 'D'; }else if ( $dados_NFe['cSitNFe']==3){ $situacao = 'C'; }else if ( $dados_NFe['cSitNFe']==4){ $situacao = 'E'; } $res_ins = nota_fiscal_busca_nsu($_SESSION['Empresa_Codigo'],$dados_NFe['chNFe']); nota_fiscal_manifetacao_insere( $_SESSION['Empresa_Codigo'],$dados_NFe[' NSU'],$dados_NFe['chNFe'], $dados_NFe['tpNF'],'55',$serie,$nr_doc, $cnpj,UpperDados($dados_NFe['xNome']),UpperDados($dados_NFe['IE']), $dados_NFe['vNF'],$dados_NFe['dEmi'],$situacao, '',''); $st_nf = ''; if ($res_ins!=0){ $st_nf = ' (Já Escriturado)'; } echo '
NF-e: '.$dados_NFe['chNFe'].' de '.dataf($dados_NFe['dEmi']).$st_nf.'
'; } //print_r($dados_NFe); //echo '
'; } //é doczip }//for dcozip }//é lote }//for lote }//status 138 $continua = ($ult_nsu!=$max_nsu); if (($status=='137')||($status=='138')){ if ($continua=='1'){ echo '
A SEFAZ não consultou a totalidade das operações! Ainda existem mais NF-es na base de dados que não foram consultadas!
Fazendo nova consulta para localizar as próximas operações!
'; $repetir = true; }else{ echo '
A SEFAZ já consultou a totalidade das operações! NÃO existem mais NF-es na base de dados a serem consultadas!
Aguarde no mínimo 1 hora antes de efetuar a consulta novamente!
'; } } if ($ult_nsu>0){ $con_ins = 'Insert into nota_fiscal_manifestacao '. '(Dominio, Empresa, NSU, Evento_Situacao) '. ' values ('. '"'.$_SESSION['Dominio'].'", '. '"'.$_SESSION['Empresa_Codigo'].'", '. '"-1", '. '"E")'; consulta_sql($con_ins); $con_ins = 'Update nota_fiscal_manifestacao set '. ' NFe_Chave="'.$ult_nsu.'" '. ' where Dominio="'.$_SESSION['Dominio'].'" '. ' and Empresa="'.$_SESSION['Empresa_Codigo'].'" '. ' and NSU=-1'; consulta_sql($con_ins); } nfe_copia_arquivo('retorno','SEFAZ/Consultas/'.$ano_mes,$cnpj_empresa.'-dist-dfe.xml','',true); }else if (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-con-dist-dfe.err')){ $conteudo_arquivo = nfe_abre_arquivo_err($cnpj_empresa.'-ret-cons-nfe-dest.err'); echo '
Falha no Processamento do Arquivo "'.$cnpj_empresa.'-ret-con-dist-dfe.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$cnpj_empresa.'-ret-con-dist-dfe.err','',true); }else if (file_exists(nfe_pasta_raiz().'retorno/'.$cnpj_empresa.'-dist-dfe.err')){ $conteudo_arquivo = nfe_abre_arquivo_err($cnpj_empresa.'-dist-dfe.err'); echo '
Falha no Processamento do Arquivo "'.$cnpj_empresa.'-dist-dfe.err"!'. $conteudo_arquivo.'
'; nfe_copia_arquivo('retorno','erros/'.$ano_mes,$cnpj_empresa.'-dist-dfe.err','',true); } }else{ sleep(1); } } if ($repetir){ if ($tentativa<90){ //php não aceita fazer mais de 100 vezes a função recursiva echo '
'; nfe_manifestacao_consulta($tentativa+1); }else{ echo '
Limite de tentativas consecutivas atingido! Aguarde 1 minuto e efetue a consulta novamente!
'; } } //echo 'Terminou'; } function nfe_manifestacao_manifesta($nsu, $manifesta_tipo, $data, $hora, $cod_cancela, $desc_cancela){ //consulta o corpo da mafifestação $con_man = 'select * from nota_fiscal_manifestacao '. ' where Dominio= "'.$_SESSION['Dominio'].'" '. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'" '. ' and NSU = "'.$nsu.'"'; $res_man = consulta_sql($con_man); $reg_man = consulta_ler_objeto($res_man); consulta_limpa($res_man); //consulta dados da empresa emitente $con_empresa = 'select CPF_CNPJ from pessoa'. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa = "'.$_SESSION['Empresa_Codigo'].'"'; $res_empresa = consulta_sql($con_empresa); $reg_empresa = consulta_ler_linha($res_empresa); consulta_limpa($res_empresa); $cnpj_empresa = limpa_numero($reg_empresa[0]); //consulta dados da empresa emitente $con_enderec = 'select Codigo_Cidade from pessoa_endereco '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Pessoa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and Situacao<>"E" '. ' order by Seq_Endereco'; $res_enderec = consulta_sql($con_enderec); $reg_enderec = consulta_ler_linha($res_enderec); consulta_limpa($res_enderec); //$cod_uf = substr($reg_enderec[0],0,2); $cod_uf = '91'; //$cod_uf = substr($reg_man->NFe_Chave,0,2); //consulta maior seq evento deste NSU $id_evento = ''; $tp_evento = ''; $desc_evento = ''; $campo = ''; if ($manifesta_tipo=='I'){ $tp_evento = '210210'; $desc_evento = 'Ciencia da Operacao'; $campo = 'Evento_Ciencia'; }else if ($manifesta_tipo=='C'){ $tp_evento = '210200'; $desc_evento = 'Confirmacao da Operacao'; $campo = 'Evento_Confirmacao'; }else if ($manifesta_tipo=='D'){ $tp_evento = '210220'; $desc_evento = 'Desconhecimento da Operacao'; $campo = 'Evento_Desconhecida'; }else if ($manifesta_tipo=='N'){ $tp_evento = '210240'; $desc_evento = 'Operacao nao Realizada'; $campo = 'Evento_NaoRealizada'; } //salva na tabela $id_evento = $tp_evento.$reg_man->NFe_Chave.'01';//manifestacao é sempre seq 1 $nome_arq_man2 = $reg_man->NFe_Chave.'_'.$tp_evento.'_01';//manifestacao é sempre seq 1 $versao_evento = config_pad('conf_versao'); $nome_arq_man = $id_evento; $ambiente = nfe_busca_ambiente_evento(); $con_nsu = 'select Seq_Evento, Tipo, Situacao from nota_fiscal_manifestacao_evento '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and NSU="'.$nsu.'"'. ' order by Seq_Evento desc'. ' limit 1'; $res_nsu = consulta_sql($con_nsu); $reg_nsu = consulta_ler_linha($res_nsu); consulta_limpa($res_nsu); $seq_evento = $reg_nsu[0]; $ok = true; $existe = false; if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.xml')){ //só vai gerar consulta se não teve retorno até agora $con_nsu = 'select Seq_Evento, Tipo, Situacao from nota_fiscal_manifestacao_evento '. ' where Dominio = "'.$_SESSION['Dominio'].'"'. ' and Empresa = "'.$_SESSION['Empresa_Codigo'].'"'. ' and NSU="'.$nsu.'"'. ' and Tipo="'.$manifesta_tipo.'"'. ' order by Seq_Evento desc'. ' limit 1'; $res_nsu = consulta_sql($con_nsu); $reg_nsu = consulta_ler_linha($res_nsu); consulta_limpa($res_nsu); if ($reg_nsu[0]>0){ $seq_evento = $reg_nsu[0]; $existe = true; } } if (!($existe)){ $seq_evento++; $ins_evento = 'INSERT INTO nota_fiscal_manifestacao_evento '. '(Dominio, Empresa, NSU, Seq_Evento, Nr_Nota, '. ' Tipo, DH_Evento, Versao_Evento, Id_Evento, '. ' Cod_Orgao, Evento_Situacao, Situacao, '. ' Evento_Motivo_Codigo, Evento_Motivo ) VALUES ('. ' "'.$_SESSION['Dominio'].'", '. ' "'.$_SESSION['Empresa_Codigo'].'", '. ' "'.$nsu.'", '. ' "'.$seq_evento.'", '. ' "'.$reg_man->Nr_Nota.'", '. ' "'.$manifesta_tipo.'", '. ' "'.$data.' '.$hora.'", '. ' "'.$versao_evento.'", '. ' "'.$id_evento.'", '. ' "'.$cod_uf.'", '. ' "", '. ' "E", '. ' "'.$cod_cancela.'", '. ' "'.$desc_cancela.'" )'; consulta_sql($ins_evento); } $nr_lote = 1; //gera arquivo if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.err')){ unlink(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.err'); } if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-env-manif.err')){ unlink(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-env-manif.err'); } if (!(file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.xml'))){ $xml = new XML(); //adiciona dados da nota $env_evento = &$xml->createRoot("envEvento"); $env_evento->addAttribute('versao', $versao_evento, true); $env_evento->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $env_evento->addAttribute('idLote', $nr_lote , false); $e_evento = &$env_evento->addChild("evento"); //$e_evento = &$xml->createRoot("evento"); $e_evento->addAttribute('versao', $versao_evento, true); // $e_evento->addAttribute('xmlns', 'http://www.portalfiscal.inf.br/nfe' , true); $inf_evento = &$e_evento->addChild("infEvento"); $inf_evento->addAttribute('Id', 'ID'.$id_evento, True); $inf_evento->addAttribute('cOrgao', $cod_uf , false); $inf_evento->addAttribute('tpAmb', $ambiente , false); $inf_evento->addAttribute('CNPJ', $cnpj_empresa , false); $inf_evento->addAttribute('chNFe', $reg_man->NFe_Chave , false); //$dif_UTC = '-03:00'; /*$ver_php = phpversion(); if ($ver_php[0]!='4'){ date_default_timezone_set('America/Sao_Paulo'); //só faz isso no php 5 } */ /*$dif_UTC = date('O', mktime( 12, 00 , 00 , substr($data.' '.$hora,5,2) , substr($data.' '.$hora,8,2) , substr($data.' '.$hora,0,4) ) ); //$dif_UTC = '-2000'; // 01234 $dif_UTC = substr($dif_UTC,0,3).':'.substr($dif_UTC,3,2); */ $uf = substr($reg_man->NFe_Chave,0,2); $dif_UTC = calcula_horario_verao($data,$uf); $inf_evento->addAttribute('dhEvento', $data.'T'.$hora.$dif_UTC , false); $inf_evento->addAttribute('tpEvento', $tp_evento , false); $inf_evento->addAttribute('nSeqEvento', 1 , false); $inf_evento->addAttribute('verEvento', $versao_evento , false); $det_evento = &$inf_evento->addChild("detEvento"); $det_evento->addAttribute('versao', $versao_evento, true); $det_evento->addAttribute('descEvento', $desc_evento , false); if ($manifesta_tipo=='N'){ $det_evento->addAttribute('xJust', $desc_cancela , false); } $xml->toFile(nfe_pasta_raiz().'tmp/', $nome_arq_man.'-env-manif.xml'); $ok = nfe_copia_arquivo('tmp','envio',$nome_arq_man.'-env-manif.xml','',false); }else{ $ok = true; } //consulta arquivo de retorno if ($ok){ $ok = false; $ano_mes = nfe_ano_mes($reg_man->DT_Emissao); sleep(5); //echo $cnpj_empresa.'-ret-cons-nfe-dest.xml'; flush(); @ob_flush(); flush(); @ob_flush(); while (!($ok)){ set_time_limit(30); if ((file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.xml'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.err'))|| (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-env-manif.err'))){ $ok = true; sleep(5); if (file_exists(nfe_pasta_raiz().'retorno/'.$nome_arq_man.'-ret-env-manif.xml')){ $status = ''; $motivo = ''; $ult_nsu = 0; $continua = 0; $xml = new XML(); $xml->fromFile(nfe_pasta_raiz().'retorno/', $nome_arq_man.'-ret-env-manif.xml', true); //le nr do lote no arquivo if ($xml->root->name == 'retEnvEvento'){ foreach($xml->root->atts as $key => $value){ if ($xml->root->atts[$key]->name == 'cStat'){ $status = $xml->root->atts[$key]->value; } if ($xml->root->atts[$key]->name == 'xMotivo'){ $motivo = $xml->root->atts[$key]->value; } } } echo '
'.$status.'-'.$motivo.'
'; if ($status=='128'){ //se tem documentos no arquivo processa eles foreach($xml->root->childs as $key => $value){ if ($xml->root->childs[$key]->name== 'retEvento'){ //$txt_inf_prot = $xml->root->childs[$key]->toString(); $ret = &$xml->root->childs[$key]; foreach($ret->childs as $key2 => $value2){ if ($ret->childs[$key2]->name== 'infEvento'){ $res_nfe = &$ret->childs[$key2]; $dados_NFe['tpAmb'] =''; $dados_NFe['verAplic'] =''; $dados_NFe['cStat'] =''; $dados_NFe['xMotivo'] =''; $dados_NFe['dhRegEvento'] =''; $dados_NFe['nProt'] =''; //echo '