Schema
Utilize nossa biblioteca criada em C# para gerar um arquivo XML que represente uma Nota Fiscal Eletrônica. RDI.NFe2.Schema.dll já está revisada com campos acrescentados pela Reforma Tributária.
Como funciona?
Baixe a biblioteca
Escolha a biblioteca de acordo com a versão de .NET que seu projeto utiliza.
Adicione ao projeto
Como você faria com qualquer outra biblioteca.
Gere o XML
Utilize o código abaixo para gerar sua NFe.
Exemplo de uso da Biblioteca
Observe a seguir um exemplo de código fonte em C# já utilizando campos da Reforma Tributária como IBS e CBS. O método a ser chamado é ObterXMLNFe, enviando um objeto que represente uma Nota de Produto. A classe NotaProduto representa uma estrutura montada pelo seu ERP e que possua emitente, destinatário, itens da nota, endereço de entrega, enfim, um Nota Fiscal de Produtos. Os enums TipoPessoa, TipoEntradaSaida, TipoFinalidade, TipoModalidadeFrete, TipoMeioPagamento, TipoFormaPgto, CST e CSOSNICMS são sugeridos ao final do código. Modifique o código de acordo com a realidade do seu software.
using RDI.NFe2.SchemaXML.NFe_v400;
using RDI.NFe2.SchemaXML;
...
public static string ObterXMLNFe(NotaProduto notaProduto)
{
var nfe = ObterNFe(notaProduto);
var stXML = XMLUtils.GetXML(nfe, VersaoXML.NFe_v400);
return stXML;
}
public static string DvBase11(string Numero)
{
try
{
int num = 2;
int num2 = 0;
for (int num3 = Numero.Length - 1; num3 >= 0; num3--)
{
num2 += int.Parse(Numero[num3].ToString()) * num;
num++;
if (num > 9)
{
num = 2;
}
}
num2 %= 11;
if (num2 > 1)
{
return (11 - num2).ToString();
}
return "0";
}
catch (Exception ex)
{
throw new Exception("Erro na geração da chave de acesso." + ex.Message);
}
}
public static TUfEmi StringToUFEmi(string siglaEstado)
{
var ufs = Enum.GetValues(typeof(TUfEmi));
foreach(TUfEmi uf in ufs)
{
if (uf.ToString() == siglaEstado.ToUpper())
return uf;
}
throw new Exception("Sigla de Estado inválida: " + siglaEstado);
}
public static TUf StringToUF(string siglaEstado)
{
var ufs = Enum.GetValues(typeof(TUf));
foreach (TUf uf in ufs)
{
if (uf.ToString() == siglaEstado.ToUpper())
return uf;
}
throw new Exception("Sigla de Estado inválida: " + siglaEstado);
}
public static string DecimalToString(Decimal valor)
{
return valor.ToString("N2").Replace(".", "").Replace(',', '.');
}
// Sugestão de enums para o seu ERP:
/* public enum TipoPessoa
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "Física", value = "F")]
Fisica,
[EnumeratedItemInfo(description = "Jurídica", value = "J")]
Juridica
}
public enum TipoFinalidade
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "Normal", value = "1")]
Normal,
[EnumeratedItemInfo(description = "NFe Complementar", value = "2")]
NFeComplementar,
[EnumeratedItemInfo(description = "NFe Ajuste", value = "3")]
NFeAjuste,
[EnumeratedItemInfo(description = "Devolução", value = "4")]
Devolucao,
}
public enum TipoFormaPgto
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "À Vista", value = "0")]
AVista,
[EnumeratedItemInfo(description = "À Prazo", value = "1")]
APrazo,
[EnumeratedItemInfo(description = "Outros", value = "2")]
Outros,
}
public enum TipoMeioPagamento
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "Dinheiro", value = "D")]
Dinheiro,
[EnumeratedItemInfo(description = "Cheque", value = "C")]
Cheque,
[EnumeratedItemInfo(description = "Cartão de Crédito", value = "3")]
CartaoCredito,
[EnumeratedItemInfo(description = "Cartão de Débito", value = "4")]
CartaoDebito,
[EnumeratedItemInfo(description = "Crédito Loja", value = "L")]
CreditoLoja,
[EnumeratedItemInfo(description = "Vale Alimentação", value = "A")]
ValeAlimentacao,
[EnumeratedItemInfo(description = "Vale Refeição", value = "R")]
ValeRefeicao,
[EnumeratedItemInfo(description = "Vale Presente", value = "P")]
ValePresente,
[EnumeratedItemInfo(description = "Vale Combustível", value = "X")]
ValeCombustivel,
[EnumeratedItemInfo(description = "Duplicata Mercantil", value = "M")]
DuplicataMercantil,
[EnumeratedItemInfo(description = "Boleto Bancário", value = "B")]
BoletoBancario,
[EnumeratedItemInfo(description = "Depósito Bancário", value = "5")]
DepositoBancario,
[EnumeratedItemInfo(description = "Pagamento Instantâneo (PIX)", value = "6")]
PIX,
[EnumeratedItemInfo(description = "Transferência bancária, Carteira Digital", value = "7")]
TransferenciaBancaria,
[EnumeratedItemInfo(description = "Programa de fidelidade, Cashback, Crédito Virtual", value = "8")]
Cashback,
[EnumeratedItemInfo(description = "Sem pagamento", value = "S")]
SemPagamento,
[EnumeratedItemInfo(description = "Outros", value = "O")]
Outros
}
public enum TipoEntradaSaida
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "Entrada", value = "E")]
Entrada,
[EnumeratedItemInfo(description = "Saída", value = "S")]
Saida,
[EnumeratedItemInfo(description = "Estorno-Entrada", value = "N")]
EstornoEntrada,
[EnumeratedItemInfo(description = "Estorno-Saída", value = "A")]
EstornoSaida
}
public enum CST
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "000 - Tributação integral", value = "A")]
Item000,
[EnumeratedItemInfo(description = "010 - Tributação com alíquotas uniformes", value = "B")]
Item010,
[EnumeratedItemInfo(description = "011 - Tributação com alíquotas uniformes reduzidas", value = "C")]
Item011,
[EnumeratedItemInfo(description = "200 - Alíquota reduzida", value = "D")]
Item200,
[EnumeratedItemInfo(description = "220 - Alíquota fixa", value = "E")]
Item220,
[EnumeratedItemInfo(description = "221 - Alíquota fixa proporcional", value = "F")]
Item221,
[EnumeratedItemInfo(description = "222 - Redução de Base de Cálculo", value = "G")]
Item222,
[EnumeratedItemInfo(description = "400 - Isenção", value = "H")]
Item400,
[EnumeratedItemInfo(description = "410 - Imunidade e não incidência", value = "I")]
Item410,
[EnumeratedItemInfo(description = "510 - Diferimento", value = "J")]
Item510,
[EnumeratedItemInfo(description = "515 - Diferimento com redução de alíquota", value = "K")]
Item515,
[EnumeratedItemInfo(description = "550 - Suspensão", value = "L")]
Item550,
[EnumeratedItemInfo(description = "620 - Tributação Monofásica", value = "M")]
Item620,
[EnumeratedItemInfo(description = "800 - Transferência de crédito", value = "N")]
Item800,
[EnumeratedItemInfo(description = "810 - Ajuste de IBS na ZFM", value = "O")]
Item810,
[EnumeratedItemInfo(description = "811 - Ajustes", value = "P")]
Item811,
[EnumeratedItemInfo(description = "820 - Tributação em declaração de regime específico", value = "Q")]
Item820,
[EnumeratedItemInfo(description = "830 - Exclusão da Base de Cálculo", value = "R")]
Item830,
}
public enum CSOSNICMS
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "SIMPLES: 101 - Tributada pelo Simples Nacional com permissão de crédito", value = "A")]
ItemSIMPLES101,
[EnumeratedItemInfo(description = "SIMPLES: 102 - Tributada pelo Simples Nacional sem permissão de crédito", value = "B")]
ItemSIMPLES102,
[EnumeratedItemInfo(description = "SIMPLES: 103 - Isenção do ICMS no Simples Nacional para faixa de receita bruta", value = "C")]
ItemSIMPLES103,
[EnumeratedItemInfo(description = "SIMPLES: 300 - Imune", value = "D")]
ItemSIMPLES300,
[EnumeratedItemInfo(description = "SIMPLES: 400 - Não tributada pelo Simples Nacional", value = "E")]
ItemSIMPLES400,
[EnumeratedItemInfo(description = "SIMPLES: 201 -Tributada pelo Simples Nacional com permissão de crédito e com cobrança do ICMS por Substituição Tributária", value = "F")]
ItemSIMPLES201,
[EnumeratedItemInfo(description = "SIMPLES: 202 - Tributada pelo Simples Nacional sem permissão de crédito e com cobrança do ICMS por Substituição Tributária", value = "G")]
ItemSIMPLES202,
[EnumeratedItemInfo(description = "SIMPLES: 203 - Isenção do ICMS nos Simples Nacional para faixa de receita bruta e com cobrança do ICMS por Substituição Tributária", value = "H")]
ItemSIMPLES203,
[EnumeratedItemInfo(description = "SIMPLES: 500 - ICMS cobrado anteriormente por substituição tributária (substituído) ou por antecipação", value = "I")]
ItemSIMPLES500,
[EnumeratedItemInfo(description = "SIMPLES: 900 - Outros", value = "J")]
ItemSIMPLES900,
}
public enum TipoModalidadeFrete
{
[EnumeratedItemInfo(description = "", value = "")]
Vazio,
[EnumeratedItemInfo(description = "Por conta do Emitente", value = "0")]
Emitente,
[EnumeratedItemInfo(description = "Por conta do Destinatário/Remetente", value = "1")]
Remetente,
[EnumeratedItemInfo(description = "Por conta de Terceiros", value = "2")]
Terceiros,
[EnumeratedItemInfo(description = "Sem Frete", value = "9")]
SemFrete,
}
*/
//Considere a seguir que NotaProduto seja um DTO representando uma Nota Fiscal de Produto
public static TNFe ObterNFe(NotaProduto np)
{
//Dados da nota
var oNotaXML = new TNFe();
oNotaXML.infNFe = new TNFeInfNFe();
oNotaXML.infNFe.ide = new TNFeInfNFeIde();
oNotaXML.infNFe.ide.cUF = (TCodUfIBGE)np.uf.codigoIBGE;
if (!String.IsNullOrWhiteSpace(np.naturezaOperacao))
if (np.naturezaOperacao.Length > 60)
throw new Exception("Natureza da Operação deve possuir no máximo 60 caracteres.");
oNotaXML.infNFe.ide.natOp = np.naturezaOperacao;
oNotaXML.infNFe.ide.indPres = TNFeInfNFeIdeIndPres_v400.Item1;
// nota referenciada, usada em processos de devolução
if (!String.IsNullOrEmpty(np.chaveNotaReferenciada))
{
if (oNotaXML.infNFe.ide.NFref == null)
{
oNotaXML.infNFe.ide.NFref = new TNFeInfNFeIdeNFref[1];
oNotaXML.infNFe.ide.NFref[0] = new TNFeInfNFeIdeNFref();
((TNFeInfNFeIdeNFref)oNotaXML.infNFe.ide.NFref[0]).Item = np.chaveNotaReferenciada;
((TNFeInfNFeIdeNFref)oNotaXML.infNFe.ide.NFref[0]).ItemElementName = ITCTypeRefNF.refNFe;
}
}
oNotaXML.infNFe.pag = new TNFeInfNFePag();
oNotaXML.infNFe.pag.detPag = new TNFeInfNFePagDetPag[1];
oNotaXML.infNFe.pag.detPag[0] = new TNFeInfNFePagDetPag();
oNotaXML.infNFe.pag.detPag[0].indPagSpecified = true;
switch (np.tipoFormaPagamento)
{
case TipoFormaPgto.APrazo:
{
oNotaXML.infNFe.pag.detPag[0].indPagSpecified = true;
oNotaXML.infNFe.pag.detPag[0].indPag = TIndPag_v400.APrazo;
break;
}
case TipoFormaPgto.AVista:
{
oNotaXML.infNFe.pag.detPag[0].indPagSpecified = true;
oNotaXML.infNFe.pag.detPag[0].indPag = TIndPag_v400.AVista;
break;
}
case TipoFormaPgto.Outros:
{
oNotaXML.infNFe.pag.detPag[0].indPagSpecified = false;
break;
}
default:
throw new Exception("Tipo de forma de pagamento inválido para NFe v4.0. Favor conferir.");
}
switch (np.tipoMeioPagamento)
{
case TipoMeioPagamento.Dinheiro:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item01;
break;
}
case TipoMeioPagamento.Cheque:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item02;
break;
}
case TipoMeioPagamento.CartaoCredito:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item03;
break;
}
case TipoMeioPagamento.CartaoDebito:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item04;
break;
}
case TipoMeioPagamento.CreditoLoja:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item05;
break;
}
case TipoMeioPagamento.ValeAlimentacao:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item10;
break;
}
case TipoMeioPagamento.ValeRefeicao:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item11;
break;
}
case TipoMeioPagamento.ValePresente:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item12;
break;
}
case TipoMeioPagamento.ValeCombustivel:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item13;
break;
}
case TipoMeioPagamento.DuplicataMercantil:
{
throw new Exception("Meio de pagamento 'Duplicata Mercantil' é inválido para NFe v4.0.");
break;
}
case TipoMeioPagamento.BoletoBancario:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item15;
break;
}
case TipoMeioPagamento.DepositoBancario:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item16;
break;
}
case TipoMeioPagamento.PIX:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item17;
break;
}
case TipoMeioPagamento.TransferenciaBancaria:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item18;
break;
}
case TipoMeioPagamento.Cashback:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item19;
break;
}
case TipoMeioPagamento.SemPagamento:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item90;
break;
}
case TipoMeioPagamento.Outros:
{
oNotaXML.infNFe.pag.detPag[0].tPag = TNFeInfNFePagDetPagTPag.Item99;
oNotaXML.infNFe.pag.detPag[0].xPag = "Outros";
break;
}
}
oNotaXML.infNFe.ide.dhEmi = np.dataEmissao.ToString("yyyy-MM-ddTHH:mm:sszzzz");
if (np.paisDestinatario.codigoBACEN == 1058) // Brasil
{
if (np.uf.UFeSigla == np.estadoDestinatario.UFeSigla)
oNotaXML.infNFe.ide.idDest = TNFeInfNFeIdeIdDest.OperacaoInterna;
else
oNotaXML.infNFe.ide.idDest = TNFeInfNFeIdeIdDest.OperacaoInterestadual;
}
else
oNotaXML.infNFe.ide.idDest = TNFeInfNFeIdeIdDest.OperacaoExterior;
oNotaXML.infNFe.ide.cMunFG = np.cidadeEmit.codigoIBGE.ToString();
oNotaXML.infNFe.ide.tpImp = TNFeInfNFeIdeTpImp.Item1;
oNotaXML.infNFe.ide.tpAmb = np.producao ? TAmb.Producao : TAmb.Homologacao;
switch (np.finalidade)
{
case TipoFinalidade.Normal:
{
oNotaXML.infNFe.ide.finNFe = TFinNFe_v310_v400.Normal;
break;
}
case TipoFinalidade.Devolucao:
{
oNotaXML.infNFe.ide.finNFe = TFinNFe_v310_v400.Devolucao;
break;
}
case TipoFinalidade.NFeAjuste:
{
oNotaXML.infNFe.ide.finNFe = TFinNFe_v310_v400.NFeAjuste;
break;
}
case TipoFinalidade.NFeComplementar:
{
oNotaXML.infNFe.ide.finNFe = TFinNFe_v310_v400.NFeComplementar;
break;
}
default:
{
throw new Exception("Finalidade não compatível com NFe 4.0. Favor conferir.");
}
}
oNotaXML.infNFe.ide.indPres = 0;
oNotaXML.infNFe.ide.verProc = "SISTEMA.v1.1.1";
if (np.tipo == TipoEntradaSaida.Entrada)
oNotaXML.infNFe.ide.tpNF = TNFeInfNFeIdeTpNF.Entrada;
else
oNotaXML.infNFe.ide.tpNF = TNFeInfNFeIdeTpNF.Saida;
oNotaXML.infNFe.emit = new TNFeInfNFeEmit();
oNotaXML.infNFe.emit.ItemElementName = ITCTypeCNPJCPF.CNPJ;
oNotaXML.infNFe.emit.Item = np.documentoEmitente;
oNotaXML.infNFe.emit.xNome = np.nomeEmitente;
oNotaXML.infNFe.emit.IE = np.inscricaoEstadualEmitente
.Replace(".", "").Replace(" ", "").Replace("-", "");
oNotaXML.infNFe.emit.CRT = TNFeInfNFeEmitCRT.Item1;
oNotaXML.infNFe.emit.enderEmit = new TEnderEmi();
oNotaXML.infNFe.emit.enderEmit.xLgr = np.logradouroEndEmitente;
oNotaXML.infNFe.emit.enderEmit.nro = np.numeroEndEmitente;
oNotaXML.infNFe.emit.enderEmit.xCpl = np.complementoEndEmitente;
oNotaXML.infNFe.emit.enderEmit.xBairro = np.bairroEndEmitente;
oNotaXML.infNFe.emit.enderEmit.cMun = np.cidadeEmit.codigoIBGE.ToString();
oNotaXML.infNFe.emit.enderEmit.xMun = np.cidadeEmit.nome;
oNotaXML.infNFe.emit.enderEmit.UF = StringToUFEmi(np.uf.UFeSigla);
oNotaXML.infNFe.emit.enderEmit.CEP = np.cepEndEmitente.Replace("-", "").Replace(" ", "");
oNotaXML.infNFe.emit.enderEmit.cPais = TEnderEmiCPais.Item1058; // Brasil
oNotaXML.infNFe.emit.enderEmit.xPais = TEnderEmiXPais.BRASIL;
oNotaXML.infNFe.emit.enderEmit.fone = np.telefoneEmitente
.Replace("-", "").Replace(" ", "")
.Replace("(", "").Replace(")", "");
oNotaXML.infNFe.dest = new TNFeInfNFeDest();
TipoPessoa tipoDocumentoDestinatario = TipoPessoa.Vazio;
if (np.pessoa != null)
tipoDocumentoDestinatario = np.pessoa.tipoPessoa;
else
tipoDocumentoDestinatario = np.tipoDocumentoDestinatario;
if (tipoDocumentoDestinatario == TipoPessoa.Vazio)
throw new Exception("Tipo de Documento do Destinatário não foi encontrado.");
var exportacao = false;
if (tipoDocumentoDestinatario == TipoPessoa.Fisica)
oNotaXML.infNFe.dest.ItemElementName = ITCTypeCNPJCPFIdEstrangeiro.CPF;
else if (tipoDocumentoDestinatario == TipoPessoa.Juridica)
{
if (np.oPaisDestinatario.codigoBACEN == 1058) // Brasil
oNotaXML.infNFe.dest.ItemElementName = ITCTypeCNPJCPFIdEstrangeiro.CNPJ;
else // Exterior
{
exportacao = true;
oNotaXML.infNFe.dest.ItemElementName = ITCTypeCNPJCPFIdEstrangeiro.idEstrangeiro;
}
}
oNotaXML.infNFe.dest.Item = np.documentoDestinatario;
string nomeDest = np.nomeDestinatario;
if (nomeDest.Length > 60)
nomeDest = nomeDest.Substring(0, 60);
if (np.producao)
oNotaXML.infNFe.dest.xNome = nomeDest.Trim();
else
oNotaXML.infNFe.dest.xNome = "NF-E EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";
//9 = Não Contribuinte, que pode ou não possuir Inscrição Estadual no Cadastro de Contribuintes
if (string.IsNullOrEmpty(np.inscricaoEstadualDestinatario))
{
oNotaXML.infNFe.dest.indIEDest = TNFeInfNFeDestIndIEDest.Item9;
oNotaXML.infNFe.ide.indFinal = TNFeInfNFeIdeIndFinal.ConsumidorFinal;
}
//2 = Contribuinte isento de Inscrição no cadastro de Contribuintes do ICMS;
else if (np.inscricaoEstadualDestinatario.ToUpper() == "ISENTO")
{
oNotaXML.infNFe.ide.indFinal = TNFeInfNFeIdeIndFinal.ConsumidorFinal;
oNotaXML.infNFe.dest.indIEDest = TNFeInfNFeDestIndIEDest.Item2;
}
//1 = Contribuinte ICMS(informar a IE do destinatário);
else
{
oNotaXML.infNFe.ide.indFinal = TNFeInfNFeIdeIndFinal.Normal;
oNotaXML.infNFe.dest.IE = np.inscricaoEstadualDestinatario
.Replace(".", "").Replace(" ", "").Replace("-", "");
oNotaXML.infNFe.dest.indIEDest = TNFeInfNFeDestIndIEDest.Item1;
}
if (!string.IsNullOrEmpty(np.emailDestinatario))
{
var emailDestinatario = np.emailDestinatario.Trim();
if (emailDestinatario.Length > 60)
throw new Exception("E-mail do Destinatário supera 60 caracteres.");
oNotaXML.infNFe.dest.email = emailDestinatario;
}
oNotaXML.infNFe.dest.enderDest = new TEndereco();
oNotaXML.infNFe.dest.enderDest.xLgr = np.logradouroEndDestinatario;
oNotaXML.infNFe.dest.enderDest.nro = np.numeroEndDestinatario;
oNotaXML.infNFe.dest.enderDest.xBairro = np.bairroEndDestinatario;
oNotaXML.infNFe.dest.enderDest.xCpl = np.complementoEndDestinatario;
if (np.cidadeDestinatario == null)
throw new Exception("Cidade do Destinatário não informada.");
oNotaXML.infNFe.dest.enderDest.cMun = np.cidadeDestinatario.codigoIBGE.ToString();
oNotaXML.infNFe.dest.enderDest.xMun = np.cidadeDestinatario.nome;
if (np.estadoDestinatario == null)
throw new Exception("Estado do Destinatário não informado.");
oNotaXML.infNFe.dest.enderDest.UF = StringToUF(np.estadoDestinatario.UFeSigla);
oNotaXML.infNFe.dest.enderDest.CEP = np.cepEndDestinatario
.Replace("-", "").Replace(" ", "").Replace(".", "");
if (np.paisDestinatario == null)
throw new Exception("País do Destinatário não informado.");
oNotaXML.infNFe.dest.enderDest.cPais = np.paisDestinatario.codigoBACEN.ToString();
oNotaXML.infNFe.dest.enderDest.xPais = np.paisDestinatario.nome;
if (!string.IsNullOrEmpty(np.telefoneDestinatario))
oNotaXML.infNFe.dest.enderDest.fone = np.telefoneDestinatario
.Replace("-", "").Replace(" ", "")
.Replace("(", "").Replace(")", "");
var i = 0;
oNotaXML.infNFe.det = new TNFeInfNFeDet[np.itens.Count];
decimal totalIPIDevolucao = np.itens.Sum(x => x.valorIPIDevolucao);
string strVIPIDEV = DecimalToString(totalIPIDevolucao);
bool devolverIPI = totalIPIDevolucao > 0;
foreach (var item in np.itens)
{
oNotaXML.infNFe.det[i] = new TNFeInfNFeDet();
oNotaXML.infNFe.det[i].nItem = (i + 1).ToString();
oNotaXML.infNFe.det[i].prod = new TNFeInfNFeDetProd();
oNotaXML.infNFe.det[i].prod.cProd = item.produto.codigo.ToString();
oNotaXML.infNFe.det[i].prod.cEAN = "SEM GTIN";
if (item.descricaoProduto.Length > 120)
throw new Exception("Descrição do Produto supera 120 caracteres.");
oNotaXML.infNFe.det[i].prod.xProd = item.descricaoProduto;
oNotaXML.infNFe.det[i].prod.NCM = item.ncm;
oNotaXML.infNFe.det[i].prod.CFOP = item.CFOP.ToString();
oNotaXML.infNFe.det[i].prod.uCom = item.unidade;
oNotaXML.infNFe.det[i].prod.cEANTrib = "SEM GTIN";
oNotaXML.infNFe.det[i].prod.uTrib = item.unidade;
oNotaXML.infNFe.det[i].prod.qCom = item.quantidade.ToString("N4")
.Replace(".", "").Replace(',', '.');
oNotaXML.infNFe.det[i].prod.qTrib = item.quantidade.ToString("N4")
.Replace(".", "").Replace(',', '.');
oNotaXML.infNFe.det[i].prod.vUnCom = item.valorUnitario.ToString("N10")
.Replace(".", "").Replace(',', '.');
oNotaXML.infNFe.det[i].prod.vUnTrib = item.valorUnitario.ToString("N10")
.Replace(".", "").Replace(',', '.');
oNotaXML.infNFe.det[i].prod.vProd = DecimalToString(item.quantidade * item.valorUnitario);
if (item.valorDesconto > 0)
oNotaXML.infNFe.det[i].prod.vDesc = DecimalToString(item.valorDesconto);
if (item.valorFrete > 0)
oNotaXML.infNFe.det[i].prod.vFrete = DecimalToString(item.valorFrete);
oNotaXML.infNFe.det[i].prod.indTot = TNFeInfNFeDetProdIndTot.Item1;
if (!String.IsNullOrEmpty(item.numeroPedidoCompra))
{
if (item.numeroPedidoCompra.Length > 15)
throw new Exception("Número Pedido Compra do Produto supera 15 caracteres.");
oNotaXML.infNFe.det[i].prod.xPed = item.numeroPedidoCompra;
}
if (!String.IsNullOrEmpty(item.itemPedidoCompra))
{
if (item.itemPedidoCompra.Length > 6)
throw new Exception("Item Pedido Compra do Produto supera 6 caracteres.");
oNotaXML.infNFe.det[i].prod.nItemPed = item.itemPedidoCompra;
}
oNotaXML.infNFe.det[i].imposto = new TNFeInfNFeDetImposto();
string vBCPIS = DecimalToString(item.bcPIS);
string pPIS = DecimalToString(item.percPIS);
string vPIS = DecimalToString(item.valorPIS);
string vBCCOFINS = DecimalToString(item.bcCOFINS);
string pCOFINS = DecimalToString(item.percCOFINS);
string vCOFINS = DecimalToString(item.valorCOFINS);
string vBCICMS = DecimalToString(item.bcICMS);
string pICMS = DecimalToString(item.percICMS);
string vICMS = DecimalToString(item.valorICMS);
string vBCIPI = DecimalToString(item.bcIPI);
string pIPI = DecimalToString(item.percIPI);
string vIPI = DecimalToString(item.valorIPI);
string vBCIBS = DecimalToString(item.bcIBS);
string vBCCBS = DecimalToString(item.bcCBS);
string vBCIBSCBS = DecimalToString(item.bcIBS);
string vIBSMunicipio = DecimalToString(item.valorIBSMunicipio);
string vIBSUF = DecimalToString(item.valorIBSUF);
string vIBS = DecimalToString(item.valorIBS);
string vCBS = DecimalToString(item.valorCBS);
string pIBS = item.percIBS.ToString("N4").Replace(".", "").Replace(',', '.');
string pCBS = item.percCBS.ToString("N4").Replace(".", "").Replace(',', '.');
string pIBSUF = (item.percIBSUF / 100 * item.percIBS)
.ToString("N4").Replace(".", "").Replace(',', '.');
string pIBSMunicipio = (item.percIBSMunicipio / 100 * item.percIBS)
.ToString("N4").Replace(".", "").Replace(',', '.');
if (devolverIPI)
{
string VIPIDEVOLVIDO = DecimalToString(item.valorIPIDevolucao);
var idev = new TNFeInfNFeDetImpostoDevol();
idev.IPI = new TNFeInfNFeDetImpostoDevolIPI();
idev.IPI.vIPIDevol = VIPIDEVOLVIDO;
idev.pDevol = "100.00";
oNotaXML.infNFe.det[i].impostoDevol = idev;
}
oNotaXML.infNFe.det[i].imposto.PIS = new TNFeInfNFeDetImpostoPIS();
object ItemPis = null;
var ItemPisOutr = new TNFeInfNFeDetImpostoPISPISOutr();
ItemPisOutr.CST = TNFeInfNFeDetImpostoPISPISOutrCST.Item99;
ItemPisOutr.Items = new string[2];
ItemPisOutr.Items[0] = vBCPIS;
ItemPisOutr.Items[1] = pPIS;
ItemPisOutr.ItemsElementName = new CE_pPIS[2];
ItemPisOutr.ItemsElementName[0] = CE_pPIS.vBC;
ItemPisOutr.ItemsElementName[1] = CE_pPIS.pPIS;
ItemPisOutr.vPIS = vPIS;
ItemPis = ItemPisOutr;
oNotaXML.infNFe.det[i].imposto.PIS.Item = ItemPis;
oNotaXML.infNFe.det[i].imposto.COFINS = new TNFeInfNFeDetImpostoCOFINS();
object ItemCOFINS = null;
var itemCOFINSOutr = new TNFeInfNFeDetImpostoCOFINSCOFINSOutr();
itemCOFINSOutr.Items = new string[2];
itemCOFINSOutr.Items[0] = vBCCOFINS;
itemCOFINSOutr.Items[1] = pCOFINS;
itemCOFINSOutr.ItemsElementName = new CE_pCOFINS[2];
itemCOFINSOutr.ItemsElementName[0] = CE_pCOFINS.vBC;
itemCOFINSOutr.ItemsElementName[1] = CE_pCOFINS.pCOFINS;
itemCOFINSOutr.vCOFINS = vCOFINS;
itemCOFINSOutr.CST = TNFeInfNFeDetImpostoCOFINSCOFINSOutrCST.Item99;
ItemCOFINS = itemCOFINSOutr;
oNotaXML.infNFe.det[i].imposto.COFINS.Item = ItemCOFINS;
if (oNotaXML.infNFe.det[i].imposto.Items == null)
oNotaXML.infNFe.det[i].imposto.Items = new object[1];
var itemICMS = new TNFeInfNFeDetImpostoICMS();
oNotaXML.infNFe.det[i].imposto.Items[0] = itemICMS;
if (item.csosnICMS == CSOSNICMS.Vazio)
throw new Exception("CSOSN (ICMS) deve ser informado.");
switch (item.csosnICMS)
{
case CSOSNICMS.ItemSIMPLES101:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN101();
((TNFeInfNFeDetImpostoICMSICMSSN101)itemICMS.Item).CSOSN = TNFeInfNFeDetImpostoICMSICMSSN101CSOSN.Item101;
((TNFeInfNFeDetImpostoICMSICMSSN101)itemICMS.Item).orig = Torig.Item0;
((TNFeInfNFeDetImpostoICMSICMSSN101)itemICMS.Item).pCredSN = "0.0000";
((TNFeInfNFeDetImpostoICMSICMSSN101)itemICMS.Item).vCredICMSSN = "0.00";
break;
}
case CSOSNICMS.ItemSIMPLES102:
case CSOSNICMS.ItemSIMPLES103:
case CSOSNICMS.ItemSIMPLES300:
case CSOSNICMS.ItemSIMPLES400:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN102();
((TNFeInfNFeDetImpostoICMSICMSSN102)itemICMS.Item).CSOSN =
item.csosnICMS == CSOSNICMS.ItemSIMPLES102 ? TNFeInfNFeDetImpostoICMSICMSSN102CSOSN.Item102 :
item.csosnICMS == CSOSNICMS.ItemSIMPLES103 ? TNFeInfNFeDetImpostoICMSICMSSN102CSOSN.Item103 :
item.csosnICMS == CSOSNICMS.ItemSIMPLES300 ? TNFeInfNFeDetImpostoICMSICMSSN102CSOSN.Item300 :
TNFeInfNFeDetImpostoICMSICMSSN102CSOSN.Item400;
((TNFeInfNFeDetImpostoICMSICMSSN102)itemICMS.Item).orig = Torig.Item0;
break;
}
case CSOSNICMS.ItemSIMPLES201:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN201();
((TNFeInfNFeDetImpostoICMSICMSSN201)itemICMS.Item).CSOSN = TNFeInfNFeDetImpostoICMSICMSSN201CSOSN.Item201;
((TNFeInfNFeDetImpostoICMSICMSSN201)itemICMS.Item).orig = Torig.Item0;
break;
}
case CSOSNICMS.ItemSIMPLES202:
case CSOSNICMS.ItemSIMPLES203:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN202();
((TNFeInfNFeDetImpostoICMSICMSSN202)itemICMS.Item).CSOSN =
item.csosnICMS == CSOSNICMS.ItemSIMPLES202 ? TNFeInfNFeDetImpostoICMSICMSSN202CSOSN.Item202 :
TNFeInfNFeDetImpostoICMSICMSSN202CSOSN.Item203;
((TNFeInfNFeDetImpostoICMSICMSSN202)itemICMS.Item).orig = Torig.Item0;
break;
}
case CSOSNICMS.ItemSIMPLES500:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN500();
((TNFeInfNFeDetImpostoICMSICMSSN500)itemICMS.Item).CSOSN = TNFeInfNFeDetImpostoICMSICMSSN500CSOSN.Item500;
((TNFeInfNFeDetImpostoICMSICMSSN500)itemICMS.Item).orig = Torig.Item0;
break;
}
case CSOSNICMS.ItemSIMPLES900:
{
itemICMS.Item = new TNFeInfNFeDetImpostoICMSICMSSN900();
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).CSOSN = TNFeInfNFeDetImpostoICMSICMSSN900CSOSN.Item900;
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).orig = Torig.Item0;
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).vBC = vBCICMS;
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).vICMS = vICMS;
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).pICMS = pICMS;
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).vBCST = "0.00";
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).pICMSST = "0.00";
((TNFeInfNFeDetImpostoICMSICMSSN900)itemICMS.Item).vICMSST = "0.00";
break;
}
}
oNotaXML.infNFe.det[i].imposto.IBSCBS = new TNFeInfNFeDetImpostoIBSCBS();
if (item.cst != CST.Vazio)
oNotaXML.infNFe.det[i].imposto.IBSCBS.CST = item.cst.GetDescription().Substring(0, 3);
if (item.classificacaoTributaria != null)
oNotaXML.infNFe.det[i].imposto.IBSCBS.cClassTrib = item.classificacaoTributaria.Sigla;
var gIBSCBS = new TNFeInfNFeDetImpostoIBSCBSgIBSCBS();
gIBSCBS.vIBS = vIBS;
gIBSCBS.vBC = vBCIBSCBS;
gIBSCBS.gCBS = new TNFeInfNFeDetImpostoIBSCBSgIBSCBSgCBS();
gIBSCBS.gCBS.vCBS = vCBS;
gIBSCBS.gCBS.pCBS = pCBS;
gIBSCBS.gIBSMun = new TNFeInfNFeDetImpostoIBSCBSgIBSCBSgIBSMun();
gIBSCBS.gIBSMun.pIBSMun = pIBSMunicipio;
gIBSCBS.gIBSMun.vIBSMun = vIBSMunicipio;
gIBSCBS.gIBSUF = new TNFeInfNFeDetImpostoIBSCBSgIBSCBSgIBSUF();
gIBSCBS.gIBSUF.vIBSUF = vIBSUF;
gIBSCBS.gIBSUF.pIBSUF = pIBSUF;
oNotaXML.infNFe.det[i].imposto.IBSCBS.Item = gIBSCBS;
i++;
}
oNotaXML.infNFe.total = new TNFeInfNFeTotal();
oNotaXML.infNFe.total.ICMSTot = new TNFeInfNFeTotalICMSTot();
string vBCTOTAL = DecimalToString(np.bctotal);
string vICMSTOTAL = DecimalToString(np.icmstotal);
string vPISTOTAL = DecimalToString(np.pistotal);
string vIPITOTAL = DecimalToString(np.ipitotal);
string vCOFINSTOTAL = DecimalToString(np.cofinstotal);
string vCBSTOTAL = DecimalToString(np.cbstotal);
string vIBSTOTAL = DecimalToString(np.ibstotal);
string vIBSTOTALMUNICIPIO = DecimalToString(np.ibstotalMunicipio);
string vIBSTOTALUF = DecimalToString(np.ibstotalUF);
string vProd = DecimalToString(np.itens.Sum(x => x.quantidade * x.valorUnitario));
string vCBSIBSTOTAL = DecimalToString(np.cbstotal + np.ibstotal);
string vBCIBSCBSTOTAL = vProd;
oNotaXML.infNFe.total.ICMSTot.vBC = vBCTOTAL;
oNotaXML.infNFe.total.ICMSTot.vICMS = vICMSTOTAL;
oNotaXML.infNFe.total.ICMSTot.vICMSDeson = "0.00";
oNotaXML.infNFe.total.ICMSTot.vFCPUFDest = "0.00";
oNotaXML.infNFe.total.ICMSTot.vICMSUFDest = "0.00";
oNotaXML.infNFe.total.ICMSTot.vICMSUFRemet = "0.00";
oNotaXML.infNFe.total.ICMSTot.vBCST = "0.00";
oNotaXML.infNFe.total.ICMSTot.vFCP = "0.00";
oNotaXML.infNFe.total.ICMSTot.vST = "0.00";
oNotaXML.infNFe.total.ICMSTot.vFCPST = "0.00";
oNotaXML.infNFe.total.ICMSTot.vFCPSTRet = "0.00";
oNotaXML.infNFe.total.ICMSTot.vProd = vProd;
var ValorNotaFiscal = DecimalToString(np.valorNF);
oNotaXML.infNFe.total.ICMSTot.vNF = ValorNotaFiscal;
if (oNotaXML.infNFe.pag.detPag[0].tPag == TNFeInfNFePagDetPagTPag.Item90) // Sem Pagamento
oNotaXML.infNFe.pag.detPag[0].vPag = "0.00";
else
oNotaXML.infNFe.pag.detPag[0].vPag = ValorNotaFiscal;
if (devolverIPI)
oNotaXML.infNFe.total.ICMSTot.vNF = DecimalToString(np.valorNF + totalIPIDevolucao);
oNotaXML.infNFe.total.ICMSTot.vFrete = DecimalToString(np.itens.Sum(x => x.valorFrete));
oNotaXML.infNFe.total.ICMSTot.vSeg = "0.00";
oNotaXML.infNFe.total.ICMSTot.vDesc = DecimalToString(np.itens.Sum(x => x.valorDesconto));
oNotaXML.infNFe.total.ICMSTot.vII = "0.00";
oNotaXML.infNFe.total.ICMSTot.vIPI = vIPITOTAL;
oNotaXML.infNFe.total.ICMSTot.vIPIDevol = strVIPIDEV;
oNotaXML.infNFe.total.ICMSTot.vPIS = vPISTOTAL;
oNotaXML.infNFe.total.ICMSTot.vCOFINS = vCOFINSTOTAL;
oNotaXML.infNFe.total.ICMSTot.vOutro = "0.00";
oNotaXML.infNFe.total.ICMSTot.vTotTrib = "0.00";
oNotaXML.infNFe.total.IBSCBSTot = new TNFeInfNFeTotalIBSCBSTot();
oNotaXML.infNFe.total.IBSCBSTot.gIBS = new TNFeInfNFeTotalIBSCBSTotgIBS();
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSMun = new TNFeInfNFeTotalIBSCBSTotgIBSgIBSMun();
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSMun.vIBSMun = vIBSTOTALMUNICIPIO;
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSMun.vDif = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSMun.vDevTrib = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSUF = new TNFeInfNFeTotalIBSCBSTotgIBSgIBSUF();
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSUF.vIBSUF = vIBSTOTALUF;
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSUF.vDif = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gIBS.gIBSUF.vDevTrib = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gIBS.vIBS = vIBSTOTAL;
oNotaXML.infNFe.total.IBSCBSTot.gIBS.vCredPres = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gIBS.vCredPresCondSus = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gCBS = new TNFeInfNFeTotalIBSCBSTotgCBS();
oNotaXML.infNFe.total.IBSCBSTot.gCBS.vCBS = vCBSTOTAL;
oNotaXML.infNFe.total.IBSCBSTot.gCBS.vDif = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gCBS.vDevTrib = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gCBS.vCredPres = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.gCBS.vCredPresCondSus = "0.00";
oNotaXML.infNFe.total.IBSCBSTot.vBCIBSCBS = vBCIBSCBSTOTAL;
oNotaXML.infNFe.transp = new TNFeInfNFeTransp();
if (np.tipoModalidadeFrete == TipoModalidadeFrete.Emitente)
oNotaXML.infNFe.transp.modFrete = TNFeInfNFeTranspModFrete_v400.Item0;
else if (np.tipoModalidadeFrete == TipoModalidadeFrete.Remetente)
oNotaXML.infNFe.transp.modFrete = TNFeInfNFeTranspModFrete_v400.Item1;
else if (np.tipoModalidadeFrete == TipoModalidadeFrete.Terceiros)
oNotaXML.infNFe.transp.modFrete = TNFeInfNFeTranspModFrete_v400.Item2;
else if (np.tipoModalidadeFrete == TipoModalidadeFrete.SemFrete)
oNotaXML.infNFe.transp.modFrete = TNFeInfNFeTranspModFrete_v400.Item9;
oNotaXML.infNFe.infAdic = new TNFeInfNFeInfAdic();
if (!String.IsNullOrEmpty(np.observacoes))
{
var obs = np.observacoes.Replace("\n", "").Trim();
if (!String.IsNullOrEmpty(obs))
oNotaXML.infNFe.infAdic.infCpl = obs;
}
Random random = new Random();
string cUF = np.uf.codigoIBGE.ToString("00");
string AAMM = np.dataEmissao.ToString("yyMM");
string CNPJ = np.documentoEmitente;
string mod = "55";
string serie = np.serie.ToString("000");
string nNF = np.numero.ToString("000000000");
string tpEmis = ((int)np.modoEmissao).ToString();
string cNF = random.Next(99999999).ToString("00000000");
string NFeKey = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}",
cUF, AAMM, CNPJ, mod, serie, nNF, tpEmis, cNF);
string cDV = DvBase11(NFeKey);
oNotaXML.infNFe.Id = string.Format("NFe{0}{1}", NFeKey, cDV);
oNotaXML.infNFe.versao = "4.00";
oNotaXML.infNFe.ide.cNF = cNF;
oNotaXML.infNFe.ide.nNF = np.numero.ToString();
oNotaXML.infNFe.ide.tpEmis = TNFeInfNFeIdeTpEmis.Normal;
oNotaXML.infNFe.ide.cDV = cDV;
oNotaXML.infNFe.ide.mod = TMod.Item55;
oNotaXML.infNFe.ide.serie = np.serie.ToString();
return oNotaXML;
}