def zip_recent_dls_unit(unit: str, _zip=True) -> Path: """Func for gui to find (optional zip) most recent dls folder by parsing date in folder title""" from smseventlog.gui import _global as gbl from smseventlog.gui.dialogs import msg_simple, msgbox p_dls = get_recent_dls_unit(unit=unit) if not p_dls is None: msg = f'Found DLS folder: {p_dls.name}, calculating size...' gbl.update_statusbar(msg) gbl.get_mainwindow().app.processEvents() size = fl.calc_size(p_dls) msg = f'Found DLS folder:\n\n{p_dls.name}\n{size}\n\nZip now?' if not msgbox(msg=msg, yesno=True): return else: msg = 'Couldn\'t find recent DLS folder, check folder structure for issues.' msg_simple(msg=msg, icon='warning') return if _zip: p_zip = fl.zip_folder_threadsafe(p_src=p_dls, delete=False) return p_zip else: return p_dls
def import_fc( lst_csv: list = None, upload: bool = True, df: pd.DataFrame = None, worker_thread: bool = False) -> Union[Tuple[str, str, list], None]: start = timer() if df is None: df = pd.concat([read_fc(p=p) for p in lst_csv], sort=False) \ .drop_duplicates(['FCNumber', 'Unit']) if not lst_csv is None: log.info('Loaded ({}) FCs from {} file(s) in: {}s'.format( len(df), len(lst_csv), f.deltasec(start, timer()))) # import to temp staging table in db, then merge new rows to FactoryCampaign if upload: cursor = db.cursor df.to_sql(name='FactoryCampaignImport', con=db.engine, if_exists='append', index=False) msg = 'Rows read from import files: {}'.format(len(df)) try: # FactoryCampaign Import rows = dd(int, cursor.execute('mergeFCImport').fetchall()) msg += '\n\nFactoryCampaign: \n\tRows added: {}\n\tRows updated: {}\n\tKA Completion dates added: {}' \ .format( rows['INSERT'], rows['UPDATE'], rows['KADatesAdded']) # FC Summary - New rows added rows = dd(int, cursor.execute('MergeFCSummary').fetchall()) if cursor.nextset(): msg += '\n\nFC Summary: \n\tRows added: {} \n\n\t'.format( rows['INSERT']) df2 = f.cursor_to_df(cursor) if len(df2) > 0: msg += st.left_justified(df2).replace('\n', '\n\t') for fc_number in df2.FCNumber: create_fc_folder(fc_number=fc_number) cursor.commit() except Exception as e: er.log_error(log=log) dlgs.msg_simple(msg='Couldn\'t import FCs!', icon='critical') finally: cursor.close() statusmsg = 'Elapsed time: {}s'.format(f.deltasec(start, timer())) if worker_thread: return msg, statusmsg, lst_csv else: ask_delete_files(msg, statusmsg, lst_csv)
def update_comp_smr(): from smseventlog.gui import dialogs as dlgs try: cursor = db.cursor res = cursor.execute('updateUnitComponentSMR').fetchall()[0] cursor.commit() finally: cursor.close() unit_hrs, comp_hrs = res[0], res[1] msg = f'Unit SMR updated: {unit_hrs}\nComponent SMR updated: {comp_hrs}' dlgs.msg_simple(msg=msg)
def get_db_creds() -> Dict[str, str]: m = SecretsManager('db.yaml').load driver = get_odbc_driver() if not driver is None: m['driver'] = f'{{{driver}}}' log.info(f'driver: {driver}') return m else: # raise error to user from smseventlog.gui.dialogs import msg_simple msg = 'No database drivers available, please download "ODBC Driver 17 for SQL Server" (or newer) from:\n\n \ https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-ver15' msg_simple(icon='critical', msg=msg)
def parse_units(units: str, prefix: str = None) -> list: """Parse string list/range of units, add prefix Parameters ---------- units : str list/range of units prefix : str, optional prefix to append to each unit, default None Returns ------- list list of parsed units Bool False if unit in range cannot be converted to int Examples ------- >>> fc.parse_units('301, 302--303', 'F') >>> ['F301', 'F302', 'F303'] """ # parse unit_range string units = units.split(',') # get upper/lower range if str has '-' units_range = list(filter(lambda x: '--' in x, units)) units = list(filter(lambda x: not '--' in x, units)) for _rng in units_range: rng = _rng.split('--') try: lower = int(rng[0]) upper = int(rng[1]) except Exception as e: msg = f'Values for range must be integers: "{_rng.strip()}"' dlgs.msg_simple(msg=msg, icon='warning') return False units.extend([unit for unit in range(lower, upper + 1)]) # strip whitespace, convert to str, add prefix if prefix is None: prefix = '' units = list(map(lambda x: f'{prefix}{str(x).strip()}', units)) return units
def handle_plm_result(self, rep=None, unit=None, **kw): if rep is False: # not super robust, but just warn if no rows in query msg = 'No rows returned in query, can\'t create report!' dlgs.msg_simple(msg=msg, icon='warning') if not rep or not rep.p_rep.exists(): self.update_statusbar('Failed to create PLM report.', warn=True) return self.update_statusbar(f'PLM report created for unit {unit}', success=True) msg = f'Report:\n\n"{rep.title}"\n\nsuccessfully created. Open now?' if dlgs.msgbox(msg=msg, yesno=True): rep.open_()
def __init__(self, **kw): super().__init__(**kw) username, password = CredentialManager('tsi').load() username_sms, password_sms = CredentialManager( 'sms').load() # need sms pw for new system if username is None or username_sms is None: from smseventlog.gui import dialogs as dlgs msg = 'Can\'t get TSI uesrname or password!' dlgs.msg_simple(msg=msg, icon='critical') is_init = False self.pages |= {'login': '******'} f.set_self(vars())
def get_import_files(): # load all csv files from import folder to df p = cf.p_drive / cf.config['FilePaths']['Import FC'] lst = [f for f in p.glob('*.csv')] if lst: new_files = '\n\t'.join([p.name for p in lst]) msg = f'Found file(s): \n\t{new_files}\n\nWould you like to import?' if not dlgs.msgbox(msg=msg, yesno=True): return else: msg = f'No files founnd in import folder: \n\n{p}' dlgs.msg_simple(msg=msg, icon='Warning') return return lst
def create_folder(self, show=True, ask_show=False): from smseventlog.gui import dialogs as dlgs fl.drive_exists() try: p = self._p_event p_pics = p / 'Pictures' # p_dls = p / 'Downloads' if not p.exists(): p_pics.mkdir(parents=True) # p_dls.mkdir(parents=True) if ask_show: msg = 'Event folder created. Would you like to open?' if dlgs.msgbox(msg=msg, yesno=True): self.show() elif show: self.show() except: msg = 'Can\'t create folder!' dlgs.msg_simple(msg=msg, icon='critical') log.error(msg, exc_info=True)
def show_warn_dialog(self, msg=None): from smseventlog.gui.dialogs import msg_simple msg_simple(msg)