def clockout(self): logger.info('Clockout starts.') fc = FingerprintController() if fc == None: self.controller.show_info("Vuelve a intentarlo", True) else: template = fc.search_user() del fc # check template found if template < 0: self.controller.show_info("Usuario desconocido", True) return user = get_user_by_template(template, session_factory()) username = user.name result = add_logout2(user, session_factory()) if 0 == result: txt = "Hasta pronto {username}" self.controller.show_info(txt.format(username=username)) elif 1 == result: txt = "{username} primero tienes que entrar" self.controller.show_info(txt.format(username=username), True) elif 2 == result: txt = "{username} no puedes salir dos veces consecutivas" self.controller.show_info(txt.format(username=username), True) else: self.controller.show_info("Fallo desconocido", True) logger.info('Clockout finished.')
def clockin(self): logger.info('Clockin starts.') fc = FingerprintController() if fc == None: logger.info('pyfingerprint could not be initialized') self.controller.show_info("Vuelve a intentarlo", True) else: template = fc.search_user() del fc # check template found if template < 0: self.controller.show_info("Usuario desconocido.", True) return user = get_user_by_template(template, session_factory()) username = user.name result = add_login2(user, session_factory()) if result: txt = "Bienvenido/a {username}" self.controller.show_info(txt.format(username=username)) else: txt = "{username} no se puede fichar la entrada dos veces consecutivas" self.controller.show_info(txt.format(username=user.name), True) logger.info('Clockin finished.')
def delete_user(self, username): user = models.get_user_by_name(username, models.session_factory()) if None == user: logger.info('User \"{}\" does not exists and can not be deleted.', username) return position = user.template models.delete_user(username, models.session_factory()) self.f.deleteTemplate(position) logger.info('User \"{}\" with template position #{} deleted.', username, str(position))
def create_users(api): logger.info("KIMAI2 => Creating users") # check and collect info try: tz = models.get_timezone(models.session_factory()).value lang = models.get_language(models.session_factory()).value except Exception: logging.exception("Failed to create users") logger.info("KIMAI2 => Finished creating users") return if tz is None: logger.error("Failed to create user in kimai2, no timezone defined.") logger.info("KIMAI2 => Finished creating users") return elif lang is None: logger.error("Failed to create user in kimai2, no language defined.") logger.info("KIMAI2 => Finished creating users") return # collect not created users session = models.session_factory() users = models.get_new_kimai2_users(session) users_counter = 0 # create users for user in users: try: resp = api.create_user(user.k2_name, user.k2_email, lang, tz, user.k2_password) if resp.status_code != 200: # wrong hhtp response, log error logger.error("Failed to create user in Kimai2") logger.error("Status: {}, Values: {}, {}, {}, {} {}".format( str(resp.status_code), user.k2_name, user.k2_email, lang, tz, user.k2_password)) logger.error(resp.json()) else: # right http response, update local database obj = resp.json() models.set_user_kimai2_id(user, obj['id'], session) logger.info("User created: {}, {}".format( obj['id'], obj['username'])) users_counter += 1 except Exception: logging.exception(f"Failed to create user {user.name}") session.close() logger.info(f"Total users created: {users_counter}") logger.info("KIMAI2 => Finished creating users")
def add_user_step2(self, username): try: print('Waiting for finger...') ## Wait that finger is read again while self.f.readImage() == False: pass ## Converts read image to characteristics and stores it in charbuffer 2 self.f.convertImage(0x02) ## Compares the charbuffers if self.f.compareCharacteristics() == 0: return self.RESULT_FINGER_DO_NOT_MATCH ## Creates a template self.f.createTemplate() ## Saves template at new position number template_index = self.f.storeTemplate() logger.info( 'Finger enrolled successfully. New template position #{}', str(template_index)) ## save user in DB models.add_user(username, template_index, models.session_factory()) return 0 except Exception as e: logger.exception('Error while adding a user (step2).') return self.RESULT_ERROR
def export_data_to_usb(): logger.info('Export data to the USB starts.') try: usb_path = "/media/pi/" # check usb has been mounted if not os.path.exists(usb_path): logger.error('The USB is not mounted.') return 2 # check there is a directory to write dirs = os.listdir(usb_path) if len(dirs) != 1: logger.error('The USB has an unexpected directory structure.') return 3 # export file into usb destination = usb_path + dirs[0] + "/registro_horario/" pathlib.Path(destination).mkdir(parents=True, exist_ok=True) company = get_company_short(session_factory()).value filename = company + "_" + datetime.datetime.now().strftime( "%Y-%m-%d-%H-%M-%S") + "_" + SQLITE_EXPORT_FILE _export_database_logs(destination + filename) logger.info( 'Export data to the USB finished. Data exported to the USB.') return 0 except Exception: logger.exception('Errors while exporting database data to the USB.') return R_ERROR
def create_team(api, force=False): logger.info("KIMAI2 => Creating team") try: # check if is already created team = models.get_team(models.session_factory()).k2_id if team is not None and not force: logger.info("Team no created. Team already exists.") logger.info("KIMAI2 => Finished creating a team") return # check 2 leader_id = models.get_leader(models.session_factory()).k2_id name = models.get_company_short(models.session_factory()).value if leader_id is None: logging.error( "Failed to create a team in Kimai2. There is no team leader.") logger.info("KIMAI2 => Finished creating a team") return if name is None: logging.error( "Failed to create a team in Kimai2. There is no company name.") logger.info("KIMAI2 => Finished creating a team") return # create team in Kimai2 resp = api.create_team(name, leader_id) if resp.status_code != 200: logger.error("Failed to create a team in Kima2: %s", name) logger.error("Status: {}, Values: {}, {}".format( str(resp.status_code), name, leader_id)) logger.error(resp.json()) return # update local database obj = resp.json() models.set_team(name, models.session_factory(), leader_id) logger.info("Team created: {}, {}".format(obj['id'], obj['name'])) except Exception: logging.exception("Failed to create a team in Kimai2") logger.info("KIMAI2 => Finished creating a team")
def upload_database(): # find out filename to export uuid = get_uuid(session_factory()).value filename = uuid + "_" + datetime.datetime.now().strftime( "%Y-%m-%d-%H-%M-%S") + "_" + SQLITE_EXPORT_FILE # export file _export_database_logs(filename) # upload file ssh = _create_ssh_client() scp = SCPClient(ssh.get_transport()) scp.put(filename, filename) scp.close() # delete local exported file delete_file(SQLITE_EXPORT_FILE) # delete uploaded data from database session = session_factory() truncate_user_actions(session)
def create_team_leader(api, force=False): logger.info("KIMAI2 => Creating team leader") try: # check if is already created leader_id = models.get_leader(models.session_factory()).k2_id if leader_id is not None and not force: logger.info("Team leader no created. Team leader already exists.") logger.info("KIMAI2 => Finished creating team leader") return # collect info username = models.get_leader(models.session_factory()).value email = models.get_leader_email(models.session_factory()).value lang = models.get_language(models.session_factory()).value tz = models.get_timezone(models.session_factory()).value password = models.get_leader_password(models.session_factory()).value # create team leader in Kimai2 resp = api.create_team_leader(username, email, lang, tz, password) if resp.status_code != 200: logger.error("Failed to create team leader in Kimai2: %s", username) logger.error("Status: {}, Values: {}, {}, {}, {}".format( str(resp.status_code), username, email, lang, tz)) logger.error(resp.json()) return # update local database obj = resp.json() models.set_leader(obj['username'], models.session_factory(), obj['id']) logger.info("Team leader created: {}, {}".format( obj['id'], obj['username'])) except Exception: logging.exception("Failed to create a team leader in Kimai2") logger.info("KIMAI2 => Finished creating team leader")
def create_project(api, force=False): logger.info("KIMAI2 => Creating project") try: # check if is already created project = models.get_project(models.session_factory()) if project is not None and project.k2_id is not None and not force: logger.info("Project no created. Project already exists") logger.info("KIMAI2 => Finished creating a project") return # check leader = models.get_leader(models.session_factory()) if leader is None or leader.k2_id is None: logging.exception( "Failed to create a project in Kimai2. There is no team leader." ) return # collect info name = models.get_company_short(models.session_factory()).value customer = models.get_customer(models.session_factory()).k2_id color = models.get_color(models.session_factory()).value # create project in Kimai2 resp = api.create_project(name, customer, color) if resp.status_code != 200: logger.error("Failed to create project in Kimai2: %s", name) logger.error("Status: {}, Values: {}, {}, {}".format( str(resp.status_code), name, customer, color)) logger.error(resp.json()) return # update local database obj = resp.json() models.set_project(obj['name'], models.session_factory(), obj['id']) logger.info("Project created: {}, {}".format(obj['id'], obj['name'])) except Exception: logging.exception("Failed to create project in Kimai2") logger.info("KIMAI2 => Finished creating a project")
def create_customer(api, force=False): logger.info("KIMAI2 => Creating customer") try: # check if is already created customer = models.get_customer(models.session_factory()) if customer is not None and customer.k2_id is not None and not force: logger.info("Customer no created. Customer already exists") logger.info("KIMAI2 => Finished creating a customer") return # collect info name = models.get_company_short(models.session_factory()).value country = models.get_country(models.session_factory()).value tz = models.get_timezone(models.session_factory()).value currency = models.get_currency(models.session_factory()).value color = models.get_color(models.session_factory()).value # create customer in Kimai2 resp = api.create_customer(name, country, currency, tz, color) if resp.status_code != 200: logger.error("Failed to create customer in Kimai2: %s", name) logger.error("Status: {}, Values: {}, {}, {}, {}".format( str(resp.status_code), name, country, tz, color)) logger.error(resp.json()) return # update local database obj = resp.json() models.set_customer(obj['name'], models.session_factory(), obj['id']) logger.info("Customer created: {}, {}".format(obj['id'], obj['name'])) except Exception: logging.exception("Failed to create customer in Kimai2") logger.info("KIMAI2 => Finished creating a customer")
def create_timesheets(): logger.info("KIMAI2 => Creating teamsheats") # checks try: project = models.get_project(models.session_factory()).k2_id tz = models.get_timezone(models.session_factory()).value password = models.get_user_password(models.session_factory()).value url = KIMAI2_URL if project is None: logger.error( "Failed to create timesheet in kimai2, no project id.") return if tz is None: logger.error( "Failed to create timesheet in kimai2, no timezone defined.") return if password is None: logger.error( "Failed to create timesheet in kimai2, no user password defined." ) return # fetch all timesheets to be uploaded session = models.session_factory() timesheets = models.get_new_kimai2_timesheets(session) except Exception: logging.exception("Failed to create timesheets") # create timesheets total_ts = 0 for ts in timesheets: # collect data try: utc_begin = local_date_to_utc(ts.begin, tz) utc_end = local_date_to_utc(ts.end, tz) kimai2_begin = date_to_kimai_date(utc_begin) kimai2_end = date_to_kimai_date(utc_end) # api manager ##user_k2_id = models.get_user_by_id(ts.user_id).k2_id if ts.user.k2_id is None: logger.error( "Failed to create timesheet in kimai2, user does not exists in kimai2." ) return api = Kimai2RestClient.Kimai2API(ts.user.k2_name, ts.user.k2_password, url) resp = api.create_timesheet(kimai2_begin, kimai2_end, project, 1) if resp.status_code != 200: # wrong hhtp response, log error logger.error("Failed to create timesheet in Kimai2") logger.error("Status: {}, Values: {}, {}, {}, {}".format( str(resp.status_code), ts.user.k2_name, ts.user.k2_password, ts.begin, ts.end)) logger.error(resp.json()) else: # right http response, update local database obj = resp.json() models.set_timesheet_kimai_id(ts, obj['id'], session) logger.info("Timesheet created: {}, {}".format( kimai2_begin, kimai2_end, project, 1)) total_ts += 1 except Exception: logging.exception("Failed to create a single timesheet") session.close() logger.info(f"Total timesheets created: {total_ts}") logger.info("KIMAI2 => Finished creating timesheets")
def exists_user(self, username): return models.exists_user(username, models.session_factory())