def test_init(self): # If no parameters are provided with self.assertRaises(TypeError): exp3 = Expense() # If the cost is negative with self.assertRaises(ValueError): exp3 = Expense("Bag", -2)
def get_recent_expenses(self, lookback=5): """ Returns a list of Expense Class instances for the past {lookback} expenses""" cursor = self.conn.execute( 'SELECT * FROM expenses ORDER BY date DESC, id DESC') try: return [Expense(e) for e in cursor.fetchall()[:lookback]] except IndexError: # If lookback > length of recorded expenses return [Expense(e) for e in cursor.fetchall()]
def init_repo(self): self.__repo.add_item(Expense(1, 10, 'food')) self.__repo.add_item(Expense(1, 120, 'internet')) self.__repo.add_item(Expense(1, 112, 'food')) self.__repo.add_item(Expense(4, 20, 'food')) self.__repo.add_item(Expense(4, 100, 'electricity')) self.__repo.add_item(Expense(6, 980, 'phone')) self.__repo.add_item(Expense(8, 1, 'food')) self.__repo.add_item(Expense(8, 16, 'food')) self.__repo.add_item(Expense(23, 100, 'food')) self.__repo.add_item(Expense(30, 233, 'gas'))
def add_expense(self, username): amount, category_name, date = self.gather_info(category_type='expense') new_expense = Expense(amount, category_name, date) self.aggregated_object.expenses_list.append(new_expense) if date not in self.aggregated_object.dates_list: self.aggregated_object.dates_list.append(date) self.aggregated_object.save_changes(username)
def read_expense(): day, amount, type = input('Input expense: <day> <money_amount> <type>\n').split(' ') day = int(day) amount = int(amount) expense = Expense(day, amount, type) return expense
def add_expense(): """ Adding expenses to the .csv file and the ListBox """ if name_field.get() == "" or cost_field.get() == "": error_message("You haven't entered any data!") try: # If the user tries to enter something else than a number cost = int(cost_field.get()) name = name_field.get() # Storing the name value temp_exp = Expense(name, cost) except ValueError: clear_entry() # Clearing the entry fields temp_exp = None error_message("You need to enter a number!") if temp_exp: """ If temp_exp is not None """ with open("data.csv", "a", newline='') as csv_file: """ Writing to the .csv file """ dict_writer = csv.DictWriter(csv_file, fieldnames=['name', 'cost']) dict_writer.writerow({ 'name': temp_exp.name, 'cost': temp_exp.cost }) expense_list.insert(tk.END, f"{temp_exp.name} - {temp_exp.cost}") clear_entry() # Clears entry fields exp.append(temp_exp) # Adding expense to expense list total_cost(exp) # Updating the total cost
def preload_list(self): ''' Preloads the liist with 10 predefined expenses Input: - Output: - ''' self.add_expense(Expense(1, 5, "cloathing")) self.add_expense(Expense(30, 10, "food")) self.add_expense(Expense(2, 15, "housekeeping")) self.add_expense(Expense(29, 20, "internet")) self.add_expense(Expense(3, 25, "others")) self.add_expense(Expense(28, 30, "transport")) self.add_expense(Expense(4, 35, "others")) self.add_expense(Expense(27, 40, "internet")) self.add_expense(Expense(5, 45, "housekeeping")) self.add_expense(Expense(26, 50, "food"))
def preload_list(self): ''' Preloads the liist with 10 predefined expenses Input: - Output: - ''' self.add_expense(Expense(5, constants.CATEGORY_CLOATHING, 1)) self.add_expense(Expense(10, constants.CATEGORY_FOOD, 31)) self.add_expense(Expense(15, constants.CATEGORY_HOUSEKEEPING)) self.add_expense(Expense(20, constants.CATEGORY_INTERNET, 28)) self.add_expense(Expense(25, constants.CATEGORY_OTHERS, 29)) self.add_expense(Expense(30, constants.CATEGORY_TRANSPORT)) self.add_expense(Expense(35, constants.CATEGORY_OTHERS, 30)) self.add_expense(Expense(40, constants.CATEGORY_INTERNET, 12)) self.add_expense(Expense(45, constants.CATEGORY_HOUSEKEEPING)) self.add_expense(Expense(50, constants.CATEGORY_FOOD, 4))
def from_file(self, file, conn): # Loads previous expenses from a specified .txt file expenses = database.fetch_all(conn) for i in expenses: temp = Expense(i[2]) temp.date = datetime.strptime(i[3], '%Y-%m-%d').date() temp.currency = i[1] self.expense_list.append(temp)
def csv_to_list(exp): """ Fills the list on startup """ with open("data.csv") as csv_file: reader = csv.DictReader(csv_file, fieldnames=['name', 'cost']) for row in reader: """ Fills both the ListBox and the expense list """ expense_list.insert(tk.END, f"{row['name']} - {row['cost']}") exp.append(Expense(row['name'], int(row['cost'])))
def get_expenses(self): sql = f"SELECT * FROM {self.table_name};" self.cursor.execute(sql) entries = [] for entry in self.cursor: entries.append(Expense(entry[0], entry[2], entry[3], entry[4])) print(f"Found {len(entries)} entries in database.") return entries
def add(self, params): ''' Adds to list an expense Input: list - params from input Output: string - in case of error ''' cost_string = params[0] category = params[1] self.validator.validate_add(cost_string, category) cost = int(cost_string) self.add_expense(Expense(cost, category))
def insert(self, params): ''' Adds to list an expense with a specified day Input: list - params from input Output: string - in case of error ''' day_string = params[0] cost_string = params[1] category = params[2] self.validator.validate_insert(day_string, cost_string, category) day = int(day_string) cost = int(cost_string) self.add_expense(Expense(cost, category, day))
def add(self, params): ''' Adds to list an expense Input: list - params from input Output: Error - in case of error ''' day_string = params[0] cost_string = params[1] category = params[2] self.validator.validate_add(day_string, cost_string, category) day = int(day_string) cost = int(cost_string) self.add_expense(Expense(day, cost, category))
def add_expense(): token = request.headers.get('Authorization') if token is None: return make_response( jsonify({ 'success': False, 'error': 'No Auth Token' }), 400) else: db = Database() user_id = AuthSystem.validate_token(token) query = {'_id': user_id} user = db.findUser(query) if user: expense = request.json user = User.from_dict(user) for category in user.getUserCategories(): if category.name == expense['expenseCategory']: category.addExpense( Expense(expense['item'], expense['amount'], expense['date'], expense['expenseCategory'])) user.updateTotalExpenses(expense['amount']) break user_dict = user.as_dict() updates = { 'categories': user_dict['categories'], 'totalExpenses': user_dict['totalExpenses'] } did_update = db.updateUser(query, updates) if did_update: return make_response(jsonify({'success': True}), 201) else: return make_response( jsonify({ 'success': False, 'error': 'Failed to update User!' }), 304) else: return make_response( jsonify({ 'success': False, 'error': 'User not found!' }), 404)
def add_expenses(self, expenses, date): for expense in expenses: new_expense = Expense(expense['amount'], expense['category'], date) self.expenses_list.append(new_expense) self.expense_categories.append(new_expense.name)
while login_window.sign_up: sign_up_window = SignUp() if not sign_up_window.is_closed: username = sign_up_window.username password = sign_up_window.password connection = database.connect() database.add_user(connection, username, password) login_window = LogIn() if login_window.is_closed: is_true = False if login_window.create_homepage: homepage_window = HomePage(login_window.table_name) while not homepage_window.is_closed: if homepage_window.expense: expense_window = Expense(login_window.table_name) homepage_window = HomePage(login_window.table_name) if homepage_window.income: income_window = Income(login_window.table_name) homepage_window = HomePage(login_window.table_name) if homepage_window.transaction: transaction_window = Transaction(login_window.table_name) homepage_window = HomePage(login_window.table_name) if homepage_window.delete: delete_window = Delete(login_window.table_name) homepage_window = HomePage(login_window.table_name) if homepage_window.analysis: analysis_window = Analysis(login_window.table_name) homepage_window = HomePage(login_window.table_name) if homepage_window.suggestion: suggestion_window = Savings(login_window.table_name)
total += i.get_income() return total def get_total_expense(self): total = 0 for e in self.expense: total += e.get_expense() return total def get_profit_loss(self): if self.get_total_income() > self.get_total_expense(): return "Profit = Rs " + str(self.get_total_income() - self.get_total_expense()) elif self.get_total_income() < self.get_total_expense(): return "Loss = Rs " + str(self.get_total_expense() - self.get_total_income()) else: return "No Profit No Loss" if __name__ == "__main__": inclist = [] explist = [] i1 = Income('Box1', 1200) i2 = Income('Box2', 1400) e1 = Expense('Babloo', 200) inclist.append(i1) inclist.append(i2) explist.append(e1) p = Page('1-1-2020', inclist, explist) print(p.get_profit_loss())
def add(self, x): # Adds a new expense input self.expense_list.append(Expense(x))
def log_expenses(missing_data): """ Function that iterates expenses one by one, creates an Expense object, updates its information and saves each Expense on installments dataframe and expenses dataframe. ----------------- Receives: - missing_data -> DataFrame containing the expenses to be logged. Returns: - installments_df -> DataFrame containing information about the expense divided in installments. - expenses_df -> DataFrame containing information about the expense before being divided in installments. """ print('logging expenses...') new_expenses = [] # Reads the categories from the Google Sheet. main_cats, sub_cats = hlp.get_categories_from_gsheet(GSHEET, GSHEET_ID) # Initialize the resulting dataframes installments_df, expenses_df = hlp.init_dataframes() # Iterates expenses one by one for ix, row in missing_data.iterrows(): payment_method_type = row['pay_method'] cc_used = row['credit_card_object'] # Create Expense new object an_expense = Expense(this_id=(int(LAST_ID)+1)+ix) # Dialog box to enter information about the expense dialog = LogExpenseForm( categories = main_cats, subcategories = sub_cats, expense_date_str = str(row.iloc[0].date()), expense_description = row.iloc[1], expense_amount = str(row.iloc[2]), payment_type=payment_method_type, card_last_4_digits = cc_used.get_last_four_digits() ) # Response of the log expense Dialog box log_expense = None if dialog.exec_() == LogExpenseForm.Accepted: # Get the user response log_expense, cat, sub_cat, installments = dialog.get_output() if log_expense is None: # Response was Close window or Cancel break elif log_expense == 1: # Response to log this expense? was Yes # Update the Expense object to hold the necessary information hlp.update_data( an_expense=an_expense, row=row, category=cat, sub_category=sub_cat, installments=installments, pay_method_type=payment_method_type, credit_card_used=cc_used ) # Dive the Expense in installments sub_expenses = an_expense.divide_expense() # Save the divided expense on the installments_df DataFrame installments_df = hlp.update_installments_data_frame( installments_df, expenses = sub_expenses ) # Save the Expense on the expenses_df DataFrame expenses_df = hlp.update_expenses_data_frame( cur_df = expenses_df, expense = an_expense, ignored=False ) else: # Response to log this expense? was No # Update the Expense object to hold the necessary information hlp.update_data( an_expense=an_expense, row=row, category=cat, sub_category=sub_cat, installments=1, pay_method_type=payment_method_type, credit_card_used=cc_used ) # Save the Expense on the expenses_df DataFrame expenses_df = hlp.update_expenses_data_frame( cur_df = expenses_df, expense = an_expense, ignored=True ) return installments_df, expenses_df
def test_eq(self): self.assertTrue(self.expense == Expense(10, 'Food', '12-12-1234'))
def setUp(self): self.expense = Expense(10, 'Food', '12-12-1234')
def setUp(self): """ Test setUp method """ self.exp1 = Expense("Eggs", 2.5) self.exp2 = Expense("Milk", 3.5)
import os import sqlite3 from expense import Expense expense = Expense() class ExpenseRepository(): def __init____(self): self.connection = sqlite3.connect('./db.sqlite3') self.cur = self.connection.cursor() def createTable(self): query = ''' CREATE TABLE Expenses ( Title CHAR(20) NOT NULL, Amount FLOAT NOT NULL, Created_at CHAR(20) NOT NULL, Tags TEXT) ''' try: self.cur.execute(''' DROP TABLE IF EXISTS Expenses''') except IndexError: print("Table not dropped or no such tables") finally: self.cur.execute(query) self.connection.commit() self.connection.close() return None
def add_expense(userid, content): wechat_user = user.get_user_by_id(userid) content = content.encode('utf-8', 'ignore').strip() # bypass word split #content = util.wash_sentence(content) (code, date, category, amount, brand, comment, token_list) \ = split_expense_word(" %s " % (content)) expense = Expense() expense.init_with_mysql(userid, amount, category, \ brand, date, content, config.DEFAULT_COMMENT) if code == config.RECORD_STATE_QUESTION: return chat.response_fail(expense, "?") if code == config.RECORD_STATE_MULTIPLE_RECORDS: return chat.response_fail(expense, "multiple_record") # print "====== Before (%s, %s, %d; %s) ====" % (category, brand, amount, expense.memo) # store tokens, if detection fail if category == "" or brand == "" or amount == -1: expense.memo = "" for text, start, end in token_list: expense.memo = "%s; %s" % (expense.memo, text) expense.memo = expense.memo.strip("; ") # print "====== After (%s, %s, %d; %s) ====" % (category, brand, amount, expense.memo) if chat.is_comment_meaningless(comment) is True: return chat.response_fail(expense, "empty_notes") if chat.is_comment_pure_alpha(comment) is True: return chat.response_fail(expense, "pure_alpha") if expense.amount == -1: return chat.reply_chat(expense, wechat_user) if expense.amount != -1: if insert_expense(expense) is False: rep_content = MSG.REPLY_EXPENSE_FAILED % comment log.error("user(%s) add_expense fail, content:%s" % (userid, content)) if (expense.category != config.DEFAULT_CATEGORY) and ( expense.branding != config.DEFAULT_BRANDING): tips = "" # TODO to be implemented rep_content = MSG.REPLY_EXPENSE_ADDED % ( category + get_emoji(category, "category"), str(amount)) rep_content = chat.attach_detected_extra_msg( wechat_user, rep_content, expense) else: if expense.category != config.DEFAULT_CATEGORY: tips = "" # TODO to be implemented rep_content = MSG.REPLY_EXPENSE_ADDED_WITH_CATEGORY % (\ category + get_emoji(category, "category"), str(amount)) else: if expense.branding != config.DEFAULT_BRANDING: tips = "" # TODO to be implemented rep_content = MSG.REPLY_EXPENSE_ADDED_WITH_BRANDING % (\ brand + get_emoji(brand, "brand"), str(amount)) else: tips = "" # TODO to be implemented rep_content = MSG.REPLY_EXPENSE_ADDED_SIMPLE % (\ str(date[5:7]).lstrip("0"), str(date[8:10]).lstrip("0"), \ str(amount), comment, tips) rep_content = chat.attach_undetected_extra_msg( wechat_user, expense, rep_content) if expense.category == config.CATEGORY_INCOMING: rep_content = rep_content.replace("消费", "赚了") return rep_content
print('Quit') quit() except Exception: modifyInfo(new_expense, main_cats, sub_cats) # ---- Main Program ----------------------------------- if __name__ == "__main__": new_expenses = [] gsheet = GoogleSheets() main_cats, sub_cats = hlp.getCategoriesFromGSheet(gsheet, GSHEET_ID) # ASK USER FOR THE INFO ABOUT THE EXPENSE. while (True): new_expense = Expense() modifyInfo(new_expense, main_cats, sub_cats) print(new_expense.getInstallments()) # MSI, so divide the Expense in multiple expenses sub_expenses = new_expense.divideExpense() print([se.getAmount() for se in sub_expenses]) new_expenses = new_expenses + sub_expenses print("I have just registered this expense:") print(new_expense.toString()) flag = hlp.askYesOrNo("Log another expense? ") print(" ") if (not flag): break # SAVE THE EXPENSES ON "DATABASE" #Get Current Data from Google Sheet
def edit_expense(): token = request.headers.get('Authorization') if token is None: return make_response( jsonify({ 'success': False, 'error': 'No Auth Token' }), 400) else: db = Database() user_id = AuthSystem.validate_token(token) query = {'_id': user_id} user = db.findUser(query) if user: expense = request.json user = User.from_dict(user) if expense['oldCat'] != expense['expenseCategory']: for i in range(0, len(user.categories)): if user.categories[i].getName() == expense['oldCat']: user.categories[i].removeExpense(expense) break for i in range(0, len(user.categories)): if user.categories[i].getName( ) == expense['expenseCategory']: user.categories[i].addExpense( Expense(expense['item'], expense['amount'], expense['date'], expense['expenseCategory'])) break else: amount_diff = expense['amount'] - expense['oldAmount'] user.updateTotalExpenses(amount_diff) for i in range(0, len(user.categories)): if user.categories[i].getName( ) == expense['expenseCategory']: for j in range(0, len(user.categories[i].expenses)): if user.categories[i].expenses[j].getItem( ) == expense['oldItem']: user.categories[i].expenses[j].setItem( expense['item']) user.categories[i].expenses[j].setAmount( expense['amount']) user.categories[i].expenses[j].setDate( expense['date']) user.categories[i].expenses[ j].setExpenseCategory( expense['expenseCategory']) user.categories[i].updateSpent(amount_diff) break break user_dict = user.as_dict() updates = { 'categories': user_dict['categories'], 'totalExpenses': user_dict['totalExpenses'] } did_update = db.updateUser(query, updates) if did_update: return make_response(jsonify({'success': True}), 200) else: return make_response( jsonify({ 'success': False, 'error': 'Failed to update User!' }), 304) else: return make_response( jsonify({ 'success': False, 'error': 'User not found!' }), 404)
"""Test functions for Expense module""" from expense import Expense expense = Expense() expense.add('12/01/20', 'Groceries', 'Vons', 25, 'Credit Card') expense.add('12/01/20', 'Rent', 'December Rent', 1000, 'Check') expense.add('12/01/20', 'School', 'Tuition', 4000, 'Check') def test_initialize(): assert isinstance(expense, Expense) assert isinstance(expense.expense_list, list) def test_add(): entry_1 = expense.expense_list[0] assert isinstance(entry_1, dict) assert entry_1 == { 'Date': '12/01/20', 'Category': 'Groceries', 'Description': 'Vons', 'Amount': 25, 'Form': 'Credit Card'} def test_total(): total = expense.total() assert total == 5025 def test_max(): most_expensive = expense.highest() assert most_expensive == 4000
def registerExpense(self, id, title, amount): # crear un objeto Ingreso expense = Expense(id, title, amount) # agregarlo a la lista de ingresos self.expenseList.append(expense) self.calculateBalance()