class Log(Db): def __init__(self): self.logModel = TableModel('Time', 'Type', 'Message') self.rootContext().setContextProperty('logModel', self.logModel) def log(self, message, messageType='System', messageTime=None): if not messageTime: messageTime = datetime.now().strftime('%H:%M:%S') self.logModel.addRow([messageTime, messageType, message])
class Parse(Proxylist): def __init__(self): super().__init__() self.items = [] self.parse_obj = None self.parse_thread = None self.itemsModel = TableModel('Id', 'Dt', 'Name', 'Price', 'Author', 'Address', 'Phone') self.sortItemsModel = SortFilterProxyModel(self.itemsModel) self.rootContext().setContextProperty('sortItemsModel', self.sortItemsModel) def parse(self): if self.parse_thread and self.parse_thread.isRunning(): return self.log('Start parsing', 'Parse') self.itemsModel.clear() self.items = [] self.parse_obj = ParseWorker(self.proxylist) self.parse_thread = QThread() self.parse_obj.moveToThread(self.parse_thread) self.parse_obj.message.connect(self.parse_on_message) self.parse_obj.finished.connect(self.parse_on_finished) self.parse_thread.started.connect(self.parse_obj.start) self.parse_thread.start() def parse_on_message(self, message): if message[0]: self.log(message[0], 'Parse') if message[1]: item = message[1] self.itemsModel.addRow([ item['id'] + 1, item['dt'], item['name'], item['price'], item['author'], item['address'], item['phone'] ]) def parse_on_finished(self, message): self.parse_thread.quit() self.parse_thread.wait() self.items = message[0] self.proxylist = message[1] self.log('Parsing END')
class BudgetReport(Ui_Dialog, QDialog): def __init__(self, orm): super().__init__() self.setupUi(self) self.orm = orm self.set_month_and_year() # Connect signals and slots self.yearBox.currentTextChanged.connect( lambda year: self.load_budget_bars()) self.monthBox.currentTextChanged.connect( lambda month: self.load_budget_bars()) # Show report for current month as initial self.load_budget_bars() # Prepare place for transactions list self.transactions = TableModel(("Date", "Amount", "Info", "Category")) self.transactionsView.setModel(self.transactions) def set_month_and_year(self): """ Sets initial values for year and month boxes. """ self.yearBox.addItems(YEARS) self.monthBox.addItems(MONTHS) current_date = QDate.currentDate() self.yearBox.setCurrentText(str(current_date.year())) self.monthBox.setCurrentText(MONTHS[current_date.month()]) def load_budget_bars(self): """ Loads the budget report from DB for chosen month and year and puts it into GUI. """ self.clear_bars() year = int(self.yearBox.currentText()) month = int(self.monthBox.currentIndex()) # by position for budget_bar in self.orm.fetch_budget_report_bars(month, year): self.add_bar(budget_bar) self.barsLayout.setColumnStretch(1, 1) def clear_bars(self): """ Clears the widget for budget report. """ for i in reversed(range(self.barsLayout.count())): widget = self.barsLayout.itemAt(i).widget() # Detach from layout self.barsLayout.removeWidget(widget) # Remove from GUI widget.setParent(None) def add_bar(self, budget_bar): """ Adds single bar to the budget report at selected position """ category = budget_bar.category category_text = category.parent + '::' + category.name position = self.barsLayout.rowCount() + 1 self.barsLayout.addWidget(QLabel(category_text), position, 0) bar = QBar(budget_bar) bar.mousePressed.connect(self.show_transactions) self.barsLayout.addWidget(bar, position, 1) def show_transactions(self, q_bar): """ Show list of transactions for selected budget category. """ self.transactions.prepare() year = int(self.yearBox.currentText()) month = int(self.monthBox.currentIndex()) # by position category = q_bar.model.category for transaction in self.orm.fetch_transactions_for_month(month, year, category): self.transactions.addRow(transaction)
class BalanceReport(Ui_Dialog, QDialog): def __init__(self, orm): super().__init__() self.setupUi(self) self.orm = orm self.set_month_and_year() # Connect signals and slots self.yearBox.currentTextChanged.connect( lambda year: self.load_balance()) self.monthBox.currentTextChanged.connect( lambda month: self.load_balance()) self.roll = TableModel(("Date", "Change", "Total", "Origin", "Category")) self.balanceView.setModel(self.roll) # Show report for current month as initial self.load_balance() def set_month_and_year(self): """ Sets initial values for year and month boxes. """ self.yearBox.addItems(YEARS) self.monthBox.addItems(MONTHS) current_date = QDate.currentDate() self.yearBox.setCurrentText(str(current_date.year())) self.monthBox.setCurrentText(MONTHS[current_date.month()]) def load_balance(self): """ Fetches info from ORM and puts it into balance report. """ self.roll.prepare() year = int(self.yearBox.currentText()) month = int(self.monthBox.currentIndex()) # by position # Get starting balance last_date, balance = self.orm.fetch_balance_to_date(month, year) self.roll.addRow((last_date, 0, balance, 'Transaction', "- - -")) # Get transaction for the active period for transaction in self.orm.fetch_transactions_for_period(month, year): balance += transaction.amount last_date = max(last_date, transaction.date) self.roll.addRow((transaction.date, transaction.amount, balance, 'Transaction', transaction.category)) # Correct the last activity date today = datetime.date.today() last_date = max(last_date, today) # Get budget spendings/incoms after active period predictions = list( self.orm.fetch_budget_prediction(month, year, last_date)) predictions = sorted(predictions, key=lambda p: p.date) for prediction in predictions: category = prediction.category balance += prediction.amount self.roll.addRow((prediction.date, prediction.amount, balance, 'Budget', category.parent+"::"+category.name))
class BudgetManager(ui.manageBudget.Ui_Dialog, QDialog): """ GUI that handles creation, editing and deletion of budgets. """ def __init__(self, orm): super().__init__() self.setupUi(self) self.orm = orm # Fetch subcategories list self.categories = self.orm.fetch_subcategories(full=False) self.recordsView.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.set_month_and_year() self.setup_table() self.load_budget_records() # Connect signals and slots self.yearBox.currentTextChanged.connect( lambda year: self.load_budget_records()) self.monthBox.currentTextChanged.connect( lambda month: self.load_budget_records()) self.addBtn.clicked.connect(self.add_record) self.editBtn.clicked.connect(self.edit_record) self.deleteBtn.clicked.connect(self.delete_record) self.copyBtn.clicked.connect(self.copy_records) def set_month_and_year(self): """ Sets initial values for year and month boxes. """ self.yearBox.addItems(YEARS) self.monthBox.addItems(MONTHS[1:]) current_date = QDate.currentDate() self.yearBox.setCurrentText(str(current_date.year())) self.monthBox.setCurrentText(MONTHS[current_date.month()]) def setup_table(self): """ Initializes the table for budget records. """ self.records = TableModel(("Amount", "Category", "Type", "On day")) self.recordsView.setModel(self.records) self.selection = QItemSelectionModel(self.records) self.recordsView.setSelectionModel(self.selection) def load_budget_records(self): """ Loads the data from DB to GUI. """ self.records.prepare() month = self.monthBox.currentIndex() + 1 # by position+1 year = self.yearBox.currentText() records = self.orm.fetch_records(month, year) for r in records: self.records.addRow(r) def add_record(self): """ Fires up GUI for budget record creation. """ if len(self.categories) == 0: show_warning('You have to create categories first.') return manager = Manager(self.categories.values()) manager.createdRecord.connect(self.record_created) manager.exec() def edit_record(self): """ Fires up GUI for budget record editing. """ index = self.selection.currentIndex() if index.isValid(): record = index.data(role=Qt.UserRole) manager = Manager(self.categories.values(), record) manager.editedRecord.connect(self.record_edited) manager.exec() def delete_record(self): """ Deletes the budget record from DB and GUI. """ index = self.selection.currentIndex() if index.isValid(): record = index.data(role=Qt.UserRole) self.orm.delete_record(record) self.records.removeRows(index.row(), 1) def copy_records(self): dialog = Selector() dialog.monthSelected.connect(self.copy_from_month) dialog.exec() def copy_from_month(self, month, year): records = self.orm.fetch_records(month, year) new_month = self.monthBox.currentIndex() + 1 new_year = int(self.yearBox.currentText()) _, last_day = monthrange(new_year, new_month) for rec in records: category = self.orm.fetch_subcategory(rec.category_id) amount = to_cents(rec.amount) new_day = min(last_day, rec.day) self.record_created(amount, category, rec.type, new_day, new_year, new_month) def record_created(self, amount, category, budget_type, day, year, month): """ Adds created budget record into DB and GUI. """ record = self.orm.add_record(amount, category, budget_type, day, year, month) if (self.monthBox.currentIndex() + 1 == month and int(self.yearBox.currentText()) == year): self.records.addRow(record) def record_edited(self, amount, category, budget_type, day, year, month, record_id): """ Adds edited budget record into DB and reloads all records in the GUI. """ self.orm.update_record(amount, category, budget_type, day, year, month, record_id) self.load_budget_records()
class Proxylist(Log): def __init__(self): super().__init__() self.proxylist = [] self.proxylist_obj = None self.proxylist_thread = None self.proxyModel = TableModel('Id', 'Country', 'Url', 'Response_time', 'Used', 'Error') self.sortProxyModel = SortFilterProxyModel(self.proxyModel) self.rootContext().setContextProperty('sortProxyModel', self.sortProxyModel) async def proxylist_init(self): cursor = await self.db.execute('SELECT * FROM proxy') proxylist = await cursor.fetchall() if proxylist: for p in proxylist: self.proxylist.append({'id': p[0], 'added': p[1], 'country': p[2], 'host': p[3], 'port': p[4], 'url': p[5], 'response_time': p[6], 'used': p[7], 'error': p[8]}) self.proxyModel.addRow([p[0], p[2], p[5], f'{p[6]:.2f}', p[7], p[8]]) self.log(f'Load {len(self.proxylist)} proxy', 'Proxylist') async def proxylist_close(self): if self.proxylist: await self.db.executemany('UPDATE proxy SET used=?, error=? WHERE id=?', [(proxy['used'], proxy['error'], proxy['id']) for proxy in self.proxylist]) await self.db.commit() def proxylist_update(self): if self.proxylist_thread and self.proxylist_thread.isRunning(): return self.log('Start update proxylist', 'Proxylist') self.proxyModel.clear() self.proxylist = [] self.proxylist_obj = ProxylistUpdate() self.proxylist_thread = QThread() self.proxylist_obj.moveToThread(self.proxylist_thread) self.proxylist_obj.message.connect(self.proxylist_on_message) self.proxylist_obj.finished.connect(self.proxylist_on_finished) self.proxylist_thread.started.connect(self.proxylist_obj.start) self.proxylist_thread.start() async def proxylist_save(self): await self.db.executemany('INSERT OR REPLACE INTO proxy (country,host,port,url,response_time) VALUES (?,?,?,?,?)', [(proxy['country'], proxy['host'], proxy['port'], proxy['url'], proxy['response_time']) for proxy in self.proxylist]) await self.db.commit() self.log(f'Save {len(self.proxylist)} proxy', 'Proxylist') async def proxylist_clear(self): self.proxyModel.clear() self.proxylist = [] await self.db.execute(f'DELETE FROM proxy') await self.db.execute(f'DELETE FROM sqlite_sequence WHERE name="proxy"') await self.db.commit() self.log('Clear proxylist', 'Proxylist') def proxylist_on_message(self, message): if message[0]: self.log(message[0], 'Proxylist') if message[1]: proxy = message[1] self.proxyModel.addRow([proxy['id']+1, proxy['country'], proxy['url'], f'{proxy["response_time"]:.2f}', proxy['used'], proxy['error']]) def proxylist_on_finished(self, message): self.proxylist_thread.quit() self.proxylist_thread.wait() self.proxylist = message self.loop.run_until_complete(self.proxylist_save())
class TransactionsRoll(Ui_Dialog, QDialog): """ GUI that handles the list of all transactions for given account. """ def __init__(self, orm, account): super().__init__() self.setupUi(self) self.orm = orm self.account = account self.roll = TableModel(("Date", "Amount", "Info", "Category")) self.rollView.setModel(self.roll) self.selection = QItemSelectionModel(self.roll) self.rollView.setSelectionModel(self.selection) self.rollView.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.addTransaction.clicked.connect(self.add_transaction) self.editTransaction.clicked.connect(self.edit_transaction) self.deleteTransaction.clicked.connect(self.delete_transaction) self.categories = self.orm.fetch_subcategories() self.show_transactions() def show_transactions(self): """ Fetches transactions from DB and shows them. """ self.roll.prepare() transactions = self.orm.fetch_transactions(self.account) for tr in transactions: self.roll.addRow(tr) def add_transaction(self): """ Fires up GUI for adding transaction. """ manager = Manager(self.categories.values()) manager.createdTransaction.connect(self.transaction_created) manager.exec() def edit_transaction(self): """ Fires up GUI for editing transaction. """ index = self.selection.currentIndex() if index.isValid(): transaction = index.data(role=Qt.UserRole) manager = Manager(self.categories.values(), transaction) manager.editedTransaction.connect(self.transaction_edited) manager.exec() def delete_transaction(self): """ Deletes transaction from DB and GUI. """ index = self.selection.currentIndex() if index.isValid(): transaction = index.data(role=Qt.UserRole) self.orm.delete_transaction(transaction, self.account) self.roll.removeRows(index.row(), 1) def transaction_created(self, date, amount, info, category): """ Catches transaction created signal and adds transaction to DB and GUI. """ transaction = self.orm.add_transaction(date, amount, info, self.account, category) self.roll.addRow(transaction) def transaction_edited(self, transaction, category): """ Catches transaction edited signal and updates transaction in the DB, redraws all transactions in the GUI. """ self.orm.update_transaction(transaction, self.account, category) self.show_transactions()