import getpass import sys import time from pathlib import WindowsPath if sys.version_info >= (3, 11): import tomllib else: import tomli as tomllib from selenium import webdriver from selenium.common.exceptions import NoAlertPresentException, NoSuchWindowException, UnexpectedAlertPresentException from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select # Constants for configuration and element IDs EIP_URL = "https://eip.techmation.com.tw/MotorWeb/MotorFaceDefaultNew.aspx" LANG_DROPDOWN_ID = "ddlLang" LOGIN_ID_INPUT_ID = "txtLoginID" LOGIN_PWD_INPUT_ID = "txtLoginPwd" COMPANY_ID_DROPDOWN_ID = "ddlCompanyID" LOGIN_BUTTON_ID = "btnLogin" class LoginInfo(): def __init__(self, config_path: WindowsPath): with open(config_path, mode="rb") as f: config = tomllib.load(f) required_fields = ["lang", "login_ID", "login_passwd", "company_ID"] for field in required_fields: if field not in config.get("login_info", {}): raise ValueError(f"Missing required field: {field} in login_info section") self.lang = config["login_info"]["lang"] self.login_ID = config["login_info"]["login_ID"] self.login_passwd = config["login_info"]["login_passwd"] self.company_ID = config["login_info"]["company_ID"] if self.login_ID == "": self.login_ID = getpass.getpass( "please enter your ID: ").strip() if self.login_passwd == "": self.login_passwd = getpass.getpass( "please enter your passwd: ") def keep_login_status(driver: webdriver.Chrome, login_info: LoginInfo) -> bool: """ Attempt to log into the CHI MotorWeb ERP system using the provided login information. This function navigates to the login page, fills in the login form with the user’s credentials, and attempts to log in. It handles unexpected alert pop-ups that indicate login failure, and manages browser windows to ensure only the relevant page remains open. Args: driver (webdriver.Chrome): An instance of Selenium WebDriver controlling a Chrome browser. login_info (LoginInfo): A data object containing login credentials and preferences. Returns: bool: True if login is successful or already logged in; False if login failed (e.g., due to incorrect credentials). """ # * Close all windows except the main window. while len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) time.sleep(0.05) driver.close() driver.switch_to.window(driver.window_handles[0]) top_page = driver.current_window_handle driver.get(EIP_URL) time.sleep(0.3) if driver.title == "CHI MOTOR WEB ERP 登入": # * Fill in all login information. dropdown_element = driver.find_element(By.ID, LANG_DROPDOWN_ID) select = Select(dropdown_element) select.select_by_value(login_info.lang) input_text_element = driver.find_element(By.ID, LOGIN_ID_INPUT_ID) input_text_element.clear() input_text_element.send_keys(login_info.login_ID) input_text_element = driver.find_element(By.ID, LOGIN_PWD_INPUT_ID) input_text_element.clear() input_text_element.send_keys(login_info.login_passwd) dropdown_element = driver.find_element(By.ID, COMPANY_ID_DROPDOWN_ID) select = Select(dropdown_element) select.select_by_value(login_info.company_ID) # * Press the submit button. submit_btn = driver.find_element(By.ID, LOGIN_BUTTON_ID) submit_btn.click() time.sleep(1) # * Check if login failed (alert popup) try: alert = driver.switch_to.alert print(f"Login error message: {alert.text}") alert.accept() return False # Skip remaining logic, login failed except (NoAlertPresentException, NoSuchWindowException): pass # No alert, proceed time.sleep(2) login_page_handle = "" main_page_handle = "" for handle in driver.window_handles: driver.switch_to.window(handle) try: title = driver.title except UnexpectedAlertPresentException: try: alert = driver.switch_to.alert print(f"Unexpected alert: {alert.text}") alert.accept() continue except (NoAlertPresentException, NoSuchWindowException): continue if "CHI MotorWeb - " in title: main_page_handle = handle elif "CHI MOTOR WEB ERP 登入" in title: login_page_handle = handle stay_page_handle = main_page_handle or login_page_handle or top_page # * close unnecessary pages for handle in driver.window_handles: if handle != stay_page_handle: try: driver.switch_to.window(handle) driver.close() except Exception as e: print(f"Error closing window {handle}: {e}") driver.switch_to.window(stay_page_handle) driver.maximize_window() return True elif "CHI MotorWeb - " in driver.title: return True