Beispiel #1
0
def _handle_exception(self, exception):
    """Called within an except block to allow converting exceptions
        to arbitrary responses. Anything returned (except None) will
        be used as response."""
    try:
        return eval('super(JsonRequest, self)._handle_exception(exception)')
    except eval('Exception'):
        if not isinstance(exception, (openerp.exceptions.Warning, SessionExpiredException)):
            _logger.exception("Exception during JSON request handling.")
        error = {
            'code': 200,
            'message': "Odoo Server Error",
            'data': http.serialize_exception(exception)
        }
        if isinstance(exception, AuthenticationError):
            error['code'] = 100
            error['message'] = "Odoo Session Invalid"
        if isinstance(exception, SessionExpiredException):
            error['code'] = 100
            error['message'] = "Odoo Session Expired"
        if exception.name == 'Not Found' and exception.code == 404:
            error['code'] = 100
            error['message'] = "Odoo Session Expired"
            error['data']['name'] = 'werkzeug.exceptions.Forbidden'
        return self._json_response(error=error)
Beispiel #2
0
 def _handle_exception(self, exception):
     """Called within an except block to allow converting exceptions
        to arbitrary responses. Anything returned (except None) will
        be used as response."""
     try:
         return super(ApiJsonRequest, self)._handle_exception(exception)
     except Exception:
         if not isinstance(
             exception,
             (
                 openerp.exceptions.Warning,
                 SessionExpiredException,
                 openerp.exceptions.except_orm,
                 werkzeug.exceptions.NotFound,
             ),
         ):
             _logger.exception("Exception during JSON request handling.")
         error = {
             "code": 200,
             "message": "Openerp Server Error",
             "data": serialize_exception(exception),
         }
         if isinstance(exception, werkzeug.exceptions.NotFound):
             error["http_status"] = 404
             error["code"] = 404
             error["message"] = "404: Not Found"
         if isinstance(exception, AuthenticationError):
             error["code"] = 100
             error["message"] = "Openerp Session Invalid"
         if isinstance(exception, SessionExpiredException):
             error["code"] = 100
             error["message"] = "Openerp Session Expired"
         return self._json_response(error=error)
Beispiel #3
0
 def _handle_exception(self, exception):
     """Called within an except block to allow converting exceptions
        to arbitrary responses. Anything returned (except None) will
        be used as response."""
     try:
         return super(JsonRawRequest, self)._handle_exception(exception)
     except Exception:
         if not isinstance(
                 exception,
             (openerp.exceptions.Warning, SessionExpiredException)):
             _logger.exception("Exception during JSON request handling.")
         error = {
             'code': 200,
             'message': "Odoo Server Error",
             'data': serialize_exception(exception)
         }
         if isinstance(exception, AuthenticationError):
             error['code'] = 100
             error['message'] = "Odoo Session Invalid"
         if isinstance(exception, SessionExpiredException):
             error['code'] = 100
             error['message'] = "Odoo Session Expired"
         return self._json_response(error=error)
Beispiel #4
0
    def send_signed_xml(self, document_generic, raise_error=False):
        self.ensure_one()
        fname_signed_xml = str(self.env.user.id) + '_' + str(
            document_generic.invoice_id.ebi_voucher_type) + '_' + str(
                document_generic.invoice_id.id) + '_byuser_signed.xml'
        full_path_signed_xml = self._full_path(fname_signed_xml)

        REDIRECT_URI = self.mh_receipt_test_wsdl
        if self.environment == 'prod':
            REDIRECT_URI = self.mh_receipt_prod_wsdl

        token_cr = self.oaut2_autenthication_cr(document_generic)

        try:
            byt_file = False
            with open(full_path_signed_xml) as file:
                f = file.read()
                byt_file = bytearray(f)

            headers = {
                'Content-Type': 'application/json',
                'Authorization': "bearer " + token_cr
            }

            # date_doc = document_generic.invoice_id.date_invoice
            date_doc = document_generic.invoice_id.ebi_send_date
            date_convert = self.date_format_doc(date_doc)
            # print "fecha de doc", date_convert

            jsonString = {}
            jsonString['clave'] = document_generic.invoice_id.ebi_access_key
            jsonString['fecha'] = date_convert
            jsonString['emisor'] = {}
            jsonString['emisor'][
                'tipoIdentificacion'] = document_generic.invoice_id.company_id.partner_id.identification_type
            jsonString['emisor'][
                'numeroIdentificacion'] = document_generic.invoice_id.company_id.partner_id.identification_cr
            jsonString['receptor'] = {}
            jsonString['receptor'][
                'tipoIdentificacion'] = document_generic.invoice_id.identification_type
            jsonString['receptor'][
                'numeroIdentificacion'] = document_generic.invoice_id.identification_cr
            jsonString['comprobanteXml'] = base64.b64encode(byt_file)

            response = requests.post(REDIRECT_URI + 'recepcion',
                                     json=jsonString,
                                     headers=headers)
        except (Exception, ) as e:
            _logger.error(serialize_exception(e))
            _logger.info('Error %s' % str(e))
            raise UserError(_("A ocurrido un error enviando el xml "))

        print 'POST /service {}'.format(response.status_code)
        _logger.info('Respuesta Valiacion %s' % str(response))
        _logger.info('Contenido Respuesta Valiacion %s' %
                     str(response.content))

        # aqui poner exception que hubo error
        if response.status_code != 200:
            _logger.error(
                "---->A ocurrido un error enviando el comprobante: " +
                response.content)
            if response.status_code in [400, 401]:
                text_excp_ = str(response.headers._store['x-error-cause'][1])
                message_title = "ERROR"
                message_msg = text_excp_
                state = 'ERROR'
                res_id = document_generic.obj_id
                model_name = document_generic.obj_model
                sequence_msg = len(document_generic.env[model_name].browse(
                    res_id).ebi_messages_ids) + 1
                message_data = {
                    'title': message_title,
                    'message': message_msg,
                    'state': state,
                    'access_key': document_generic.mh_access_key,
                    'res_id': res_id,
                    'model_name': model_name,
                    'type': 'interno',
                    'sequence': sequence_msg,
                    'edig_id': document_generic.id,
                    'invoice_id': document_generic.invoice_id.id,
                }
                self.env['ebi.doc.message'].create(message_data)
                document_generic.message_post(body=message_title + ' - ' +
                                              message_msg)
                document_generic.invoice_id.message_post(body=message_title +
                                                         ' - ' + message_msg)
                return self.env['cr.wizard.message'].generated_message(
                    message_msg, name=message_title)
                # raise ValidationError(
                #     _("A ocurrido un error enviando el comprobante: ") + str(response.headers._store['x-error-cause'][1]))

            # if response.status_code in [202]:
            #     raise ValidationError(
            #         _("A ocurrido un error enviando el comprobante: ") + str(
            #             response.headers))
            if response.status_code not in [202]:
                text_excp_ = "Estado " + str(
                    response.status_code) + " - " + str(response.headers)
                message_title = "ERROR"
                message_msg = text_excp_
                state = 'ERROR'
                res_id = document_generic.obj_id
                model_name = document_generic.obj_model
                sequence_msg = len(document_generic.env[model_name].browse(
                    res_id).ebi_messages_ids) + 1
                message_data = {
                    'title': message_title,
                    'message': message_msg,
                    'state': state,
                    'access_key': document_generic.mh_access_key,
                    'res_id': res_id,
                    'model_name': model_name,
                    'type': 'interno',
                    'sequence': sequence_msg,
                    'edig_id': document_generic.id,
                    'invoice_id': document_generic.invoice_id.id,
                }
                self.env['ebi.doc.message'].create(message_data)
                document_generic.message_post(body=message_title + ' - ' +
                                              message_msg)
                document_generic.invoice_id.message_post(body=message_title +
                                                         ' - ' + message_msg)
                return self.env['cr.wizard.message'].generated_message(
                    message_msg, name=message_title)
                # raise ValidationError(
                #     _("A ocurrido un error enviando el comprobante: ") + str(response.headers))

        _logger.error("Respuesta " + ustr(response.content))

        _logger.info('LLAMANDO SERVICIO verificar estado %s' %
                     str(datetime.now()))
        count = 0
        timeout = False
        time.sleep(50L)
        response_query = self.query_cr(document_generic)
        if type(response_query) is dict:
            return dict(response_query)
        # print "respuesta del estado", response_query
        return response_query
    def _handle_exception(self, exception):
        """Format the errors to conform to GMC error types."""
        error = {
            'ErrorId': self.uuid,
            'ErrorTimestamp': self.timestamp,
            'ErrorClass': 'BusinessException',
            'ErrorRetryable': False,
            'ErrorModule': 'REST OnRamp',
            'ErrorSubModule': 'Rest OnRamp Authorization',
            'ErrorMethod': 'ValidateToken',
            'ErrorLoggedInUser': '',
            'RelatedRecordId': ''
        }
        try:
            super(JsonRequest, self)._handle_exception(exception)
        except werkzeug.exceptions.HTTPException:
            # General exception, send back the exception message
            error.update({
                'ErrorCode': exception.code,
                'ErrorCategory': 'CommunicationError',
                'ErrorMessage': exception.message,
                'description': exception.description,
            })
        except exceptions.AccessDenied:
            # Access error
            error.update({
                'ErrorCode': 401,
                'ErrorCategory': 'AuthorizationError',
                'ErrorMessage': '401 Unauthorized',
            })
        except AttributeError:
            # Raised if JSON could not be parsed or invalid body was received
            error.update({
                'ErrorCode': 400,
                'ErrorSubModule': 'Rest OnRamp Message Validation',
                'ErrorMethod': 'Message Validation',
                'ErrorCategory': 'InputValidationError',
                'ErrorMessage': exception.message,
            })
        except AuthenticationError:
            error.update({
                'ErrorCode': 401,
                'ErrorCategory': 'AuthenticationError',
                'ErrorMessage': 'Session Invalid',
            })
        except SessionExpiredException:
            error.update({
                'ErrorCode': 401,
                'ErrorCategory': 'AuthenticationError',
                'ErrorMessage': 'Session Expired',
            })
        except Exception:
            # Any other cases, lookup what exception type was raised.
            if not isinstance(exception, (exceptions.Warning)):
                _logger.exception("Exception during JSON request handling.")
            error.update({
                'ErrorCode': 500,
                'ErrorCategory': 'ApplicationError',
                'ErrorMessage': 'Odoo Server Error',
            })

        finally:
            ONRAMP_LOGGER.error(serialize_exception(exception))
            return self._json_response(error=error)
    def _handle_exception(self, exception):
        """Format the errors to conform to GMC error types."""
        error = {
            'ErrorId': self.uuid,
            'ErrorTimestamp': self.timestamp,
            'ErrorClass': 'BusinessException',
            'ErrorRetryable': False,
            'ErrorModule': 'REST OnRamp',
            'ErrorSubModule': 'Rest OnRamp Authorization',
            'ErrorMethod': 'ValidateToken',
            'ErrorLoggedInUser': '',
            'RelatedRecordId': ''
        }
        try:
            super(JsonRequest, self)._handle_exception(exception)
        except werkzeug.exceptions.HTTPException:
            # General exception, send back the exception message
            error.update({
                'ErrorCode': exception.code,
                'ErrorCategory': 'CommunicationError',
                'ErrorMessage': exception.message,
                'description': exception.description,
            })
        except exceptions.AccessDenied:
            # Access error
            error.update({
                'ErrorCode': 401,
                'ErrorCategory': 'AuthorizationError',
                'ErrorMessage': '401 Unauthorized',
            })
        except AttributeError:
            # Raised if JSON could not be parsed or invalid body was received
            error.update({
                'ErrorCode': 400,
                'ErrorSubModule': 'Rest OnRamp Message Validation',
                'ErrorMethod': 'Message Validation',
                'ErrorCategory': 'InputValidationError',
                'ErrorMessage': exception.message,
            })
        except AuthenticationError:
                error.update({
                    'ErrorCode': 401,
                    'ErrorCategory': 'AuthenticationError',
                    'ErrorMessage': 'Session Invalid',
                })
        except SessionExpiredException:
                error.update({
                    'ErrorCode': 401,
                    'ErrorCategory': 'AuthenticationError',
                    'ErrorMessage': 'Session Expired',
                })
        except Exception:
            # Any other cases, lookup what exception type was raised.
            if not isinstance(exception, (exceptions.Warning)):
                _logger.exception("Exception during JSON request handling.")
            error.update({
                'ErrorCode': 500,
                'ErrorCategory': 'ApplicationError',
                'ErrorMessage': 'Odoo Server Error',
            })

        finally:
            ONRAMP_LOGGER.error(serialize_exception(exception))
            return self._json_response(error=error)