def action_send_eletronic_invoice(self): self.state = 'error' self.data_emissao = datetime.now() super(InvoiceEletronic, self).action_send_eletronic_invoice() if self.model not in ('55', '65'): return nfe_values = self._prepare_eletronic_invoice_values() lote = self._prepare_lote(self.id, nfe_values) cert = self.company_id.with_context({'bin_size': False}).nfe_a1_file cert_pfx = base64.decodestring(cert) certificado = Certificado(cert_pfx, self.company_id.nfe_a1_password) resposta_recibo = None resposta = autorizar_nfe(certificado, **lote) retorno = resposta['object'].Body.nfeAutorizacaoLoteResult retorno = retorno.getchildren()[0] if retorno.cStat == 103: obj = { 'estado': self.company_id.partner_id.state_id.ibge_code, 'ambiente': 1 if self.ambiente == 'producao' else 2, 'obj': { 'ambiente': 1 if self.ambiente == 'producao' else 2, 'numero_recibo': retorno.infRec.nRec } } self.recibo_nfe = obj['obj']['numero_recibo'] import time while True: time.sleep(2) resposta_recibo = retorno_autorizar_nfe(certificado, **obj) retorno = resposta_recibo['object'].Body.\ nfeRetAutorizacaoLoteResult.retConsReciNFe if retorno.cStat != 105: break if retorno.cStat != 104: self.codigo_retorno = retorno.cStat self.mensagem_retorno = retorno.xMotivo else: self.codigo_retorno = retorno.protNFe.infProt.cStat self.mensagem_retorno = retorno.protNFe.infProt.xMotivo if self.codigo_retorno == '100': self.write({ 'state': 'done', 'nfe_exception': False, 'protocolo_nfe': retorno.protNFe.infProt.nProt, 'data_autorizacao': retorno.protNFe.infProt.dhRecbto }) # Duplicidade de NF-e significa que a nota já está emitida # TODO Buscar o protocolo de autorização, por hora só finalizar if self.codigo_retorno == '204': self.write({ 'state': 'done', 'codigo_retorno': '100', 'nfe_exception': False, 'mensagem_retorno': 'Autorizado o uso da NF-e' }) # Denegada e nota já está denegada if self.codigo_retorno in ('302', '205'): self.write({'state': 'denied', 'nfe_exception': True}) self.env['invoice.eletronic.event'].create({ 'code': self.codigo_retorno, 'name': self.mensagem_retorno, 'invoice_eletronic_id': self.id, }) self._create_attachment('nfe-envio', self, resposta['sent_xml']) self._create_attachment('nfe-ret', self, resposta['received_xml']) recibo_xml = resposta['received_xml'] if resposta_recibo: self._create_attachment('rec', self, resposta_recibo['sent_xml']) self._create_attachment('rec-ret', self, resposta_recibo['received_xml']) recibo_xml = resposta_recibo['received_xml'] if self.codigo_retorno == '100': nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml) self.nfe_processada = base64.encodestring(nfe_proc) self.nfe_processada_name = "NFe%08d.xml" % self.numero
def action_send_eletronic_invoice(self): if self.model not in ['nfe', 'nfce']: return super(EletronicDocument, self).action_send_eletronic_invoice() if self.state in ('done', 'denied', 'cancel'): return errors = self._hook_validation() if len(errors) > 0: msg = "\n".join( ["Por favor corrija os erros antes de prosseguir"] + errors) raise UserError(msg) self._update_document_values() self.action_post_validate() _logger.info('Sending NF-e (%s) (%.2f) - %s' % (self.numero, self.valor_final, self.partner_id.name)) self.write({'state': 'error', 'data_emissao': datetime.now()}) cert = self.company_id.with_context({ 'bin_size': False }).l10n_br_certificate cert_pfx = base64.decodestring(cert) certificado = Certificado(cert_pfx, self.company_id.l10n_br_cert_password) xml_to_send = base64.decodestring(self.xml_to_send).decode('utf-8') resposta_recibo = None resposta = autorizar_nfe( certificado, xml=xml_to_send, estado=self.company_id.state_id.l10n_br_ibge_code, ambiente=1 if self.ambiente == 'producao' else 2, modelo='55' if self.model == 'nfe' else '65') retorno = resposta['object'].getchildren()[0] if retorno.cStat == 103: obj = { 'estado': self.company_id.partner_id.state_id.l10n_br_ibge_code, 'ambiente': 1 if self.ambiente == 'producao' else 2, 'obj': { 'ambiente': 1 if self.ambiente == 'producao' else 2, 'numero_recibo': retorno.infRec.nRec }, 'modelo': '55' if self.model == 'nfe' else '65', } self.recibo_nfe = obj['obj']['numero_recibo'] import time while True: time.sleep(2) resposta_recibo = retorno_autorizar_nfe(certificado, **obj) retorno = resposta_recibo['object'].getchildren()[0] if retorno.cStat != 105: break if retorno.cStat != 104: self.write({ 'codigo_retorno': retorno.cStat, 'mensagem_retorno': retorno.xMotivo, }) self.notify_user() else: self.write({ 'codigo_retorno': retorno.protNFe.infProt.cStat, 'mensagem_retorno': retorno.protNFe.infProt.xMotivo, }) if self.codigo_retorno == '100': self.write({ 'state': 'done', 'protocolo_nfe': retorno.protNFe.infProt.nProt, 'data_autorizacao': retorno.protNFe.infProt.dhRecbto }) else: self.notify_user() # Duplicidade de NF-e significa que a nota já está emitida # TODO Buscar o protocolo de autorização, por hora só finalizar if self.codigo_retorno == '204': self.write({ 'state': 'done', 'codigo_retorno': '100', 'mensagem_retorno': 'Autorizado o uso da NF-e' }) # Denegada e nota já está denegada if self.codigo_retorno in ('302', '205'): self.write({'state': 'denied'}) self._create_attachment('nfe-envio', self, resposta['sent_xml']) self._create_attachment('nfe-ret', self, resposta['received_xml']) recibo_xml = resposta['received_xml'] if resposta_recibo: self._create_attachment('rec', self, resposta_recibo['sent_xml']) self._create_attachment('rec-ret', self, resposta_recibo['received_xml']) recibo_xml = resposta_recibo['received_xml'] if self.codigo_retorno == '100': nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml) self.sudo().write({ 'nfe_processada': base64.encodestring(nfe_proc), 'nfe_processada_name': "NFe%08d.xml" % self.numero, }) _logger.info('NF-e (%s) was finished with status %s' % (self.numero, self.codigo_retorno))
# Funções Para Gerar e Assinar o XML xml_enviar = xml_autorizar_nfe(certificado, **lote) mensagens_erro = valida_nfe(xml_enviar) if mensagens_erro: print(mensagens_erro) print(xml_enviar) #xml_to_send = base64.encodestring(xml_enviar.encode('utf-8')) #Funções para Envio do XML estado = '15' resposta_recibo = None resposta = autorizar_nfe(certificado, xml=xml_enviar, estado='13', ambiente=2, modelo='55') #import pudb;pu.db # Elemento Alterado retorno = resposta['object'].Body.nfeResultMsg retorno = retorno.getchildren()[0] if retorno.cStat == 103: obj = { 'estado': estado, 'ambiente': 2, 'obj': { 'ambiente': 2, 'numero_recibo': retorno.infRec.nRec }
def action_send_eletronic_invoice(self): if self.model not in ('55', '65') or self.state in ('done', 'denied', 'cancel'): return self.state = 'error' self.data_emissao = datetime.now() nfe_values = self._prepare_eletronic_invoice_values() lote = self._prepare_lote(self.id, nfe_values) cert = self.company_id.with_context({'bin_size': False}).nfe_a1_file cert_pfx = base64.decodestring(cert) certificado = Certificado(cert_pfx, self.company_id.nfe_a1_password) resposta_recibo = None resposta = autorizar_nfe(certificado, self.model, **lote) retorno = resposta['object'].Body.nfeAutorizacaoLoteResult retorno = retorno.getchildren()[0] if self.model == '65': xml = resposta['sent_xml'] qr_code = etree.XML(resposta['sent_xml']) qr_code = qr_code.find(".//{http://www.portalfiscal.inf.br/nfe}qrCode") self.qrcode_hash = qr_code.text self.qrcode_url = qr_code.text.split('?')[0] if retorno.cStat == 103: obj = { 'estado': self.company_id.partner_id.state_id.ibge_code, 'ambiente': 1 if self.ambiente == 'producao' else 2, 'obj': { 'ambiente': 1 if self.ambiente == 'producao' else 2, 'numero_recibo': retorno.infRec.nRec } } self.recibo_nfe = obj['obj']['numero_recibo'] import time while True: time.sleep(2) resposta_recibo = retorno_autorizar_nfe(certificado, self.model, **obj) retorno = resposta_recibo['object'].Body.\ nfeRetAutorizacaoLoteResult.retConsReciNFe if retorno.cStat != 105: break if retorno.cStat != 104: self.codigo_retorno = retorno.cStat self.mensagem_retorno = retorno.xMotivo else: self.codigo_retorno = retorno.protNFe.infProt.cStat self.mensagem_retorno = retorno.protNFe.infProt.xMotivo if self.codigo_retorno == '100': self.write({ 'state': 'done', 'nfe_exception': False, 'protocolo_nfe': retorno.protNFe.infProt.nProt, 'data_autorizacao': retorno.protNFe.infProt.dhRecbto}) # Duplicidade de NF-e significa que a nota já está emitida # TODO Buscar o protocolo de autorização, por hora só finalizar if self.codigo_retorno == '204': self.write({'state': 'done', 'codigo_retorno': '100', 'nfe_exception': False, 'mensagem_retorno': 'Autorizado o uso da NF-e'}) self.env['invoice.eletronic.event'].create({ 'code': self.codigo_retorno, 'name': self.mensagem_retorno, 'invoice_eletronic_id': self.id, }) self._create_attachment('nfe-envio', self, resposta['sent_xml']) self._create_attachment('nfe-ret', self, resposta['received_xml']) if resposta_recibo: self._create_attachment('rec', self, resposta_recibo['sent_xml']) self._create_attachment('rec-ret', self, resposta_recibo['received_xml'])
def action_send_eletronic_invoice(self): super(InvoiceEletronic, self).action_send_eletronic_invoice() if self.model not in ('55', '65') or self.state in ('done', 'denied', 'cancel'): return self.state = 'error' self.data_emissao = datetime.now() cert = self.company_id.with_context({'bin_size': False}).nfe_a1_file cert_pfx = base64.decodestring(cert) certificado = Certificado(cert_pfx, self.company_id.nfe_a1_password) xml_to_send = base64.decodestring(self.xml_to_send).decode( 'utf-8', 'ignore') import string _logger.info("----------before-------------%s", xml_to_send) xml_to_send = ''.join(x for x in xml_to_send if x in string.printable) xml_to_send = re.sub('\s+(?=<)', '', xml_to_send) xml_to_send = re.sub('\n', '', xml_to_send) _logger.info("----------xml_to_send-------------%s", xml_to_send) resposta_recibo = None resposta = autorizar_nfe( certificado, xml=xml_to_send, estado=self.company_id.state_id.ibge_code, ambiente=1 if self.ambiente == 'producao' else 2, modelo=self.model) retorno = resposta['object'].getchildren()[0] if retorno.cStat == 103: obj = { 'estado': self.company_id.partner_id.state_id.ibge_code, 'ambiente': 1 if self.ambiente == 'producao' else 2, 'obj': { 'ambiente': 1 if self.ambiente == 'producao' else 2, 'numero_recibo': retorno.infRec.nRec }, 'modelo': self.model, } self.recibo_nfe = obj['obj']['numero_recibo'] import time while True: time.sleep(2) resposta_recibo = retorno_autorizar_nfe(certificado, **obj) retorno = resposta_recibo['object'].getchildren()[0] if retorno.cStat != 105: break if retorno.cStat != 104: self.codigo_retorno = retorno.cStat self.mensagem_retorno = retorno.xMotivo else: self.codigo_retorno = retorno.protNFe.infProt.cStat self.mensagem_retorno = retorno.protNFe.infProt.xMotivo if self.codigo_retorno == '100': self.write({ 'state': 'done', 'protocolo_nfe': retorno.protNFe.infProt.nProt, 'data_autorizacao': retorno.protNFe.infProt.dhRecbto }) # Duplicidade de NF-e significa que a nota já está emitida # TODO Buscar o protocolo de autorização, por hora só finalizar if self.codigo_retorno == '204': self.write({ 'state': 'done', 'codigo_retorno': '100', 'mensagem_retorno': 'Autorizado o uso da NF-e' }) # Denegada e nota já está denegada if self.codigo_retorno in ('302', '205'): self.write({'state': 'denied'}) self.env['invoice.eletronic.event'].create({ 'code': self.codigo_retorno, 'name': self.mensagem_retorno, 'invoice_eletronic_id': self.id, }) self._create_attachment('nfe-envio', self, resposta['sent_xml']) self._create_attachment('nfe-ret', self, resposta['received_xml']) recibo_xml = resposta['received_xml'] if resposta_recibo: self._create_attachment('rec', self, resposta_recibo['sent_xml']) self._create_attachment('rec-ret', self, resposta_recibo['received_xml']) recibo_xml = resposta_recibo['received_xml'] if self.codigo_retorno == '100': nfe_proc = gerar_nfeproc(resposta['sent_xml'], recibo_xml) self.nfe_processada = base64.encodestring(nfe_proc) self.nfe_processada_name = "NFe%08d.xml" % self.numero