Class: BrNfe::Product::Operation::Base

Inherits:
Base show all
Includes:
NfXmlValue
Defined in:
lib/br_nfe/product/operation/base.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#certificate_pkcs12_password, #certificate_pkcs12_path, #certificate_pkcs12_value, #env, #ibge_code_of_issuer_city, #ibge_code_of_issuer_uf

Attributes inherited from ActiveModelBase

#reference

Instance Method Summary collapse

Methods included from NfXmlValue

#nf_xml_fixed_code, #nf_xml_value_CEP, #nf_xml_value_CEST, #nf_xml_value_CFOP, #nf_xml_value_CNAE, #nf_xml_value_CRT, #nf_xml_value_EAN, #nf_xml_value_EXTIPI, #nf_xml_value_IE, #nf_xml_value_IM, #nf_xml_value_ISSQN_incentivo_fiscal, #nf_xml_value_NCM, #nf_xml_value_NVE, #nf_xml_value_RNTC, #nf_xml_value_UF, #nf_xml_value_boolean, #nf_xml_value_chave_nfe, #nf_xml_value_cnpj, #nf_xml_value_codigo_enquadramento_IPI, #nf_xml_value_codigo_ibge_municipio, #nf_xml_value_codigo_nf, #nf_xml_value_codigo_pais, #nf_xml_value_consumidor_final, #nf_xml_value_cpf, #nf_xml_value_date, #nf_xml_value_date_time, #nf_xml_value_drawback, #nf_xml_value_email, #nf_xml_value_float, #nf_xml_value_fone, #nf_xml_value_id_estrangeiro, #nf_xml_value_id_local_destino, #nf_xml_value_indicador_IE, #nf_xml_value_indicador_sincrono, #nf_xml_value_inscricao_suframa, #nf_xml_value_monetary, #nf_xml_value_number, #nf_xml_value_number_fixed_size, #nf_xml_value_numero_recibo, #nf_xml_value_orgao_emissor, #nf_xml_value_percent, #nf_xml_value_peso, #nf_xml_value_placa, #nf_xml_value_quantidade, #nf_xml_value_text, #nf_xml_value_time, #nf_xml_value_tipo_ambiente

Methods inherited from Base

#certificate, #certificate=, #certificate_key, #certificate_key=, #certificate_pkcs12, #certificate_pkcs12=, #client_wsdl, #content_xml, #env_namespace, #env_test?, #find_xml, #get_xml_dirs, #id_attribute?, #message_namespaces, #namespace_for_signature, #namespace_for_tags, #namespace_identifier, #original_response, #render_xml, #response_encoding, #sign_xml, #signature_type, #signature_type?, #soap_namespaces, #soap_xml, #tag_xml, #wsdl_encoding, #xml_builder, #xml_default_dir_path

Methods included from Association::HaveEmitente

#emitente, #emitente=

Methods inherited from ActiveModelBase

#assign_attributes, #initialize

Constructor Details

This class inherits a constructor from BrNfe::ActiveModelBase

Instance Attribute Details

#inicio_contingenciaObject

Data e hora do início da contingência



33
34
35
# File 'lib/br_nfe/product/operation/base.rb', line 33

def inicio_contingencia
  @inicio_contingencia
end

#motivo_contingenciaObject

Informações que devem ser informadas quando a operação for em contingência.



32
33
34
# File 'lib/br_nfe/product/operation/base.rb', line 32

def motivo_contingencia
  @motivo_contingencia
end

#nfe_versionObject

Versão da NF-e que irá pegar as configurações



8
9
10
# File 'lib/br_nfe/product/operation/base.rb', line 8

def nfe_version
  @nfe_version
end

#original_xmlObject

String XML que será aplicado o resultado da resposta do serviço de acordo com a operação. Por exemplo, quando vai consultar o protocolo da emissão de uma nfe, deve ser passado por parâmetro o XML da NF-e para que seja possível obter o XML da nota fiscal junto com o protocolo de autorização. Também quando for cancelar uma nota fiscal deve passar o XML da nota para que seja adicionado o protocolo de confirmação de cancelamento junto a nota.

Required: No Type: String XML



49
50
51
# File 'lib/br_nfe/product/operation/base.rb', line 49

def original_xml
  @original_xml
end

#tipo_emissaoObject

Serve para saber se vai usar o módo de contingência, e se usar, serve para saber qual o tipo de contingência será utilizado. Options: [:normal, :svc]

Required: Yes Default: :normal



17
18
19
# File 'lib/br_nfe/product/operation/base.rb', line 17

def tipo_emissao
  @tipo_emissao
end

Instance Method Details

#certificado_obrigatorio?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/br_nfe/product/operation/base.rb', line 62

def certificado_obrigatorio?
  true
end

#client_wsdl_paramsObject

Parâmetros específicos para cada servidor de cada estado para que seja instanciado o Client WSDL savon.

Tipo de retorno: Hash



201
202
203
204
205
206
207
208
# File 'lib/br_nfe/product/operation/base.rb', line 201

def client_wsdl_params
  super.merge({
    ssl_version:           :SSLv3, # Valores possíveis: [:TLSv1_2, :TLSv1_1, :TLSv1, :SSLv3, :SSLv23]
    ssl_cert:              certificate,
    ssl_cert_key:          certificate_key,
    ssl_cert_key_password: certificate_pkcs12_password,
  }).merge(gateway_settings[:soap_client][operation_name][env])
end

#codigo_tipo_emissao(nfe) ⇒ Object

Código do Tipo de Emissão da NF-e



277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/br_nfe/product/operation/base.rb', line 277

def codigo_tipo_emissao(nfe)
  return 9 if nfe.nfce?
  case tipo_emissao
  when :normal 
    1
  when :svc
    if gateway == :svc_rs
      7 # SVC-RS
    else
      6 # SVC-AN
    end
  end
end

#contingencia?Boolean

Método utilizado para saber se a operação será em contingência.

Tipo de retorno: Boolean

Returns:

  • (Boolean)


262
263
264
# File 'lib/br_nfe/product/operation/base.rb', line 262

def contingencia?
  tipo_emissao != :normal
end

#default_valuesObject



55
56
57
58
59
60
# File 'lib/br_nfe/product/operation/base.rb', line 55

def default_values
  {
    tipo_emissao:   :normal,
    nfe_version:    :v3_10,
  }
end

#gatewayObject

Método utilizado para saber qual Webservice será utilizado. Deve sempre retornar um symbol de acordo com as configurações dos gateways.

Tipo de retorno: Symbol



71
72
73
74
75
76
77
78
# File 'lib/br_nfe/product/operation/base.rb', line 71

def gateway
  @gateway ||= case tipo_emissao
  when :normal
    get_gateway_by_normal_operation
  when :svc
    get_gateway_by_svc_operation
  end
end

#gateway_settingsObject

Método que retorna as configurações do Servidor da Sefaz a ser utilziada. Irá retornar um Hash com as seguntes chaves:

- :operation   => Cont

Tipo de retorno: Symbol



95
96
97
# File 'lib/br_nfe/product/operation/base.rb', line 95

def gateway_settings
  nfe_settings[:gateway][gateway]
end

#gateway_xml_versionObject

Versão utilizada pelo webservice do estado para determinada ação. Irá retornar a versão setada de acordo com o serviço e estado conforme descrito em: www.nfe.fazenda.gov.br/portal/webServices.aspx

Tipo de retorno: Symbol



183
184
185
# File 'lib/br_nfe/product/operation/base.rb', line 183

def gateway_xml_version
  gateway_settings[:operation][operation_name][env][:xml_version]
end

#get_gateway_by_normal_operationObject

Seta o WebService quando o tipo de emissão for normal para cada UF

Tipo de retorno: Hash



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/br_nfe/product/operation/base.rb', line 121

def get_gateway_by_normal_operation       
  case "#{ibge_code_of_issuer_uf}"
  when '13'
    :am
  when '29'
    :ba
  when '23'
    :ce
  when '52'
    :go
  when '31'
    :mg
  when '50'
    :ms
  when '51'
    :mt
  when '26'
    :pe
  when '41'
    :pr
  when '43'
    :rs
  when '35'
    :sp
  when '21', '15' # MA, PA
    :svan
  else 
    # AC, AL, AP, ES, DF, PB, RJ, RM, RO, RR, SC, PI
    # 12, 27, 16, 32, 53, 25, 33, 24, 11, 14, 42, 22
    :svrs
  end
end

#get_gateway_by_svc_operationObject

WebServices utilizados para contingência em SVC (Servidor Virtual de Contingência) Existe 2 servidores de contingência para SVC: O ‘SVC-AN` e `SVC-RS` Cada estado(UF) é autorizado a emitir notas em contingência em apenas 1 dos servidores. Esse método é responsável em setar qual o WebService será utilizado para cada UF.

Tipo de retorno: Hash



107
108
109
110
111
112
113
114
115
# File 'lib/br_nfe/product/operation/base.rb', line 107

def get_gateway_by_svc_operation
  case ibge_code_of_issuer_uf
  #    'AM', 'BA', 'CE', 'GO', 'MA', 'MS', 'MT', 'PA', 'PE', 'PI', 'PR'
  when '13', '29', '23', '52', '21', '50', '51', '15', '26', '22', '41'
    :svc_rs
  else # AC, AL, AP, DF, ES, MG, PB, RJ, RN, RO, RR, RS, SC, SE, SP, TO 
    :svc_an
  end
end

#method_wsdlObject

Método SOAP que será chamado para enviar o XML

Tipo de retorno: Symbol



162
163
164
# File 'lib/br_nfe/product/operation/base.rb', line 162

def method_wsdl
  gateway_settings[:operation][operation_name][env][:operation_method]
end

#nfe_settingsObject

Configurações das operações da nota fiscal de acordo com a versão.



82
83
84
# File 'lib/br_nfe/product/operation/base.rb', line 82

def nfe_settings
  BrNfe.settings[:nfe][nfe_version]
end

#operation_nameObject

Raises:

  • (NotImplementedError)


154
155
156
# File 'lib/br_nfe/product/operation/base.rb', line 154

def operation_name
  raise NotImplementedError.new("Not implemented #operation_name in #{self}.")
end

#requestObject



291
292
293
294
295
296
297
298
299
# File 'lib/br_nfe/product/operation/base.rb', line 291

def request
  @savon_response = client_wsdl.call(method_wsdl, xml: soap_xml)
rescue Savon::SOAPFault => error
  return @response = response_class_builder.new.response_class.new(request_status: :soap_error,    request_message_error: error.message)
rescue Savon::HTTPError => error
  return @response = response_class_builder.new.response_class.new(request_status: :http_error,    request_message_error: error.message)
rescue Exception => error
  return @response = response_class_builder.new.response_class.new(request_status: :unknown_error, request_message_error: error.message)
end

#responseObject



301
302
303
# File 'lib/br_nfe/product/operation/base.rb', line 301

def response
  @response ||= get_response
end

#url_wsdlObject

Deve conter o LINK do webservice a ser chamado TODO: Remover método



214
215
216
# File 'lib/br_nfe/product/operation/base.rb', line 214

def url_wsdl
  ''
end

#url_xmlnsObject

Valor utilizado para inserir a url do xmlns nas tags nfeCabecMsg e nfeDadosMsg. URL que será setada no atribto xmlns do XML; Ex:

nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"

Tipo de retorno: String



173
174
175
# File 'lib/br_nfe/product/operation/base.rb', line 173

def url_xmlns
  gateway_settings[:operation][operation_name][env][:url_xmlns]
end

#xml_current_dir_pathObject

Declaro que o método ‘render_xml` irá verificar os arquivos também presentes nos diretórios especificados. O diretório dos XMLs irá variar de acordo com a operação e a versão do XML utilizado. EX:

Se a vers

Foi construido dessa forma pois algumas tags utilizadas na v3.10 são exatamente iguais da v2.0, e nesse caso não há a necessidade de duplicar o código.

Tipo de retorno: Array



247
248
249
250
251
252
253
254
255
256
# File 'lib/br_nfe/product/operation/base.rb', line 247

def xml_current_dir_path
  return @xml_current_dir_path if @xml_current_dir_path.present?
  paths = ["#{BrNfe.root}/lib/br_nfe/product/xml/v1_00"] # Sempre terá o path da v1_00
  paths << "#{BrNfe.root}/lib/br_nfe/product/xml/v1_10" if gateway_xml_version >= :v1_10
  paths << "#{BrNfe.root}/lib/br_nfe/product/xml/v2_00" if gateway_xml_version >= :v2_00
  paths << "#{BrNfe.root}/lib/br_nfe/product/xml/v2_01" if gateway_xml_version >= :v2_01
  paths << "#{BrNfe.root}/lib/br_nfe/product/xml/v3_10" if gateway_xml_version == :v3_10
  
  @xml_current_dir_path = paths.reverse+["#{BrNfe.root}/lib/br_nfe/product/xml"]+super
end

#xml_versionObject

Versão do XML utilizado na requisição. Como a versão do XML pode divergir para cada estado/servidor e serviço, é necessário passar a versão do XML na requisição para o servidor saber qual validação aplicar e como pegar os dados. Esse método tem o intuíto de pegar a versão setada no Gateway de cada UF e serviço e transformar em uma String aplicável no XML. Exemplo:

Se a vers

Tipo de retorno: String



230
231
232
# File 'lib/br_nfe/product/operation/base.rb', line 230

def xml_version
  "#{gateway_xml_version}".gsub('_','.').gsub(/[^\d\.]/,'')
end

#xmlns_soapObject

Retorna o xmlns utilizada para identificar o envelope da requisição SOAP Normalmente é www.w3.org/2003/05/soap-envelope

Tipo de retorno: String



192
193
194
# File 'lib/br_nfe/product/operation/base.rb', line 192

def xmlns_soap
  gateway_settings[:operation][operation_name][env][:xmlns_soap]
end