def __init__(self, userInput, accountFile, transactionFile, isRunningFromFile=False): self.transactionRecords = Transactions(transactionFile) self.frontEndValidator = FrontEndValidator() self.admin = None self.isReady = False userInput = userInput.strip() if userInput == "login": while userInput != "agent" and userInput != "atm": if not isRunningFromFile: userInput = self.getInput() if userInput != "agent" and userInput != "atm": print "Please enter 'atm' or 'agent'" self.validAccount = ValidAccounts(accountFile) if userInput == "agent": self.admin = True self.isReady = True self.isLoggedIn = True elif userInput == "atm": self.admin = False self.isReady = True self.isLoggedIn = True else: print "You must log in using 'login' command"
def __init__(self, mainwindow): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.mainwindow = mainwindow self.ui.expense_radioButton.setChecked(True) self.ui.back_pushButton.clicked.connect(self.close) self.ui.savecategory_pushButton.clicked.connect(self.save_category) self.ui.income_radioButton.clicked.connect(self.refresh_categories) self.ui.expense_radioButton.clicked.connect(self.refresh_categories) self.category_manager = Categories() self.refresh_categories() #################################### # categories tab part #################################### self.ui.t_expense_radioButton.setChecked(True) self.ui.t_expense_radioButton.clicked.connect( self.refresh_transaction_categories) self.ui.t_income_radioButton.clicked.connect( self.refresh_transaction_categories) self.ui.t_dateEdit.setDate( QDate(date.today().year, date.today().month, date.today().day)) self.ui.t_savebutton.clicked.connect(self.save_transaction) self.transaction_manager = Transactions() self.refresh_transaction_categories()
def InterfaceTransfer(): print('#### OPERAÇÃO DE TRANSFÊRENCIA BANCÁRIA ######') destiny = input('Para qual conta deseja enviar? R: ') value = int(input('Qual valor da transferência? R: ')) if (value >= 0): transaction = Transactions(user, destiny, value) transaction.transfer() else: print('------> Operação cancelada.') painel(user)
class Block: def __init__(self, block_bytes_array, _block_num): bytes_magic = block_bytes_array[:4] bytes_rest = block_bytes_array[4:] bytes_size = bytes_rest[:4] bytes_rest = bytes_rest[4:] bytes_header = bytes_rest[:80] bytes_rest = bytes_rest[80:] bytes_tx_count = bytes_rest[:1] # get varInt prefix bytes_rest = bytes_rest[1:] # check if varInt is on 1, 2, 4, or 8 bytes if(bytes_tx_count[0] == 253): # varInt is on 2 bytes AFTER the prefix bytes_tx_count = bytes_rest[:2] bytes_rest = bytes_rest[2:] elif(bytes_tx_count[0] == 254): # varInt is on 4 bytes AFTER the prefix bytes_tx_count = bytes_rest[:4] bytes_rest = bytes_rest[4:] elif(bytes_tx_count[0] == 255): # varInt is on 8 bytes AFTER the prefix bytes_tx_count = bytes_rest[:8] bytes_rest = bytes_rest[8:] # else varInt was on 1 bytes, nothing to do bytes_tx_data = bytes_rest self.block_num = _block_num self.magic = int.from_bytes(bytes_magic, byteorder='little') self.size = int.from_bytes(bytes_size, byteorder='little') self.tx_count = int.from_bytes(bytes_tx_count, byteorder='little') self.header = Header(bytes_header) self.transactions = Transactions(bytes_tx_data, self.tx_count) def getNet(self): if(self.magic == 3652501241): return 'main network' elif(self.magic == 3669344250): return 'test network' elif(self.magic == 118034699): return 'test network 3' elif(self.magic == 4273258233): return 'namecoin network' else: return 'unknown network' def print(self): print() print('Block :', self.block_num) print(' ', self.getNet()) print(' block size :', self.size) print(' ', self.tx_count, 'transaction(s)') self.header.print() self.transactions.print() print() print('*** END OF BLOCK',self.block_num,'***')
def __init__(self, entry: dict, mainwindow): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.show() self.ui.back_pushButton.clicked.connect(self.close) self.ui.back_pushButton_2.clicked.connect(self.edit) self.entry = entry self.mainwindow = mainwindow self.categories = Categories().category_list[self.entry['type']] self.transactions = Transactions() self.load_entry()
def __init__(self, transaction, mainwindow): super().__init__() self.ui = Ui_edit_transaction_dialog() self.ui.setupUi(self) self.mainwindow = mainwindow self.transaction = transaction self.mainwindow.setEnabled(False) self.transaction_manager = Transactions() self.categories = Categories().category_list[self.transaction['type']] self.laod_transaction() self.show() self.ui.back_pushButton.clicked.connect(self.close) self.ui.savebutton.clicked.connect(self.edit) print(transaction)
def checkBlock(self): blocksList = self.blocks.getList() lastBlockFile = max(map(lambda e: int(e.split('.')[0]), blocksList)) result = False # for each node for node in self.peers: # On s'assure qu'on essaye pas de copier nos propres blocs if node != self.name: # On cherche tous les blocs plus grands que celui actuel foreignBlocks = Blocks('', node) foreignTransactions = Transactions('', node) foreignAccounts = Accounts('', node) blocksListF = foreignBlocks.getList() blocksListF.sort() for block in blocksListF: if int(block.split('.')[0]) > lastBlockFile: # On récupère le bloc et on indique qu'il ne faut plus miner result = True infos = foreignBlocks.getBlock(block) # Vérifie que les informations ont bien été lues # Sinon essaye de les relire while not infos: infos = foreignBlocks.getBlock(block) self.blocks.writeBlock(infos['previous'], infos['miner'], infos['pow'], infos['date'], infos['nonce'], infos['transactions']) # On récupère les transactions de ce bloc et met à jour les comptes for t in infos['transactions']: trans = foreignTransactions.readTrans(t) self.transactions.writeTrans( trans['from'], trans['to'], trans['amount'], trans['fees']) self.accounts.modify_account( trans['from'], foreignAccounts.get_account_amount( trans['from'])) self.accounts.modify_account( trans['to'], foreignAccounts.get_account_amount( trans['to'])) # Affiche un message print('New block get from foreign node with ID ' + block) # Si le bloc a été miné, on quitte sans vérifier les autres noeuds if result: return True return False
def add_transaction(self,recipient,amount,signature,sender=None,is_recieving = False): if self.hosting_id is None: return False if sender is None: sender = self.hosting_id # transaction = { # "sender" : sender, # "recipient" : recipient, # "amount" : amount # } # verification = Verifications() transaction = Transactions(sender,recipient,amount,signature) if not Verifications.verify_transaction(transaction,self.calculate_balances): return False if Verifications.verify_transaction(transaction,self.calculate_balances): self.__open_transactions.append(transaction) self.participants.add(sender) self.participants.add(recipient) self.save_data() if is_recieving is False: for node in self.__peer_nodes: url = "http://{}/broadcast-transactions".format(node) try: response = requests.post(url,json = {'sender': sender,'recipient':recipient,'signature': signature,'amount' : amount}) if response.status_code == 400 or response.status_code == 500: print("Broadcasting transactions failed") return False else: print("Successfully broadcasted transaction with response %s"%(response)) except requests.exceptions.ConnectionError: continue return True else: return False
def load_data(self): try: with open('blockchain_data-%s.txt'%(self.port_id),'r') as read_file: block_data = read_file.readlines() blockchain = json.loads(block_data[0][:-1]) open_transactions = json.loads(block_data[1][:-1]) self.__peer_nodes = set(json.loads(block_data[2])) updated_blockchain = [] updated_transactions = [] for block in blockchain: updated_block = Block(index = block['index'],previousBlockHash = block['previousBlockHash'],transactions = [Transactions(txn['sender'],txn['recipient'],txn['amount'],txn['signature']) for txn in block['transactions']],proof = block['proof']) updated_blockchain.append(updated_block) for tx in open_transactions: updated_transaction = Transactions(tx['sender'],tx['recipient'],tx['amount'],tx['signature']) updated_transactions.append(updated_transaction) self.__chain = updated_blockchain self.__open_transactions = updated_transactions except (IOError,AttributeError,IndexError): genesis_block = Block(index = 0,previousBlockHash = "",transactions = [],proof = 100) self.__chain.append(genesis_block) self.__open_transactions = [] print("Handled the error") finally: print("Blockchain loaded")
def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.transactions = Transactions() self.expenses = self.transactions.expense_transactions self.income = self.transactions.income_transactions self.ui.expense_radioButton.setChecked(True) self.load_table() self.show() self.ui.add_pushButton.clicked.connect(self.show_add_form) self.ui.tableWidget.cellPressed.connect(self.get_table_selection) self.ui.edit_pushButton.clicked.connect(self.edit_button_clicked) self.ui.income_radioButton.toggled.connect( self.income_radiobtn_clicked) self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_clicked) self.ui.delete_pushButton.clicked.connect(self.delete_button_clicked)
def test_from_csv(self): trxs = Transactions.from_csv('sample_transactions_1.csv') self.assertEqual(len(trxs), 36) # Spot check data self.assertAlmostEqual(trxs.df.iloc[0].Amount, -12) self.assertAlmostEqual(trxs.df.iloc[1].Amount, 12) self.assertAlmostEqual(trxs.df.iloc[2]['Account Name'], 'Ac') self.assertAlmostEqual(trxs.df.iloc[3]['Category'], 'Two Trx')
def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.transactions = Transactions() self.show() self.ui.categories_pushButton.clicked.connect( self.categories_button_click) self.ui.add_pushButton.clicked.connect(self.add_button_click) self.ui.edit_pushButton.clicked.connect(self.edit_button_click) self.ui.delete_pushButton.clicked.connect(self.delet_button_click) self.ui.view_pushButton.clicked.connect(self.view_button_click) self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_active) self.ui.income_radioButton.toggled.connect(self.income_radiobtn_active) self.ui.expense_radioButton.setChecked(True) self.load_table()
def add_block(self,block): print("Broadcasting will add %s"%(block)) transactions = [ Transactions(sender = txn['sender'], recipient = txn['recipient'], amount = txn['amount'], signature = txn['signature'] ) for txn in block['transactions']] is_valid_proof = Verifications.valid_proof(transactions[:-1],block['previousBlockHash'], block['proof']) hu = HashUtils() is_valid_hash = block['previousBlockHash'] == hu.hash_block(self.__chain[-1]) if (is_valid_hash is False) or (is_valid_proof is False): return False else: self.save_data() return True
def parseTx(self, index): print('parsing tx', index, '. . .') with open(self.path, 'rb') as block_file: # open file in read binary mode block_file.seek(self.byte_index[index]) bytes_block = block_file.read(self.tx_size[index]) block_file.closed # close the file tx = Transactions(bytes_block, 1) return tx
class TestTransactions(unittest.TestCase): def test_gather_all_statements(self): self.assertEqual(self.transactions.transaction_df.shape[0], 10) def setUp(self): self.transactions = Transactions(statements_dir='./test_data') self.transactions.gather_all_statements() self.transactions.mark_duplicates_2() def test_mark_duplicates_run(self): bool_list = pd.Series(self.transactions.transaction_df.columns).isin( ['isDuplicate']) self.assertTrue(bool_list.any()) def test_get_net_expense(self): # print (self.transactions.transaction_df) net_expense = self.transactions.get_net_expense( df_to_use=self.transactions.transaction_df) self.assertEqual(net_expense.Amount.loc['Credit'], -650.5) self.assertEqual(net_expense.Amount.loc['Debit'], 110)
def test_sum(self): """ Test Transactions.sum() """ # Reference tranactions trxs = Transactions.from_csv('sample_transactions_1.csv') # Known summation of the entire file ref_sum = -np.sum([i for i in range(1, 13)]) self.assertEqual(ref_sum, trxs.sum()) self.assertEqual(ref_sum, trxs.slice_by_category(["One Trx", "Two Trx"]).sum()) self.assertEqual(2 * ref_sum, trxs.slice_by_category(["Two Trx"]).sum())
def __init__(self, mainwindow): super().__init__() self.ui = Ui_add_transaction_dialog() self.ui.setupUi(self) self.mainwindow = mainwindow self.ui.expense_radioButton.setChecked(True) self.category_manager = Categories() self.transactions = Transactions() self.load_categories() self.ui.dateEdit.setDate( QDate(date.today().year, date.today().month, date.today().day)) self.show() self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_active) self.ui.income_radioButton.toggled.connect(self.income_radiobtn_active) self.ui.savebutton.clicked.connect(self.save_category) self.ui.back_pushButton.clicked.connect(self.close) self.mainwindow.setEnabled(False)
class TestTransactions(unittest.TestCase): def setUp(self): self.transactions = Transactions(321001, "2020-06-04", "20:33:51", [ 'Gala Apple', 'Sour Patch Watermelon Soft & Chewy Candy - 8oz', 'Organic Green Bell Pepper' ], 400901, 5.97, 0.05, "K0091", 0.00, 5.92) def test_AddItem(self): self.assertEquals(self.transactions.addItem("Gala Apple"), ['Gala Apple']) self.assertEquals( self.transactions.addItem( 'Sour Patch Watermelon Soft & Chewy Candy - 8oz'), ['Gala Apple', 'Sour Patch Watermelon Soft & Chewy Candy - 8oz']) self.assertEquals( self.transactions.addItem('Organic Green Bell Pepper'), [ 'Gala Apple', 'Sour Patch Watermelon Soft & Chewy Candy - 8oz', 'Organic Green Bell Pepper' ]) def test_EmployeeString(self): self.assertEquals(str(self.transactions), "Transaction #321001 item bought: 3 Thank You!")
def __init__(self, block_bytes_array, _block_num): bytes_magic = block_bytes_array[:4] bytes_rest = block_bytes_array[4:] bytes_size = bytes_rest[:4] bytes_rest = bytes_rest[4:] bytes_header = bytes_rest[:80] bytes_rest = bytes_rest[80:] bytes_tx_count = bytes_rest[:1] # get varInt prefix bytes_rest = bytes_rest[1:] # check if varInt is on 1, 2, 4, or 8 bytes if(bytes_tx_count[0] == 253): # varInt is on 2 bytes AFTER the prefix bytes_tx_count = bytes_rest[:2] bytes_rest = bytes_rest[2:] elif(bytes_tx_count[0] == 254): # varInt is on 4 bytes AFTER the prefix bytes_tx_count = bytes_rest[:4] bytes_rest = bytes_rest[4:] elif(bytes_tx_count[0] == 255): # varInt is on 8 bytes AFTER the prefix bytes_tx_count = bytes_rest[:8] bytes_rest = bytes_rest[8:] # else varInt was on 1 bytes, nothing to do bytes_tx_data = bytes_rest self.block_num = _block_num self.magic = int.from_bytes(bytes_magic, byteorder='little') self.size = int.from_bytes(bytes_size, byteorder='little') self.tx_count = int.from_bytes(bytes_tx_count, byteorder='little') self.header = Header(bytes_header) self.transactions = Transactions(bytes_tx_data, self.tx_count)
def process_line(self, line): payer = line[1] payee = line[2] if payer.lower() not in self.users: self.users[payer.lower()] = User(payer) if payee.lower() not in self.users: self.users[payee.lower()] = User(payee) try: self.transactions.append(Transactions(line)) self.users[payer.lower()].remove_money(line[4]) self.users[payee.lower()].add_money(line[4]) except: self.logger.fail( f"Support Bank.py. Could not confirm amount to float. Value: {line[4]}" )
def test_slice_by_categories(self): """ Test Transactions.slice_by_category by slicing a sample Transactions object :return: """ trxs = Transactions.from_csv('sample_transactions_1.csv') # Positive match trxs_2 = trxs.slice_by_category(["Two Trx"]) # Do a few spot checks (not comprehensive...) self.assertEqual(len(trxs_2), 24) self.assertEqual(trxs_2.df.iloc[6].Amount, -9.0) # Negative match trxs_2 = trxs.slice_by_category(["Two Trx"], return_anti_match=True) # Do a few spot checks (not comprehensive...) self.assertEqual(len(trxs_2), 12) self.assertEqual(trxs_2.df.iloc[6].Amount, 6.0)
def mine_block(self): if self.hosting_id is not None: hu = HashUtils() last_block = self.__chain[-1] block_hash = hu.hash_block(last_block) proof = self.proof_of_work() # reward_transaction = { # 'sender' : 'MINER', # 'recipient' : owner, # 'amount' : MINING_REWARD # } reward_transaction = Transactions('MINER',self.hosting_id,self.MINING_REWARD,'') copied_transactions = self.__open_transactions[:] if not Verifications.verify_transactions(copied_transactions,self.calculate_balances): return None copied_transactions.append(reward_transaction) block = Block(index = len(self.__chain),previousBlockHash = block_hash,proof = proof,transactions = copied_transactions) self.__open_transactions = [] for node in self.__peer_nodes: url = "http://{}/broadcast-block".format(node) broadcasted_block = block.__dict__.copy() broadcasted_block['transactions'] = [txn.__dict__ for txn in broadcasted_block['transactions']] response = requests.post(url,json = {'block': broadcasted_block}) if response.status_code == 500 or response.status_code == 400: print(json.loads(response.text)) print("Broadcasting block failed") else: print("Successfully broadcasted the block") print("New length of blockchain %s"%(len(self.__chain))) print("Adding new block %s"%(block.__dict__)) self.__chain.append(block) self.save_data() return block else: return None
import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.express as px from Transactions import Transactions import pandas as pd import plotly.figure_factory as ff import plotly.graph_objects as go # or plotly.express as px # df = px.data.iris() transactions = Transactions( statements_dir='/Users/shivakumar/Documents/GitHubRepos/BudgetDash/data') transactions.gather_all_statements() transactions.generate_month_labels() transactions.mark_duplicates_2() all_transactions = transactions.transaction_df summary_df = transactions.get_net_expense(df_to_use=all_transactions) cols_to_exclude = ['Month_string', 'isDuplicate'] display_cols_bools = pd.Series( all_transactions.columns.values).isin(cols_to_exclude) cols_to_display = all_transactions.columns[~display_cols_bools.values] navbar = dbc.NavbarSimple( children=[ dbc.NavItem(dbc.NavLink("Link", href="#")), dbc.DropdownMenu( nav=True, in_navbar=True, label="Menu",
def setUp(self): self.transactions = Transactions(321001, "2020-06-04", "20:33:51", [ 'Gala Apple', 'Sour Patch Watermelon Soft & Chewy Candy - 8oz', 'Organic Green Bell Pepper' ], 400901, 5.97, 0.05, "K0091", 0.00, 5.92)
def main(): parser = argparse.ArgumentParser(description=' Budget analyzer.') parser.add_argument('--statements-dir', type=str, required=True, help='Path to the directory containing statements.') args = parser.parse_args() transactions = Transactions(statements_dir=args.statements_dir) transactions.gather_all_statements() transactions.mark_duplicates_2() print(transactions.transaction_df) df = transactions.get_net_expense(df_to_use=transactions.transaction_df) print(df) print(df.index.values) print(transactions.transaction_df.dtypes) transactions.generate_month_labels() print(transactions.transaction_df.head()) transactions.mark_duplicates_2() print(transactions.transaction_df)
class EditDialog(QDialog): def __init__(self, transaction, mainwindow): super().__init__() self.ui = Ui_edit_transaction_dialog() self.ui.setupUi(self) self.mainwindow = mainwindow self.transaction = transaction self.mainwindow.setEnabled(False) self.transaction_manager = Transactions() self.categories = Categories().category_list[self.transaction['type']] self.laod_transaction() self.show() self.ui.back_pushButton.clicked.connect(self.close) self.ui.savebutton.clicked.connect(self.edit) print(transaction) def laod_transaction(self): self.ui.type_label.setText(self.transaction['type']) self.ui.amountlineEdit.setText(self.transaction['amount']) date_ = [int(part) for part in self.transaction['date'].split('-')] self.ui.dateEdit.setDate(QDate(date_[0], date_[1], date_[2])) self.ui.notelineEdit.setText(self.transaction['note']) self.ui.categories_combobox.clear() self.ui.categories_combobox.addItems(self.categories) self.ui.categories_combobox.setCurrentIndex( self.categories.index(self.transaction['category'])) def change(self): ui_date = self.ui.dateEdit.date().toPyDate() entry_date = [ int(part) for part in self.transaction['date'].split('-') ] entry_date = date(entry_date[0], entry_date[1], entry_date[2]) ui_amount = float(self.ui.amountlineEdit.text()) entry_amount = float(self.transaction['amount']) ui_category = self.ui.categories_combobox.currentText() entry_category = self.transaction['category'] ui_note = self.ui.notelineEdit.text().strip() entry_note = self.transaction['note'] print(ui_note, entry_note) return not (ui_amount == entry_amount and ui_category == entry_category and ui_note == entry_note and ui_date == entry_date) def edit(self): if self.change(): row_id = self.transaction['row_id'] category = self.ui.categories_combobox.currentText() amount = float(self.ui.amountlineEdit.text()) note = self.ui.notelineEdit.text().strip() date_ = str(self.ui.dateEdit.date().toPyDate()) self.transaction_manager.edit(row_id, category, amount, date_, note) self.transaction_manager.refresh() self.mainwindow.load_table() self.close() QMessageBox.information(self, 'Transaction Updated', 'Transaction is updated successfully', QMessageBox.Ok) self.transaction['category'] = category self.transaction['amount'] = amount self.transaction['date'] = date_ self.transaction['note'] = note else: QMessageBox.warning( self, 'Can\'t update', 'Nothing is edited to update\nPlease edit the transaction entry first before clicking edit', QMessageBox.Ok) def closeEvent(self, event: QtGui.QCloseEvent): self.mainwindow.setEnabled(True) event.accept()
class MainWindow(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.transactions = Transactions() self.expenses = self.transactions.expense_transactions self.income = self.transactions.income_transactions self.ui.expense_radioButton.setChecked(True) self.load_table() self.show() self.ui.add_pushButton.clicked.connect(self.show_add_form) self.ui.tableWidget.cellPressed.connect(self.get_table_selection) self.ui.edit_pushButton.clicked.connect(self.edit_button_clicked) self.ui.income_radioButton.toggled.connect( self.income_radiobtn_clicked) self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_clicked) self.ui.delete_pushButton.clicked.connect(self.delete_button_clicked) def show_add_form(self): add_form = AddWindow(self) add_form.exec_() def load_table(self): self.ui.tableWidget.clearContents() if self.ui.income_radioButton.isChecked(): dataframe = self.transactions.income_transactions else: dataframe = self.transactions.expense_transactions r, c = dataframe.shape self.ui.tableWidget.setRowCount(r) self.ui.tableWidget.setColumnCount(c + 1) row_count = 0 for row_index, row_data in dataframe.iterrows(): self.ui.tableWidget.setItem(row_count, 0, QTableWidgetItem(str(row_index))) self.ui.tableWidget.setItem(row_count, 1, QTableWidgetItem(row_data['category'])) self.ui.tableWidget.setItem( row_count, 2, QTableWidgetItem(str(row_data['amount']))) self.ui.tableWidget.setItem(row_count, 3, QTableWidgetItem(row_data['date'])) self.ui.tableWidget.setItem(row_count, 4, QTableWidgetItem(row_data['note'])) self.ui.tableWidget.setItem(row_count, 5, QTableWidgetItem(row_data['type'])) row_count += 1 self.ui.tableWidget.setHorizontalHeaderLabels( ['#', 'Category', 'Amount', 'Date', 'Memo', 'Type']) header = self.ui.tableWidget.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.ResizeToContents) header.setSectionResizeMode(1, QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QHeaderView.ResizeToContents) header.setSectionResizeMode(4, QHeaderView.ResizeToContents) header.setSectionResizeMode(5, QHeaderView.ResizeToContents) header.setStretchLastSection(True) def get_table_selection(self): items = [item.text() for item in self.ui.tableWidget.selectedItems()] if items: selected_items = { 'row_id': items[0], 'category': items[1], 'amount': items[2], 'date': items[3], 'note': items[4], 'type': items[5], } return selected_items else: return False def edit_button_clicked(self): items = self.get_table_selection() pprint(items) if items: edit_dialog = EditWindow(items, self) edit_dialog.exec_() self.load_table() else: QMessageBox.question( self, 'Nothing is selected', 'Please select something first so you can edit it', QMessageBox.Ok) def income_radiobtn_clicked(self): if self.ui.income_radioButton.isChecked(): self.load_table() def expense_radiobtn_clicked(self): if self.ui.expense_radioButton.isChecked(): self.load_table() def delete_button_clicked(self): items = self.get_table_selection() if items: delete_question = QMessageBox.question( self, 'Delete Transaction', 'Are you sure you want to delete the selected transaction', QMessageBox.Yes | QMessageBox.No) if delete_question == QMessageBox.Yes: self.transactions.delete(items['row_id']) self.load_table() else: QMessageBox.question( self, 'Nothing is selected', 'Please select something first so you can delete it', QMessageBox.Ok)
class MainWindow(QDialog): def __init__(self): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.transactions = Transactions() self.show() self.ui.categories_pushButton.clicked.connect( self.categories_button_click) self.ui.add_pushButton.clicked.connect(self.add_button_click) self.ui.edit_pushButton.clicked.connect(self.edit_button_click) self.ui.delete_pushButton.clicked.connect(self.delet_button_click) self.ui.view_pushButton.clicked.connect(self.view_button_click) self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_active) self.ui.income_radioButton.toggled.connect(self.income_radiobtn_active) self.ui.expense_radioButton.setChecked(True) self.load_table() def categories_button_click(self): categories_window = CategoriesWindow() categories_window.exec_() def add_button_click(self): add_window = AddDialog(self) add_window.exec_() def edit_button_click(self): selection = self.get_table_selection() if selection: edit_dialog = EditDialog(self.get_table_selection(), self) edit_dialog.exec_() else: QMessageBox.warning( self, 'No Transaction Selected', 'Please select a transaction before clicking the edit button again', QMessageBox.Ok) def delet_button_click(self): selected_transaction = self.get_table_selection() if selected_transaction: delete_question = QMessageBox.question( self, 'Delete Transaction', 'Are you sure you want to delete the selected transaction', QMessageBox.Yes | QMessageBox.No) if delete_question == QMessageBox.Yes: self.transactions.delete(selected_transaction['row_id']) self.load_table() else: QMessageBox.warning( self, 'Nothing is selected', 'Please select something first before you click the delete button again', QMessageBox.Ok) def view_button_click(self): pass def expense_radiobtn_active(self): if self.ui.expense_radioButton.isChecked(): self.load_table() def income_radiobtn_active(self): if self.ui.income_radioButton.isChecked(): self.load_table() def get_active_radiobtn(self): if self.ui.income_radioButton.isChecked(): return 'income' else: return 'expense' def load_table(self): self.ui.tableWidget.clearContents() dataframe = self.transactions.transactions_dict[ self.get_active_radiobtn()] print(dataframe) r, c = dataframe.shape self.ui.tableWidget.setRowCount(r) self.ui.tableWidget.setColumnCount(c + 1) self.ui.tableWidget.setHorizontalHeaderLabels( ['#', 'Category', 'Amount', 'Date', 'Memo', 'Type']) row_count = 0 for row_index, row_data in dataframe.iterrows(): self.ui.tableWidget.setItem(row_count, 0, QTableWidgetItem(str(row_index))) self.ui.tableWidget.setItem(row_count, 1, QTableWidgetItem(row_data['category'])) self.ui.tableWidget.setItem( row_count, 2, QTableWidgetItem(str(row_data['amount']))) self.ui.tableWidget.setItem(row_count, 3, QTableWidgetItem(row_data['date'])) self.ui.tableWidget.setItem(row_count, 4, QTableWidgetItem(row_data['note'])) self.ui.tableWidget.setItem(row_count, 5, QTableWidgetItem(row_data['type'])) row_count += 1 header = self.ui.tableWidget.horizontalHeader() for i in range(6): header.setSectionResizeMode(i, QHeaderView.ResizeToContents) header.setStretchLastSection(True) def get_table_selection(self): items = [item.text() for item in self.ui.tableWidget.selectedItems()] if items: return { 'row_id': items[0], 'category': items[1], 'amount': items[2], 'date': items[3], 'note': items[4], 'type': items[5], } else: return False def closeEvent(self, event: QtGui.QCloseEvent): exit() event.accept()
class EditWindow(QDialog): def __init__(self, entry: dict, mainwindow): super().__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) self.show() self.ui.back_pushButton.clicked.connect(self.close) self.ui.back_pushButton_2.clicked.connect(self.edit) self.entry = entry self.mainwindow = mainwindow self.categories = Categories().category_list[self.entry['type']] self.transactions = Transactions() self.load_entry() def load_entry(self): self.ui.type_label.setText(self.entry['type']) self.ui.amountlineEdit.setText(self.entry['amount']) date_ = [int(part) for part in self.entry['date'].split('-')] self.ui.dateEdit.setDate(QDate(date_[0], date_[1], date_[2])) self.ui.noteLineEdit.setText(self.entry['note']) self.ui.categories_combobox.clear() self.ui.categories_combobox.addItems(self.categories) self.ui.categories_combobox.setCurrentIndex( self.categories.index(self.entry['category'])) def change(self): ui_date = [int(part) for part in self.ui.dateEdit.text().split('/')] ui_date = date(ui_date[2], ui_date[1], ui_date[0]) entry_date = [int(part) for part in self.entry['date'].split('-')] entry_date = date(entry_date[0], entry_date[1], entry_date[2]) ui_amount = float(self.ui.amountlineEdit.text()) entry_amount = float(self.entry['amount']) ui_category = self.ui.categories_combobox.currentText() entry_category = self.entry['category'] ui_note = self.ui.noteLineEdit.text().strip() entry_note = self.entry['note'].strip() return not (ui_amount == entry_amount and ui_category == entry_category and ui_note == entry_note and\ ui_date == entry_date) def edit(self): if self.change(): row_id = self.entry['row_id'] category = self.ui.categories_combobox.currentText() amount = float(self.ui.amountlineEdit.text().strip()) note = self.ui.noteLineEdit.text().strip() ui_date = [ int(part) for part in self.ui.dateEdit.text().split('/') ] ui_date = date(ui_date[2], ui_date[1], ui_date[0]) self.transactions.edit(row_id, category, amount, ui_date, note) print('updated') self.transactions.refresh() self.mainwindow.load_table() self.entry['category'] = category self.entry['amount'] = amount self.entry['date'] = str(ui_date) self.entry['note'] = note else: print('nothing is edited to update')
class AddDialog(QDialog): def __init__(self, mainwindow): super().__init__() self.ui = Ui_add_transaction_dialog() self.ui.setupUi(self) self.mainwindow = mainwindow self.ui.expense_radioButton.setChecked(True) self.category_manager = Categories() self.transactions = Transactions() self.load_categories() self.ui.dateEdit.setDate( QDate(date.today().year, date.today().month, date.today().day)) self.show() self.ui.expense_radioButton.toggled.connect( self.expense_radiobtn_active) self.ui.income_radioButton.toggled.connect(self.income_radiobtn_active) self.ui.savebutton.clicked.connect(self.save_category) self.ui.back_pushButton.clicked.connect(self.close) self.mainwindow.setEnabled(False) def expense_radiobtn_active(self): if self.ui.expense_radioButton.isChecked(): self.load_categories() def income_radiobtn_active(self): if self.ui.income_radioButton.isChecked(): self.load_categories() def save_category(self): if self.ui.categories_combobox.count( ) > 0 and self.ui.amountlineEdit.text() != "": category_type = self.get_active_radiobtn() category = self.ui.categories_combobox.currentText() amount = self.ui.amountlineEdit.text() date_ = self.ui.dateEdit.date().toPyDate() note = self.ui.notelineEdit.text() print(category_type, category, amount, date_, note) try: amount = float(amount) self.transactions.add(category, amount, date_, note, category_type) self.mainwindow.load_table() self.close() QMessageBox.information( self, 'Transaction Saved', f"{category.capitalize()} transaction is saved successfuly" ) except ValueError as verr: QMessageBox.warning( self, 'Wrong Format', 'The amount entered is not a proper number format\nplease check it again', QMessageBox.Ok) else: QMessageBox.warning( self, 'Fields Missing', 'Please insert all the required information about the transaction and try again', QMessageBox.Ok) def get_active_radiobtn(self): if self.ui.expense_radioButton.isChecked(): return 'expense' else: return 'income' def load_categories(self): self.ui.categories_combobox.clear() self.ui.categories_combobox.addItems( self.category_manager.category_list[self.get_active_radiobtn()]) def closeEvent(self, event: QtGui.QCloseEvent): self.mainwindow.setEnabled(True) event.accept()