Exemplo n.º 1
0
def create_account():
    """
        Add an account with a user id

        :rtype: dict | bytes
    """
    code = HTTPStatus.CREATED
    aux = Auxiliar()
    msg = Message()

    user = Account.query.filter_by(user_id=request.json.get('user_id')).first()
    if not user:
        try:
            # Get parameters
            user_id = request.json.get('user_id')
            password = request.json.get('password')
            currency = request.json.get('currency').upper()

            # Validate the parameters
            if not isinstance(Currency(currency), Currency):
                code = HTTPStatus.BAD_REQUEST
                response = {
                    'status':
                    'fail',
                    'message':
                    "Currency's wrong. Use the international standard that defines three-letter codes as "
                    "currencies established by the International Organization. (ISO 4217)"
                }
            else:
                # Save the account
                ac = Account(user_id=user_id,
                             password=password,
                             currency=Currency(currency))
                ac.save_to_db()

                response = {
                    'status': 'success',
                    'account': {
                        'id': ac.id,
                        'user': ac.user_id,
                        'password': ac.password,
                        'currency': ac.currency.name,
                        'balance': ac.balance,
                        'state': 'active' if ac.state else 'desactive',
                        'created_at': ac.created_at,
                        'updated_at': ac.updated_at
                    }
                }
        except Exception as exc:
            code = HTTPStatus.INTERNAL_SERVER_ERROR
            response = {'status': 'fail', 'message': str(exc)}
    else:
        code = HTTPStatus.ACCEPTED
        response = {
            'status': 'fail',
            'message': 'User already exists. Please Log in'
        }

    # Return the information
    return msg.message(code, response)
Exemplo n.º 2
0
def initialize_database():

    ac = Account(user_id='transdev', password='******', currency=Currency('EUR'))
    ac.save_to_db()

    ac = Account(user_id='cp', password='******', currency=Currency('EUR'))
    ac.save_to_db()

    ac = Account(user_id='metro', password='******', currency=Currency('EUR'))
    ac.save_to_db()
Exemplo n.º 3
0
    def __init__(
        self,
        keystore,
        resource,
        alias,
        amount,
        lang="en",
        currency='KWD',
        tracking_id=None,
    ):

        self.lang = LANG_LOOKUP.get(lang, 'USA')
        self.currency = Currency(currency).number
        self.amount = amount

        # Configure the terminal settings
        terminal_configuration = read_resource_file(resource, keystore, alias)
        root = ET.fromstring(terminal_configuration)
        terminal = {c.tag: c.text for c in root}

        self.password = terminal["password"]
        self.key = terminal["resourceKey"]
        self.portal_id = terminal["id"]
        self._pgw_url = terminal["webaddress"]

        if tracking_id is None:
            now = int(time.time())
            self.tracking_id = f"{now}"

        # Setting these as private, since we will manipulate the values
        # and sanitize them before setting the final value

        self._udf1 = self._udf2 = self._udf3 = self._udf4 = self._udf5 = ""
        self._response_url = None
        self._error_url = None
 def _validate_currency(self):
     """
         The invoice base currency will be in ISO4217 alphabetic code format e.g. NZD
     """
     currency = self.input_data['invoice']['currency']
     try:
         currency_obj = Currency(currency)
     except:
         print('Error: invalid currency code \n')
         sys.exit(4)
 def _validate_input_invoice_lines_currency_valid(self):
     """
         Each invoice line should include a valid currency code
     """
     for line in self.input_data['invoice']['lines']:
         try:
             line_currency = line['currency']
             line_currency_obj = Currency(line_currency)
         except:
             print('Error: invalid currency code in a line \n')
             sys.exit(6)
Exemplo n.º 6
0
 def _amount_to_int(amount: str, currency: str) -> int:
     try:
         iso_currency = Currency(currency.upper())
         amount_flt = Decimal(amount.replace(",", "."))
         amount_flt = amount_flt * pow(10, iso_currency.exponent)
         if amount_flt % 1 > 0:
             raise PaymentAmountInvalidException("The provided amount has too many decimal places.")
         return int(amount_flt)
     except ValueError:
         logging.warning("`{}` currency has not been recognized. Make sure the provided value is correct.".format(currency))
         return int(amount)
Exemplo n.º 7
0
 def validate(self):
     errors = []
     if not CC.__contains__(self.country):
         errors.append(ERRORS["wrong_country_iso"])
     if not self.name:
         errors.append(ERRORS["wrong_bank_name"])
     if not self.pageurl:
         errors.append(ERRORS["empty_url"])
     if not validators.url(self.pageurl):
         errors.append(ERRORS["bank_url_error"])
     if not self.unit == "M100" and not self.unit == "exchange100" and not self.unit == "exchange" \
             and not self.unit == "percentage":
         errors.append(ERRORS["wrong_unit"])
     try:
         Currency(self.fromCurrency)
     except:
         errors.append(ERRORS["wrong_from_currency"])
     try:
         lxml.etree.XPath(self.toCurrencyXpath)
     except:
         errors.append(ERRORS["to_currency_xpath"])
     try:
         lxml.etree.XPath(self.buyxpath)
     except:
         errors.append(ERRORS["buy_exchange_xpath"])
     try:
         lxml.etree.XPath(self.toCurrencyXpath)
     except:
         errors.append(ERRORS["sell_exchange_xpath"])
     if errors:
         error_message = {"errors": errors}
         return Response(response=json.dumps(error_message),
                         status=400,
                         mimetype='application/json')
     else:
         return None
Exemplo n.º 8
0
def create_payment(account_id):
    """
        Make a payment

        :rtype: dict | bytes
    """

    code = HTTPStatus.CREATED
    aux = Auxiliar()
    msg = Message()

    account = Account.query.filter_by(id=account_id).first()

    if account:
        try:
            # Get parameters
            request_id = request.json.get('request_id')
            seller_id = uuid.UUID(uuid.UUID(request.json.get('seller_id')).hex) 
            currency = request.json.get('currency').upper()
            reference = request.json.get('reference')

            # Check if there is some missing argument
            if not request_id or not seller_id or not currency or not reference:
                code = HTTPStatus.BAD_REQUEST
                response = {
                    'status': 'fail',
                    'message': 'Missing arguments.'
                }
                return msg.message(code, response)

            # Flag to check if account exists
            receiver = Account.query.get(seller_id)

            # Validate parameters
            if not aux.validate_uuid(seller_id) or not receiver:
                code = HTTPStatus.BAD_REQUEST
                response = {
                    'status': 'fail',
                    'message': 'The number receiver account is wrong or they dont exist.'
                }
                return msg.message(code, response)

            # Check if the currency is valid
            if not isinstance(Currency(currency), Currency):
                code = HTTPStatus.BAD_REQUEST
                response = {
                    'status': 'fail',
                    'message': 'Your currency is wrong. Uses the international standard that defines three-letter "\
                                "codes as currencies established by the International Organization. (ISO 4217).'
                }
                return msg.message(code, response)

        except Exception as exc:
            code = HTTPStatus.INTERNAL_SERVER_ERROR
            response = {
                'status': 'fail',
                'message': str(exc)
            }

        # Save the new payment
        # Everytime that we create a payment, his state is "pending"
        payment = Payment(request_id, account.id, seller_id, Currency(currency), reference)
        payment.save_to_db()

        response = {
            'status': 'success',
            'id': payment.id
        }
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }        

    return msg.message(code, response)
Exemplo n.º 9
0
def currency_converter(request):
    """
    Currency coversion view

    @params base_currency: ISO4217 currency code
    @params target_currency: ISO4217 currency code
    @params amount: Float

    @returns coverted currency data in json
    @error return BadRequest with error message
    """

    # Get all params
    base_currency = request.GET.get("base_currency", '').upper().strip()
    target_currency = request.GET.get("target_currency", '').upper().strip()
    amount = request.GET.get("amount", '')
    # All params are mandatory
    if not all([base_currency, target_currency, amount]):
        return HttpResponseBadRequest("Payload missing")
    try:
        # check for ISO4217 validation
        base_currency = Currency(base_currency)
        target_currency = Currency(target_currency)
    except Exception as e:
        return JsonResponse(status=400,
                            data={
                                'status': 'false',
                                'message': str(e)
                            })
    try:
        # Amount should be in int or float
        amount = float(amount)
    except:
        message = "{} Not a valid amount".format(amount)
        return JsonResponse(status=400,
                            data={
                                'status': 'false',
                                'message': message
                            })

    # Lets scrape result
    url = "https://www.exchange-rates.org/converter/{}/{}/{}".format(
        base_currency.code, target_currency.code, amount)
    headers = {
        'Accept':
        '*/*',
        'Accept-Language':
        'en-US,en;q=0.5',
        'Connection':
        'keep-alive',
        'User-Agent':
        'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0'
    }

    response = requests.get(url, headers=headers, timeout=5)
    if response.status_code != 200:
        # Oops, they might have blocked
        return JsonResponse(status=400,
                            data={
                                'status': 'false',
                                'message': "Unable to scrape"
                            })
    soup = BeautifulSoup(response.content, 'html.parser')
    try:
        # Get the conversion rate
        value = float(
            soup.select('span[id*="ToAmount"]')[0].text.replace(",", ""))
        return JsonResponse(status=200,
                            data={
                                'status': 'true',
                                'message': value
                            })
    except Exception as e:
        return JsonResponse(status=400,
                            data={
                                'status': 'false',
                                'message': str(e)
                            })
Exemplo n.º 10
0
 def __verify_currency(currency):
     currency = str(currency).upper()
     Currency(currency)
     return currency