File size: 6,606 Bytes
fca0b38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import logging
import time
import sys
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ActionChains
from webdriver_manager.chrome import ChromeDriverManager

# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

def switch_to_iframe_with_text(driver, text_to_find, timeout=5):
    """Switch to the iframe containing specific text."""
    driver.switch_to.default_content()
    all_iframes = driver.find_elements(By.TAG_NAME, "iframe")
    logger.info(f"Found {len(all_iframes)} iframes on page")

    for idx, iframe in enumerate(all_iframes):
        driver.switch_to.default_content()
        driver.switch_to.frame(iframe)
        try:
            if text_to_find.lower() in driver.page_source.lower():
                logger.info(f"Found '{text_to_find}' in iframe #{idx}")
                return True
        except Exception as e:
            logger.warning(f"Error reading iframe #{idx}: {e}")
    driver.switch_to.default_content()
    return False

def main(customer, user, pwd):
    logger.info(f"Starting sitearea creation for customer: {customer}")

    chrome_options = Options()
    chrome_options.add_argument("--headless=new")  # Headless mode
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("start-maximized")

    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    wait = WebDriverWait(driver, 20)

    try:
        # --- LOGIN ---
        driver.get("https://xindus-01.infiplex.com/admin/admin_login.php")
        wait.until(EC.presence_of_element_located((By.ID, 'uname'))).send_keys(user)
        driver.find_element(By.ID, 'password').send_keys(pwd)
        driver.find_element(By.ID, 'submit').click()
        logger.info("Logged in successfully")
        time.sleep(2)

        # --- CREATE SITEAREA ---
        driver.get("https://xindus-01.infiplex.com/admin/sitearea/siteareaadd.php")
        wait.until(EC.presence_of_element_located((By.ID, "sitearea_name"))).send_keys(customer)
        driver.find_element(By.ID, "base_folder").send_keys(customer)
        driver.find_element(By.ID, "content_section_name").send_keys(customer)
        driver.find_element(By.ID, "_content_section_security_group_all_users_yes").click()

        # Applications tab
        driver.find_element(By.LINK_TEXT, "Applications").click()
        app_ids = [325, 320, 317, 342, 322, 346, 393, 387, 336, 31, 195, 293, 5, 384, 340, 344, 3, 334, 327, 7]
        for app_id in app_ids:
            driver.find_element(By.ID, f"install_app_yes_no_{app_id}").click()

        save_buttons = driver.find_elements(By.ID, "submit")
        save_button = save_buttons[1]
        driver.execute_script("arguments[0].scrollIntoView();", save_button)
        save_button.click()
        logger.info("Sitearea created and saved")

        # --- NAVIGATE TO CUSTOMER SHOP PAGE ---
        driver.get("https://xindus-01.infiplex.com/admin/index.php")
        links = driver.find_elements(By.TAG_NAME, "a")
        for link in links:
            href_value = link.get_attribute("href")
            if href_value and customer in href_value:
                driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", link)
                driver.execute_script("arguments[0].click();", link)
                logger.info(f"Clicked customer link for {customer}")
                break
        time.sleep(3)

        # --- SWITCH TO IFRAME WITH TOOLS ---
        logger.info("Searching for iframe containing 'Tools'")
        if not switch_to_iframe_with_text(driver, "Tools"):
            logger.error("Could not find iframe containing 'Tools'")
            return None

        # --- TOOLS → SHOP ADMIN API ---
        logger.info("Navigating to Tools → Shop Admin API")
        tools_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(., 'Tools')]")))

        # If hover menu
        try:
            ActionChains(driver).move_to_element(tools_link).perform()
            time.sleep(1)
        except:
            pass
        tools_link.click()

        api_tab = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(., 'Shop Admin API')]")))
        api_tab.click()
        time.sleep(2)

        # --- CHECK OR CREATE API KEY ---
        no_results = driver.find_elements(By.XPATH, "//h3[text()='No Results Found']")
        if no_results:
            logger.info("No API key found, creating a new one")
            create_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(text(), 'Create New API Key')]")))
            create_button.click()
            time.sleep(1)
            driver.switch_to.frame(driver.find_element(By.XPATH, "//iframe[contains(@src, 'admin_api_add_edit.php')]"))
            wait.until(EC.presence_of_element_located((By.ID, "reference_name"))).send_keys("StoreAPI")
            checkboxes = driver.find_elements(By.XPATH, "//td[@style='text-align:left;vertical-align:top;']//input[@type='checkbox']")
            for cb in checkboxes:
                if not cb.is_selected():
                    cb.click()
            driver.find_element(By.ID, "submit").click()
            logger.info("API key created")
            driver.switch_to.default_content()
            switch_to_iframe_with_text(driver, "Shop Admin API")

        # --- FETCH API KEY ---
        logger.info("Fetching API key from table")
        api_key_elem = wait.until(EC.presence_of_element_located((By.XPATH, "//tr[td[1]]/td[2]")))
        api_key = api_key_elem.text.strip()

        if not api_key:
            raise Exception("Found API key element but it was empty.")

        logger.info(f"API Key for {customer}: {api_key}")
        return api_key

    except Exception as e:
        logger.error(f"Error: {e}", exc_info=True)
        try:
            with open('debug_page_source.html', 'w', encoding='utf-8') as f:
                f.write(driver.page_source)
            driver.save_screenshot('debug_screenshot.png')
            logger.info("Saved debug files: debug_page_source.html & debug_screenshot.png")
        except:
            pass
        return None
    finally:
        driver.quit()