def accept_track_data(self): logger.debug("Accept track data button clicked.") track_code_number = self.TrackCodeInput.text() if not 8 <= len(track_code_number) <= 40: QMessageBox.critical(self, "Error!", "Wrong track code number") else: track_code_desc = self.TrackCodeDescInput.text() with session_scope() as session: result = get_or_none(session, TrackNumber, idx=track_code_number) # if this track number already exist if result: QMessageBox.critical(self, "Error!", "This track number already exist") return else: # get user and create new track number user = session.query(User).first() get_or_create( session, TrackNumber, idx=track_code_number, description=track_code_desc, user_id=user.id, ) self.finished_trigger.emit() logger.debug(f"New track created #{track_code_number}") self.close()
def write_track_info(self): events = self.track_info["data"]["events"][::-1] with session_scope() as session: # get all exist track information IDXs track_info_idxs = [ idx[0] for idx in session.query(TrackInfo.idx).filter( TrackInfo.track_number_id == self.track_idx).all() ] logger.info(f"Track info IDXs - {track_info_idxs}") for event in events: if event["id"] not in track_info_idxs: # create new track info if it is not exist new_event = TrackInfo( idx=event["id"], title=event["operationAttributeTranslated"], description=event["operationAttributeInformation"], operation_dt=datetime.strptime( event["operationDateTime"], OPERATION_DATETIME_FORMAT), track_number_id=self.track_idx, ) session.add(new_event) self.signals.change_statusbar.emit( "green", f"New track info exist and success added, for #{self.track_idx}" ) # update track number data track_data = session.query(TrackNumber).filter( TrackNumber.idx == self.track_idx).first() track_data.destination_place = self.track_info["data"][ "destinationCountry"] track_data.from_place = self.track_info["data"]["fromCountry"]
def fill_main_tree(self): old_widgets = self.TreeWidget.children() if old_widgets: [item.deleteLater() for item in old_widgets] central_widget: QWidget = self.TreeWidget with session_scope() as session: trackers = (session.query(TrackNumber).filter_by( is_active=True).order_by(desc(TrackNumber.updated_dt)).all()) if trackers: data_tracks = {} for record in trackers: data_tracks.update({ f"{record.idx} {record.description}": [[row.title, row.description, row.operation_dt] for row in record.track_infos] }) tree_widget = CustomTreeWidget(data_tracks, parent=central_widget) tree_widget.itemChanged.connect(self.checkbox_click_event) tree_widget.item_selected.connect(self.ctx_menu_handler) tree_widget.doubleClicked.connect(self.cell_double_click) tree_widget.resize(central_widget.size().width(), central_widget.size().height()) tree_widget.show() else: self.statusbar.showMessage( "No track codes available, create your first track.")
def remove_archive_click(self): if self.selected_numbers: with session_scope() as session: for number in self.selected_numbers: resp = get_or_none(session, TrackNumber, idx=number) if resp: session.delete(resp) elif self.clicked_row: with session_scope() as session: resp = get_or_none(session, TrackNumber, idx=self.clicked_row) if resp: session.delete(resp) # reset data self.clicked_row = None self.selected_numbers = [] # self.buttons_enabled_logic() self.init_data()
def init_data(self): self.LangBox.clear() self.LangBox.addItems(config.LANGUAGES.keys()) with session_scope() as session: user = session.query(User).first() self.LangBox.setCurrentText(user.language) self.AutoUpdateInput.setText(str(user.requests_hours)) self.AutoUpdateSlider.setValue(user.requests_hours) self.TrayCheckBox.setChecked(user.system_tray_status)
def archive_track_click(self): if self.selected_numbers: with session_scope() as session: for number in self.selected_numbers: resp = get_or_none(session, TrackNumber, idx=number) if resp: resp.is_active = False elif self.clicked_row: with session_scope() as session: resp = get_or_none(session, TrackNumber, idx=self.clicked_row) if resp: resp.is_active = False # reset data self.clicked_row = None self.selected_numbers = [] self.buttons_enabled_logic() self.fill_main_tree() self.statusbar.setStyleSheet("color: black") self.statusbar.showMessage("Success! Track code archived.")
def remove_track_click(self): if self.selected_numbers: with session_scope() as session: for number in self.selected_numbers: resp = get_or_none(session, TrackNumber, idx=number) if resp: session.delete(resp) elif self.clicked_row: with session_scope() as session: resp = get_or_none(session, TrackNumber, idx=self.clicked_row) if resp: session.delete(resp) # reset data self.clicked_row = None self.selected_numbers = [] self.buttons_enabled_logic() self.fill_main_tree() self.statusbar.setStyleSheet("color: red") self.statusbar.showMessage("Success! Track code deleted.")
def update_settings(self): lang = self.LangBox.currentText() requests_hours = self.AutoUpdateInput.text() system_tray_status = self.TrayCheckBox.isChecked() with session_scope() as session: user = session.query(User).first() user.language = lang user.requests_hours = requests_hours user.system_tray_status = system_tray_status self.LangBox.setItemText(0, lang) self.TrayCheckBox.setChecked(system_tray_status) QMessageBox.information(self, "Success!", "Data updated.") self.close()
def run(self): with session_scope() as session: user = session.query(User).first() if not user: user = User(idx=str(uuid4())) session.add(user) self.main_window.show() # Check if DE supports system tray if not QSystemTrayIcon.isSystemTrayAvailable(): QMessageBox.critical( None, "Error", "I couldn't detect any system tray on this system.") return self.app.exec_()
def check_tracks(self): page_data = TrackerParser.get_page() with session_scope() as session: # get user info self.user = session.query(User).first() # prepare backend self.backend_api = BackendAPI(self.user.idx) # parse page data self.page_credits = self.backend_api.get_page_data(page=page_data) # setup language code self.language = config.LANGUAGES[self.user.language] # get all tracker numbers with update expire time track_numbers = (session.query(TrackNumber).filter( (TrackNumber.is_active == True) & (TrackNumber.updated_dt <= datetime.now() - timedelta(hours=self.user.requests_hours))).all()) if track_numbers: self.signals.change_statusbar.emit( "green", "Track numbers update started.") for track_number in track_numbers: try: # change last upd datetime track_number.updated_dt_update() self.track_idx = track_number.idx self.update_track(track_number.idx) self.signals.change_statusbar.emit( "green", f"{track_number.idx} success updated.") except Exception as err: logger.exception(err) finally: time.sleep(2) # rewrite main table self.signals.update_table.emit() else: self.signals.change_statusbar.emit("red", "Nothing to update.")
def __init__(self, ctx): super().__init__() self.ctx = ctx uic.loadUi(self.ctx.get_resource("MainWindow.ui"), self) # QDialogs self.track_window = TrackNumberWindow(self.ctx) self.info_window = InfoWindow(self.ctx) self.contacts_window = ContactsWindow(self.ctx) self.sync_settings_window = SyncSettingsWindow(self.ctx) self.app_setting_window = SettingsWindow(self.ctx) self.archive_window = ArchiveWindow(self.ctx) # Если запустить апу и не войти в настройки, то проверка статуса чекбокса трея не сработает # TODO я не знаю, куда это засунуть, пока пусть будет здесь with session_scope() as session: user = session.query(User).first() self.app_setting_window.TrayCheckBox.setChecked( user.system_tray_status) # System tray icon setup self.tray_icon = QSystemTrayIcon() self.tray_icon.setIcon( QtGui.QIcon(ctx.get_resource("ui_imgs/icon.png"))) self.tray_icon.show() self.tray_icon.setContextMenu(self.build_tray_icon_menu()) self.tray_icon.activated.connect(self.tray_icon_activated_handler) # Status bar setup self.statusbar.setStyleSheet("color: black") self.statusbar.showMessage("App started") """ Top widget buttons """ # Buttons icons set green_plus = self.ctx.get_resource("ui_imgs/green_plus.png") red_minus = self.ctx.get_resource("ui_imgs/red_minus.png") grey_arrow = self.ctx.get_resource("ui_imgs/grey_arrow.png") # Prepare central buttons self.AddButton.setIcon(QIcon(green_plus)) self.AddButton.clicked.connect(self.new_track_click) self.RemoveButton.setIcon(QIcon(red_minus)) self.RemoveButton.clicked.connect(self.remove_track_click) self.UpdateButton.setIcon(QIcon(grey_arrow)) self.UpdateButton.clicked.connect(self.update_track_click) self.ArchiveButton.clicked.connect(self.archive_track_click) # Prepare top bar buttons self.InfoAction.triggered.connect(self.info_window_show) self.ContactsAction.triggered.connect(self.contacts_window_show) self.SyncSettingsAction.triggered.connect( self.sync_settings_window_show) self.SettingsAction.triggered.connect(self.app_settings_window_show) self.ArchiveAction.triggered.connect(self.app_archive_window_show) # Startup events self.fill_main_tree() # Threads self.threadpool = QThreadPool() # prepare thread pool self.track_window.finished_trigger.connect(self.track_code_added) # create and and start auto-update thread self.auto_update_tracks_thread = TrackAutoUpdateThread() self.auto_update_tracks_thread.signals.change_statusbar.connect( self.manual_status_set) self.auto_update_tracks_thread.signals.message_set.connect( self.manual_message_set) self.auto_update_tracks_thread.signals.update_table.connect( self.fill_main_tree) self.auto_update_tracks_thread.start() # Main table self.selected_numbers = [ ] # contains list of user selected rows track numbers IDX self.clicked_row = None # contains user clicked row track number IDX logger.info("Main window configured")
def update_track_click(self): # if user select some track numbers, update only them if self.selected_numbers: logger.debug( f"Update clicked; Numbers for update - {', '.join(self.selected_numbers)}" ) # prepare track thread with session_scope() as session: # get user data user = User.get(session) tracks = (session.query(TrackNumber).filter( TrackNumber.idx.in_(self.selected_numbers) & (TrackNumber.updated_dt <= datetime.now() - timedelta(hours=config.UPDATE_THRESHOLD))).all()) logger.debug(f"Tracks for manual update - {tracks}") if tracks: self.statusbar.setStyleSheet("color: green") self.statusbar.showMessage("Update success started.") for track in tracks: update_tracks_thread = TrackUpdateThread( user.idx, track.idx, config.LANGUAGES[user.language]) update_tracks_thread.signals.change_statusbar.connect( self.manual_status_set) update_tracks_thread.signals.message_set.connect( self.manual_message_set) update_tracks_thread.signals.update_table.connect( self.fill_main_tree) # Execute self.threadpool.start(update_tracks_thread) # change last upd datetime track.updated_dt_update() self.fill_main_tree() else: self.statusbar.setStyleSheet("color: red") self.statusbar.showMessage( "Tracks already update recently.") self.system_alert_show("Tracks already update recently.") # start update all numbers else: logger.debug(f"Full update clicked") # prepare track thread with session_scope() as session: # get user data user = User.get(session) tracks = (session.query(TrackNumber).filter( TrackNumber.updated_dt <= datetime.now() - timedelta(hours=config.UPDATE_THRESHOLD)).all()) logger.debug(f"Tracks for manual update - {tracks}") if tracks: self.statusbar.setStyleSheet("color: green") self.statusbar.showMessage("Update success started.") for track in tracks: update_tracks_thread = TrackUpdateThread( user.idx, track.idx, config.LANGUAGES[user.language]) update_tracks_thread.signals.change_statusbar.connect( self.manual_status_set) update_tracks_thread.signals.message_set.connect( self.manual_message_set) update_tracks_thread.signals.update_table.connect( self.fill_main_tree) # Execute self.threadpool.start(update_tracks_thread) # change last upd datetime track.updated_dt_update() self.fill_main_tree() else: self.statusbar.setStyleSheet("color: red") self.statusbar.showMessage( "Tracks already update recently.") self.system_alert_show("Tracks already update recently.")