Ejemplo 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)
Ejemplo n.º 2
0
def logout(account_id):
    """
        Logout Resource
    """
    # get auth token
    code = HTTPStatus.OK
    msg = Message()

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

    if account:
        if account.state:
            active = Active_Sessions.query.filter_by(
                user_id=account.user_id).first()

            if active:
                Active_Sessions.query.filter(
                    Active_Sessions.user_id == account.user_id).delete()
                response = {
                    'status': 'success',
                    'message': 'Successfully logged out.'
                }
        else:
            code = HTTPStatus.UNAUTHORIZED
            response = {
                'status': 'fail',
                'message': 'Yout account is desactivated'
            }
        return msg.message(code, response)
    else:
        code = HTTPStatus.FORBIDDEN
        response = {'status': 'fail', 'message': 'Provide a valid auth token.'}
        return msg.message(code, response)
Ejemplo n.º 3
0
def desativate_account(account_id):
    """
        Desactivate the user account

        :rtype: dict | bytes    
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:
        if account.state:
            account.state = False
            db.session.commit()

            response = {
                'status': 'success',
                'message': 'Successfully desactivated.',
            }
        else:
            code = HTTPStatus.NOT_MODIFIED
            response = {
                'status': 'fail',
                'message': 'The account is already desactivated'
            }
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {'status': 'fail', 'message': 'Try Again.'}

    return msg.message(code, response)
Ejemplo n.º 4
0
def account_info(account_id):
    """
        Get the account information

        :rtype: dict | bytes (with the Transaction)
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:
        response = {
            'status': 'success',
            'account': {
                'id': account.id,
                'user': account.user_id,
                'balance': account.balance,
                'currency': account.currency.name,
                'state': 'active' if account.state else 'desactive',
                'created_at': account.created_at,
                'updated_at': account.updated_at
            }
        }
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {'status': 'fail', 'message': 'Try Again.'}

    return msg.message(code, response)
Ejemplo n.º 5
0
def authorize_response(payment_id):
    code = HTTPStatus.OK
    msg = Message()

    try:

        payment = Payment.query.get(payment_id)

        if payment.state != PaymentState("requested"):
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'You dont have any authorization request.'
            }
            return msg.message(code, response)

        payment.update_state("authorized")

        transactions = Transaction.query.filter_by(id_payment=payment_id)

        for t in transactions:
            t.update_state("authorized")

        response = {
            'status': 'success',
            'message': 'Your payment was authorized.'
        }

    except Exception as exc:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': str(exc)
        }
    return msg.message(code, response)
Ejemplo n.º 6
0
def authorize(payment_id):
    code = HTTPStatus.OK
    msg = Message()

    try:

        payment = Payment.query.filter_by(id=payment_id).first()
        account_buyer = Account.query.filter_by(id=payment.account_id).first()
        account_seller = Account.query.filter_by(id=payment.receiver_id).first()

        payment_data = {
            'id': payment.id,
            'buyer_user_id': str(account_buyer.user_id),
            'buyer': str(account_buyer.id),
            'seller_user_id': str(account_seller.user_id),
            'seller': str(account_seller.id),
            'created_at': payment.created_at,
            'state': payment.state.name,
            'amount': payment.amount,
            'currency': payment.currency.name,
            'reference': payment.reference
        }

        transactions = Transaction.query.filter_by(id_payment=payment_id)

        data = []
        for transaction in transactions:
            transaction_data = {
                'amount': transaction.amount,
                'emission_date': transaction.emission_date.date(),
                'emission_time': transaction.emission_date.strftime("%H:%M:%S"),
                'state': transaction.state.name,
                'update_date': transaction.update_date,
                'reference': transaction.reference
            }
            data.append(transaction_data)

        if payment.state == PaymentState("requested"):
            return render_template('index.html', payment=payment_data, transactions=data)
        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'You dont have any authorization request.'
            }

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

    return msg.message(code, response)
Ejemplo n.º 7
0
def add_amount(account_id):
    """
        Add an amount to an account

        :rtype: dict | bytes
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:

        if account.state:
            try:
                # Get parameters
                amount = request.json.get('amount')

                # Validate the parameters
                if not isinstance(float(amount), float):
                    code = HTTPStatus.BAD_REQUEST
                    raise Exception(
                        "Your amount is wrong. The amount is not valid")

                elif float(amount) < 0.0:
                    code = HTTPStatus.BAD_REQUEST
                    raise Exception(
                        "Your amount is wrong. The amount needs to be more than 0.0"
                    )
            except Exception as excep:
                response = {'status': 'fail', 'message': str(excep)}

            # Update the total amount in his account
            account.balance += amount
            db.session.commit()

            response = {
                'status': 'success',
                'message': 'The amount was added.'
            }

        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }
        return msg.message(code, response)
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {'status': 'fail', 'message': 'Try Again.'}

    return msg.message(code, response)
Ejemplo n.º 8
0
def get_payments(account_id):
    """
        Get the payments from an User

        :rtype: dict | bytes    
    """    

    code = HTTPStatus.OK
    msg = Message()

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

    if account:
        try:
            payments = Payment.query.filter_by(account_id=account.id)

            data = []
            for payment in payments:
                payment_data = {
                    'id': payment.id,
                    'request': payment.request_id,
                    'seller': payment.receiver_id,
                    'created_at': payment.created_at,
                    'state': payment.state.name,
                    'amount': payment.amount,
                    'currency': payment.currency.name,
                    'reference': payment.reference
                }
                data.append(payment_data)

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

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

    return msg.message(code, response)
Ejemplo n.º 9
0
def get_trans():
    msg = Message()
    transdev_account = Account.find_by_id("transdev")
    cp_account = Account.find_by_id("cp")
    metro_account = Account.find_by_id("metro")

    response = {
        'status': 'success',
        'carriers': {
            'Transdev': transdev_account.id,
            'CP': cp_account.id,
            'metro': metro_account.id
        }
    }
    return msg.message(HTTPStatus.OK, response)
Ejemplo n.º 10
0
def test_connection():
    msg = Message()
    response = {'status': 'success'}
    return msg.message(HTTPStatus.OK, response)
Ejemplo n.º 11
0
def get_transaction(account_id, payment_id, transaction):
    """
        Find transactions from payment by ID

        :param account_id: Account id
        :type account_id: uuid
        :param payment_id: Id of the payment associated
        :type payment_id: uuid
        :param transaction: A specific transaction of a payment
        :type transaction: uuid

        :rtype: dict | bytes (with the Transaction)
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:
        
        if account.state:
            try:
                payment = Payment.query.get(payment_id)

                # Check if payments exists
                if not payment:
                    code = HTTPStatus.NOT_FOUND
                    response = {
                        'status': 'fail',
                        'message': "Payment not found"
                    }
                    return msg.message(code, response)

                transaction = Transaction.query.get(transaction)

                response = {
                    'status': 'success',
                    'transaction':
                    {
                        'id': transaction.id,
                        'amount': transaction.amount,
                        'emission_date': transaction.emission_date,
                        'state': transaction.state.name,
                        'update_date': transaction.update_date,
                        'id_payment': transaction.id_payment
                    }
                }
            except Exception as excep:
                code = HTTPStatus.INTERNAL_SERVER_ERROR
                response = {
                    'status': 'fail',
                    'message': str(excep)
                }
        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }  
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }
    return msg.message(code, response)
Ejemplo n.º 12
0
def login():
    """
        User Login Resource
    """
    code = HTTPStatus.OK
    msg = Message()

    user = Account.query.filter_by(user_id=request.json.get('user_id')).first()
    print(user)
    if user:
        try:
            # Get parameters
            user_id = request.get_json()['user_id']
            password = request.get_json()['password']

            # fetch the user data
            current_user = Account.find_by_id(user_id=user_id)

            if not current_user:
                code = HTTPStatus.NOT_FOUND
                response = {
                    'status': 'fail',
                    'message': 'User {} doesn\'t exist'.format(user_id)
                }

            if Account.check_password_hash(current_user.password, password):

                with_token = Active_Sessions.query.filter_by(
                    user_id=user_id).first()
                if with_token is None:
                    auth_token = Account.encode_auth_token(current_user.id)
                    # mark the token into Active_Sessions
                    active_session = Active_Sessions(token=auth_token,
                                                     user_id=user_id)
                    active_session.save_to_db()

                    if auth_token:
                        response = {
                            'status': 'success',
                            'message': 'Successfully logged in.',
                            'auth_token': auth_token.decode()
                        }
                else:
                    auth_token = with_token.token

                    if auth_token:
                        response = {
                            'status':
                            'success',
                            'message':
                            'Successfully logged in.',
                            'auth_token':
                            auth_token.replace("b\'", "").replace("\'", "")
                        }

            else:
                code = HTTPStatus.BAD_REQUEST
                response = {'status': 'fail', 'message': 'Wrong Credentials'}

        except Exception as e:
            code = HTTPStatus.INTERNAL_SERVER_ERROR
            response = {'status': 'fail', 'message': str(e)}
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {'status': 'fail', 'message': 'Something is wrong'}
    return msg.message(code, response)
Ejemplo n.º 13
0
def authorization_payment(account_id, payment_id):
    """
        Authorization the payment

        :param account_id: Account id
        :type : uuid
        :param payment_id: Id of the payment
        :type payment_id: int

        :rtype: dict | bytes
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:

        if account.state:
            try:
                payment = Payment.query.get(payment_id)

                # Check if payments exists
                if not payment:
                    code = HTTPStatus.NOT_FOUND
                    response = {
                        'status': 'fail',
                        'message': "Payment not found"
                    }
                    return msg.message(code, response)

                if payment.state == PaymentState("completed"):
                    code = HTTPStatus.CONFLICT
                    response = {
                        'status': 'fail',
                        'message': "The payment is already completed"
                    }
                    return msg.message(code, response)

                if payment.state == PaymentState("pending"):
                    payment.update_state("requested")

                response = {
                    'status': 'success',
                    'payment': payment_id,
                    'message': 'http://192.168.85.208/payments/'+str(payment_id)+'/authorize/request'
                }

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

        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }  
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }

    return msg.message(code, response)
Ejemplo n.º 14
0
def execute(account_id, payment_id):
    """
        Execute payment by ID

        :param account_id: Account id
        :type account_id: uuid
        :param payment_id: Id of the payment to be executed
        :type payment_id: uuid

        :rtype: dict | bytes
    """

    code = HTTPStatus.OK
    msg = Message()

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

    if account:

        if account.state:
            try:

                payment = Payment.query.get(payment_id)

                # Check if payments exists
                if not payment:
                    code = HTTPStatus.NOT_FOUND
                    response = {
                        'status': 'fail',
                        'message': "Payment not found"
                    }
                    return msg.message(code, response)

                if payment.state == PaymentState("completed"):
                    code = HTTPStatus.CONFLICT
                    response = {
                        'status': 'fail',
                        'message': "The payment is already completed"
                    }
                    return msg.message(code, response)

                if payment.state == PaymentState("authorized"):

                    transactions = Transaction.query.filter_by(id_payment=payment_id, state="created")

                    total = 0.0

                    for t in transactions:
                        t.state = "completed"
                        total += t.amount

                    try:

                        # Check if he is enough money to pay
                        if total > account.balance:
                            code = HTTPStatus.NOT_ACCEPTABLE
                            response = {
                                'status': 'fail',
                                'message': "The account does not have enough available amount"
                            }
                            return msg.message(code, response)

                        seller = Account.query.get(payment.receiver_id)
                        seller.balance += total

                        account.balance -= total
                        payment.state = PaymentState("completed")

                        response = {
                            'status': 'success',
                            'message': 'The payment was executed'
                        }
                    except Exception as exc:
                        code = HTTPStatus.INTERNAL_SERVER_ERROR
                        response = {
                            'status': 'fail',
                            'message': str(exc)
                        }
                else:
                    code = HTTPStatus.METHOD_NOT_ALLOWED
                    response = {
                        'status': 'fail',
                        'message': 'Payment not authorized.'
                    }
            except Exception as exc:
                code = HTTPStatus.INTERNAL_SERVER_ERROR
                response = {
                    'status': 'fail',
                    'message': str(exc)
                }
        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }

    return msg.message(code, response)
Ejemplo n.º 15
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)
Ejemplo n.º 16
0
def cancel_transaction(account_id, payment_id, transaction):
    """
        Cancel transaction from payment by the ID of the transaction

        :param account_id: Account id
        :type account_id: uuid
        :param payment_id: Id of the payment
        :type payment_id: uuid
        :param transaction: Id of the transaction
        :type transaction: uuid

        :rtype: dict | bytes
    """

    code = HTTPStatus.OK
    msg = Message()

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

        if account:
            if account.state:
                try:

                    payment = Payment.query.get(payment_id)

                    # Check if payments exists
                    if not payment:
                        code = HTTPStatus.NOT_FOUND
                        response = {
                            'status': 'fail',
                            'message': "Payment not found"
                        }
                        return msg.message(code, response)

                    transaction = Transaction.query.get(transaction)

                    # Check if transaction exists
                    if not transaction:
                        code = HTTPStatus.NOT_FOUND
                        response = {
                            'status': 'fail',
                            'message': "Transaction not found"
                        }
                        return msg.message(code, response)

                    if transaction.state == PaymentState("completed"):
                        code = HTTPStatus.CONFLICT
                        response = {
                            'status': 'fail',
                            'message': "The transaction is already completed, you cannot cancel"
                        }
                        return msg.message(code, response)

                    # Calculate the amount that will no longer be included in the final payment
                    diff = payment.amount - transaction.amount

                    payment.amount -= diff

                    # The transaction was cancelled
                    transaction.state = PaymentState("cancelled")

                    response = {
                        'status': 'success',
                        'message': 'The transaction '+str(transaction.id)+' was cancelled'
                    }

                except Exception as exc:
                    response = {
                        'status': 'fail',
                        'message': str(exc)
                    }
            else:
                code = HTTPStatus.METHOD_NOT_ALLOWED
                response = {
                    'status': 'fail',
                    'message': 'Your number account is desactivated.'
                }
        else:
            code = HTTPStatus.INTERNAL_SERVER_ERROR
            response = {
                'status': 'fail',
                'message': 'Try Again.'
            }
    except Exception as err:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': str(err)
        }
    return msg.message(code, response)
Ejemplo n.º 17
0
def create_transaction(account_id, payment_id):
    """
        Add transaction to payment by ID

        :param account_id: Account id
        :type account_id: uuid
        :param payment_id: Id of the payment to be associated
        :type payment_id: uuid

        :rtype: dict | bytes (Transaction details)
    """

    code = HTTPStatus.CREATED
    msg = Message()

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

    if account:
        
        if account.state:
            try:
                amount = request.json.get('amount')
                reference = request.json.get('reference')

                # Check if missing arguments
                if not amount or not reference:
                    code = HTTPStatus.BAD_REQUEST
                    response = {
                        'status': 'fail',
                        'message': "The amount or reference values is missing"
                    }
                    return msg.message(code, response)

                payment = Payment.query.get(payment_id)

                # Check if payments exists
                if not payment:
                    code = HTTPStatus.NOT_FOUND
                    response = {
                        'status': 'fail',
                        'message': "Payment not found"
                    }
                    return msg.message(code, response)

            except Exception as excep:
                return msg.message(code, str(excep))

            # Create a transaction
            transaction = Transaction(amount, payment_id, reference)
            transaction.save_to_db()

            payment.amount += amount

            response = {
                'status': 'success',
                'id': transaction.id
            }                
        else:
            code = HTTPStatus.METHOD_NOT_ALLOWED
            response = {
                'status': 'fail',
                'message': 'Your number account is desactivated.'
            }  
    else:
        code = HTTPStatus.INTERNAL_SERVER_ERROR
        response = {
            'status': 'fail',
            'message': 'Try Again.'
        }

    return msg.message(code, response)