Exemple #1
0
 def _check_simultaneous_edit(self):
     """Check if the user is working with stale data"""
     if self.request.method != 'PUT':
         return
     ui_dict = self.request.body
     model, key = None, None
     for key in ui_dict.iterkeys():
         model = to_class(key)
         break
     if not model or not key:
         return
     last_modified = ui_dict[key].get('last_modified')
     if not last_modified:
         return
     last_modified = datetime.strptime(last_modified, DATETIME_FORMAT)
     model_id = ui_dict[key]['id']
     with DatabaseAPI() as db_obj:
         obj = db_obj.get_obj(model, id=model_id)
         if not obj or not obj.last_modified or\
                 last_modified == obj.last_modified:
             return
         user = db_obj.get_obj(User, id=obj.last_modified_by)
         secs = (obj.last_modified - last_modified).total_seconds()
         raise SimultaneousEditError(
             'This %s has been modified by %s user %d seconds ago,'
             'please refresh before save' % (key, user.display_name, secs))
Exemple #2
0
 def fetch(id):
     """Fetches Account info"""
     with DatabaseAPI() as db_obj:
         account = db_obj.get_obj(Account, account_id=id)
     del account._sa_instance_state
     account = dict(account)
     return {'account': account}
Exemple #3
0
 def fetch_all(**query_params):
     """Fetches all Payees"""
     with DatabaseAPI() as db_obj:
         payees = db_obj.get_objs(Payee, **query_params)
         if payees:
             return {'payees': [dict(payee) for payee in payees]}
         else:
             return {'payees': []}
Exemple #4
0
 def fetch_all():
     """Fetches all Accounts info"""
     with DatabaseAPI() as db_obj:
         accounts = db_obj.get_objs(Account)
         if accounts:
             return {'accounts': [dict(account) for account in accounts]}
         else:
             return {'accounts': []}
Exemple #5
0
def import_tables():
    """Import all tables from pickle"""
    all_tables = set(Base.metadata.tables.keys())
    dependent = _find_related_tables()
    with DatabaseAPI() as db_obj:
        # Import independent tables first
        for tablename in all_tables - set(dependent):
            import_table(db_obj, to_class(tablename))
        for tablename in dependent:
            import_table(db_obj, to_class(tablename))
Exemple #6
0
 def fetch_all(**query_params):
     """Fetches all transactions"""
     with DatabaseAPI() as db_obj:
         transactions = db_obj.get_objs(Transaction, **query_params)
         if transactions:
             return {
                 'transactions':
                 [dict(transaction) for transaction in transactions]
             }
         else:
             return {'transactions': []}
Exemple #7
0
def insert_sequential(rows, model):
    """Non-bulk insert of rows"""
    for row in rows:
        with DatabaseAPI() as db_obj:
            try:
                db_obj.insert_or_update(model(**row))
            except IntegrityError:
                # TODO write error records to another file
                db_obj.db_session.rollback()
                logger.info(
                    "Skipping import of %s row: %s", model.__tablename__, row)
Exemple #8
0
def recreate_db():
    """Drop and create DB using latest model definitions"""
    logger.debug(db_settings)
    db_obj = MySQLConnection(**db_settings)
    db_obj.connect()
    cursor = db_obj.cursor()
    drop_all = "DROP DATABASE IF EXISTS %s;"
    logger.info('Dropping database')
    cursor.execute(drop_all % options.db_name)
    db_settings.update({'db': options.db_name})
    logger.info('Creating database')
    cursor.execute(
        """CREATE DATABASE IF NOT EXISTS %(db)s
           DEFAULT CHARACTER SET %(charset)s
           DEFAULT COLLATE %(collation)s;""" % db_settings)
    cursor.close()
    with DatabaseAPI() as db_api:
        db_api.create_tables()
Exemple #9
0
 def _update_username(resp):
     """Replace user id with user display name in the response dict"""
     if not resp:
         return
     key = resp.keys()[0]
     if not isinstance(resp[key], dict) or\
             not resp[key].get('last_modified_by'):
         return
     user_id = resp[key].get('last_modified_by')
     try:
         with DatabaseAPI() as db_obj:
             user = db_obj.get_obj(User, id=user_id)
             if not user:
                 return
             name = user.display_name if user.display_name else user.mail
             resp[key]['last_modified_by'] = name
     except Exception as e:
         logger.error(e.message, exc_info=True)
Exemple #10
0
 def create_or_edit(data, user, payee_id=None):
     """Creates or edits the Payee"""
     try:
         payee_info = data['payee_info']
     except Exception:
         raise InvalidInputError('Invalid Json')
     try:
         payee = Payee()
         payee.from_dict(payee_info)
         with DatabaseAPI() as db_obj:
             if payee_id:
                 payee.id = payee_id
                 payee_obj = db_obj.get_obj(Payee, payee_id)
             payee.user_id = user.id
             payee_id = db_obj.insert_or_update(payee, 'id')
             return {"payee": {"id": payee_id}}
     except Exception as e:
         raise DBOperationError(e.message)
Exemple #11
0
 def create_or_edit(data, user, account_id=None):
     """Create the account info"""
     try:
         account_info = data['account_info']
     except Exception:
         raise InvalidInputError('Invalid Json')
     try:
         account = Account()
         account.from_dict(account_info)
         with DatabaseAPI() as db_obj:
             if account_id:
                 account.id = account_id
                 account_obj = db_obj.get_obj(Account, account_id)
             account.user_id = user.id
             account.account_id = user.account_id
             account.account_name = user.user_name
             account_id = db_obj.insert_or_update(account, 'id')
             return {"account": {"id": account_id}}
     except Exception as e:
         raise DBOperationError(e.message)
Exemple #12
0
 def post(self):
     """User Registration"""
     user_info = self.request.body['user_info']
     with DatabaseAPI() as db_obj:
         user = db_obj.db_session.query(User). \
             filter(User.user_name == user_info['user_name']).first()
         if user:
             return {
                 "status": "error",
                 "error": 'This User already existed'
             }
         else:
             user = User()
         user.from_dict(user_info)
         user.password_hash = encode(ENCRYPTION_KEY, user_info['password'])
         user.transaction_password_hash = encode(
             ENCRYPTION_KEY, user_info['transaction_password'])
         counter = db_obj.db_session.query(Counter). \
             filter(Counter.name == User.__tablename__).first()
         if not counter:
             counter = Counter()
             counter.name = User.__tablename__
             # Account ID  starts from 100000
             counter.value = ACCOUNT_COUNTER_START
         user.account_id = str(BANK_CODE) + str(BRANCH_CODE) + str(
             counter.value)
         counter.value += 1
         db_obj.insert_or_update(counter)
         id = db_obj.insert_or_update(user, 'id')
         user.id = id
         account = Account()
         account.user_id = user.id
         account.account_id = user.account_id
         account.account_name = user.user_name
         account_id = db_obj.insert_or_update(account, 'id')
         resp = {"status": "ok", "user_info": dict(user)}
     return resp
Exemple #13
0
    def create_or_edit(data, user, transaction_id=None):
        """Make the Transaction"""
        try:
            transaction_info = data['transaction_info']
        except Exception:
            raise InvalidInputError('Invalid Json')
        try:
            transaction = Transaction()
            # transaction.from_dict(transaction_info)
            src_account_id = transaction_info.get('src_account_id')
            dst_account_id = transaction_info.get('dst_account_id', None)
            transaction_type = transaction_info['transaction_type']
            if transaction_type == 'Deposit':
                type = 'DEPOSITED'
            else:
                type = 'CREDITED'
            transaction_amount = float(transaction_info['amount'])
            description = transaction_info.get('description', '')
            with DatabaseAPI() as db_obj:
                if transaction_id:
                    transaction.id = transaction_id
                    transaction_obj = db_obj.get_obj(Transaction,
                                                     transaction_id)
                src_account_obj = db_obj.get_obj(Account,
                                                 account_id=src_account_id)
                if type == 'CREDITED':
                    transaction_password = transaction_info.get(
                        'transaction_password', None)
                    if transaction_password:
                        transaction_password_hash = encode(
                            settings.ENCRYPTION_KEY, transaction_password)
                        if user.transaction_password_hash != transaction_password_hash:
                            raise InvalidInputError(
                                'Invalid Transaction password')
                    else:
                        raise InvalidInputError(
                            'Transaction password is needed to withdraw and transfer money'
                        )
                    if transaction_amount > src_account_obj.balance:
                        raise InvalidInputError('Insufficient Balance')
                if transaction_type == 'ThirdParty':
                    if dst_account_id:
                        dst_account_obj = db_obj.get_obj(
                            Account, account_id=dst_account_id)
                        if not dst_account_obj:
                            raise InvalidInputError(
                                'Third Party payee account id is not existed')
                        src_account_obj.balance -= transaction_amount
                        dst_account_obj.balance += transaction_amount
                        description += ' Funds transfered to: ' + dst_account_id
                    else:
                        raise InvalidInputError(
                            'Third Party payee account id is needed to transfer money third party payee'
                        )
                elif type == 'DEPOSITED':
                    src_account_obj.balance += transaction_amount
                    description = "Deposited: " + description
                else:
                    src_account_obj.balance -= transaction_amount
                    description = "Credited: " + description

                transaction_id = random_with_N_digits(12)
                transaction.transaction_id = str(transaction_id)
                transaction.account_id = src_account_id
                transaction.type = type
                transaction.description = description
                transaction.amount = transaction_amount
                transaction.total = src_account_obj.balance

                db_obj.insert_or_update(src_account_obj)
                db_obj.insert_or_update(transaction)

                if transaction_type == 'ThirdParty':
                    db_obj.insert_or_update(dst_account_obj)
                    transaction_id = random_with_N_digits(12)
                    transaction.transaction_id = str(transaction_id)
                    transaction.account_id = dst_account_id
                    transaction.type = 'DEPOSITED'
                    transaction.description = transaction_info.get(
                        'description',
                        '') + ' Funds came from: ' + src_account_id
                    transaction.amount = transaction_amount
                    transaction.total = dst_account_obj.balance
                    db_obj.insert_or_update(transaction)
                return {"transaction": {"id": transaction_id}}
        except Exception as e:
            raise DBOperationError(e.message)
Exemple #14
0
 def delete(id):
     """Delete Account"""
     with DatabaseAPI() as db_obj:
         db_obj.del_obj(Account, account_id=id)
     return
Exemple #15
0
def export_tables():
    """Export all tables to a pickle"""
    with DatabaseAPI() as db_obj:
        for table in Base.metadata.tables.keys():
            export_table(db_obj, to_class(table))
Exemple #16
0
 def fetch(id):
     """Fetches transaction info"""
     with DatabaseAPI() as db_obj:
         transaction = db_obj.get_obj(Transaction, id=id)
     return {'transaction': dict(transaction)}
Exemple #17
0
 def delete(id):
     """Delete Payee"""
     with DatabaseAPI() as db_obj:
         db_obj.del_obj(Payee, id=id)
     resp = {"status": "ok"}
     return resp
Exemple #18
0
 def delete(id):
     """Delete Transaction info"""
     with DatabaseAPI() as db_obj:
         db_obj.del_obj(Transaction, id=id)
     resp = {"status": "ok"}
     return resp
Exemple #19
0
 def fetch(id):
     """Fetches Payee info"""
     with DatabaseAPI() as db_obj:
         payee = db_obj.get_obj(Payee, id=id)
     return {'payee': dict(payee)}