Beispiel #1
0
    def __init__(self, bank_name='', bank=None):
        self.bank = bank or Bank.get(name=bank_name.title())
        if self.bank is None:
            raise ValueError('Bank not supported.')

        # Defining each bank parsing method
        if self.bank.name == 'Tangerine':
            """
            Tangerine CSV format:
            Transaction date,Transaction,Name,Memo,Amount
            """
            # 0-Date, 2-Description, 4-Amount
            self.description = lambda row: row[2]
            self.amount = lambda row: float(row[4] or '0')
            self.date = lambda row: self.format_date(row[0], '%m/%d/%Y')
            self.start_at = 1
            self.columns = 5

        elif self.bank.name == 'Desjardins':
            """
            Desjardins CSV format:
            https://www.desjardins.com/en/services_en_ligne/accesd_affaires/soutien/guiderel.pdf
            """
            # 3-Date, 5-Description, 6-Cheque #, 7-Withdrawal, 8-Deposit
            self.description = lambda row: row[5] + (' #' + row[6]
                                                     if row[6] else '')
            self.amount = lambda row: float(row[8] or '0') or -float(row[7] or
                                                                     '0')
            self.date = lambda row: self.format_date(row[3], '%Y/%m/%d')
            self.start_at = 0
            self.columns = 14

        else:
            raise ValueError('Bank not supported yet.')
Beispiel #2
0
def transactions_fetcher():
    truncate = lambda data, max: (data[:max - 3] + '...') if len(
        data) > max - 3 else data

    transactions_count = 0
    transactions = json.loads(request.form['transactions'])
    for transaction in transactions:
        try:
            # Getting fields
            attributes = {
                'user':
                g.user,
                'bank':
                Bank.get(name=transaction.get('bank')),
                'description':
                truncate(transaction.get('desc', ''), 256),
                'amount':
                float(transaction.get('amount', '0').replace(',', '.') or 0),
                'date':
                datetime.strptime(transaction.get('date'), '%d-%m-%Y')
                if transaction.get('date') else datetime.today()
            }
            # Fields validation
            if not attributes['description'] or not attributes['bank']:
                continue
            if attributes['date'] > datetime.today():
                attributes['date'] = datetime.today()
            # Trying to find a category
            category = Categorizer.find_category(attributes['description'])
            # Creating transaction
            db_transaction = Transaction.get(**attributes)
            if db_transaction is None:
                db_transaction = add_to_db(Transaction(), **attributes)
                transactions_count += 1
            # Finding or updating category
            if category is not None:
                db_transaction.category = category
                db_session.commit()
        except Exception as e:
            pass  # Skip this transaction

    return HttpResponse('Transactions fetched.', {'count': transactions_count},
                        status=200)
Beispiel #3
0
    def run(self, username, password, bank_name):

        try:
            bank = Bank.get(bank_name=bank_name)
        except Bank.DoesNotExist:
            raise Exception("no bank exists with this name")

        try:
            user = User.create_user(username, password)

        except IntegrityError as e:
            raise Exception("username is duplicate, please choose another")

        try:
            Customer.create(user=user, bank=bank)
            print("Welcome to virtual bank world ;)")
        except Exception as e:
            print(e)
            raise Exception('Some problem happened in creating customer')
Beispiel #4
0
def put_transactions(json_data, user):
    """Save a list of transactions into the database
    Args:
        json_data : str The json containing the bank and the transactions to add
        user : User The user to add to
    Returns:
        The number of transactions added
    """
    bank = Bank.get(name=json_data.get('bank'))
    if bank is None:
        raise ValueError('Bank not supported.')

    added_transactions = 0
    for t in json_data.get('transactions', []):
        transaction = set_attributes(Transaction(),
                                     user_id=user.user_id,
                                     bank_id=bank.bank_id)
        add_to_db(transaction, **t)
        added_transactions += 1

    return added_transactions
Beispiel #5
0
def upload_transactions():
    file = request.files.get('file')
    bank = Bank.get(bank_id=request.form.get('bank_id'))

    if bank is None:
        return HttpResponse("No bank was given.", status=400)
    # check if the post request has the file part
    if file is None or file.filename == '':
        return HttpResponse("No file was given.", status=400)

    if allowed_file(file.filename):
        filename = str(uuid.uuid4()) + os.path.splitext(
            secure_filename(file.filename))[1]
        relative_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        full_path = os.path.abspath(relative_path)
        # Saving file with unique name
        file.save(full_path)

        parsed = StatementParser(bank=bank).parse(full_path)
        if len(parsed['transactions']) > 0:
            added_transactions = put_transactions(parsed, g.user)

            transactions = Transaction.filter(user_id=g.user.user_id).order_by(
                Transaction.date.desc()).all()
            response = {
                "description": "Transactions uploaded.",
                "transactions": [t.as_dict() for t in transactions],
                "number": added_transactions
            }
            status = 200
        else:
            response = "No transactions found."
            status = 204

        os.remove(full_path)
        return HttpResponse(response, status=status)
    return HttpResponse("Error: Unauthorized file.", status=400)