In [ ]:
from time import sleep, time
import cyschoolhousesuite as cysh
from pandas import read_excel
import logging as log
from pathlib import Path

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC

In [2]:
def configure_log():
    """Configures the log for update cycle
    
    Generates a log file for this session. Uses a timestamp from the time library to as a part
    of the name. 
    """
    log_path = '/'.join([str(Path.home()), 'OneDrive/Documents/GitHub/cy-automation-library/cyautomation/cyschoolhouse'])
    timestamp = str(time()).split(".")[0]
    log.basicConfig(filename="".join([log_path, '/log/student_enrollment_', timestamp, '.log']), level=log.INFO)
    
def search_for_section(driver, sec_num):
    """ Search function for finding the specified intervention section 
    """
    # Update the search scope to sections (helps find the section w/o going to secondary screen)
    selector = Select(driver.find_element_by_name("sen"))
    selector.select_by_visible_text("Sections")
    
    # Clear contents of search box, enter the given section number, and wait for the screen to load.
    driver.find_element_by_class_name("searchTextBox").clear()
    driver.find_element_by_class_name("searchTextBox").send_keys(sec_num)
    driver.find_element_by_name("search").click()
    
    # Open Section Intervention Data
    open_section_intervention_data(driver)
    
def open_section_intervention_data(driver):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "section_intervention_data")))
    # Once it's loaded, click on Section Intervention Data
    driver.find_element_by_name("section_intervention_data").click()

def enrollment_window(driver):
    """ Function for engaging with the student enrollment window
    Args:
    
    Returns:
        bool: False if this function encounters an error, True otherwise. 
    """
    def select_add_button(driver):
        driver.find_element_by_id("addButton").click()
        WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "j_id0:j_id48:enrollDate")))
        
    sleep(1)
    driver.switch_to_window(driver.window_handles[1])
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "addButton")))
    try:
        select_add_button(driver)
    except:
        log.error("Exception Caught, trying again")
        select_add_button(driver)
        
def enter_enrollment_date(driver):
    driver.find_element_by_id("j_id0:j_id48:enrollDate").clear()
    driver.find_element_by_id("j_id0:j_id48:enrollDate").send_keys('8/14/2017')
    
def select_student_from_enrollment_table(driver, sfid):
    log.info("selecting student {}".format(sfid))
    table = driver.find_element_by_xpath("//table[@id='availableStudents']/tbody")
    student = table.find_element_by_xpath("//tr[starts-with(@id, '" + sfid + "') and not(contains(@style, 'display: none'))]")
    print(student.text)
    student.click()
    log.info("Finished clicking, now waiting")
    sleep(2)
    return student
    
def enrollement_student_search(driver, name):
    driver.find_element_by_name("filterBox").clear()
    driver.find_element_by_name("filterBox").send_keys(name)
    
def enroll_batch(driver):
    log.info('starting batch enrollement')
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//img[@src='/resource/1496397506000/Style_Bundle/images/arrow-right.png']")))
    driver.find_element_by_xpath("//img[@src='/resource/1496397506000/Style_Bundle/images/arrow-right.png']").click()

def update_gl(driver, _grade):
    selector = Select(driver.find_element_by_name("j_id0:j_id48:j_id103"))
    selector.select_by_index(1)
    sleep(3)
    selector = Select(driver.find_element_by_name("j_id0:j_id48:j_id103"))
    selector.select_by_visible_text(_grade)
    
def save_enrollments(driver):    
    driver.find_element_by_xpath("//input[@value='Save']").click()
    
def input_data():
    data = read_csv('input_files/section-key.csv')
    return data.to_dict(orient='records')

In [3]:
def enrollment_script():
    configure_log()
    data = read_excel('input_files/student-enrollment-records.xlsx')
    staff = data['Intervention Primary Staff: Staff Name'].unique()
    for _staff in staff:
        driver = cysh.get_driver()
        try:
            cysh.open_cyschoolhouse18(driver)
        except:
            log.error("Error occured while logging in")
            driver.close()
            driver = cysh.get_driver()
            cysh.open_cyschoolhouse18(driver)
        staff_records = data[data['Intervention Primary Staff: Staff Name'] == _staff]
        sections = staff_records['Intervention Section Number'].unique()
        for _section in sections:
            search_for_section(driver, str(_section))
            try:
                enrollment_window(driver)
            except:
                log.error("Enrollment window error on {}".format(_section))
                continue
            enter_enrollment_date(driver)
            section_records = staff_records[staff_records['Intervention Section Number'] == _section]
            relevant_grades = section_records['Grade'].unique()
            for _grade in relevant_grades:
                update_gl(driver, str(_grade))
                sleep(2)
                students_in_gl = section_records[section_records.Grade == _grade]
                students_to_enroll = students_in_gl['Student ID'].unique()
                for _student in students_to_enroll:
                    #lastname = str(students_in_gl[students_in_gl['Student ID'] == _student]['Last Name'].values[0])
                    #enrollement_student_search(driver, lastname)
                    sleep(2)
                    try:
                        select_student_from_enrollment_table(driver, _student)
                    except:
                        log.error("Missed student {} from list".format(_student))
                        continue
                    enroll_batch(driver)
                    sleep(2)
            save_enrollments(driver)
            sleep(2)
            driver.close()
            driver.switch_to_window(driver.window_handles[0])
        driver.quit()

In [5]:
enrollment_script()


LEON, VALERIA A. 8
ANTUNA, LIZBETH A. 9
ROMERO, NATHALIE 9
BARRALES RODRIGUEZ, PILAR 9
LOPEZ, JASMINE 9
CRUZ, FABIOLA 9
DIAZ, KEVIN J. 9
GARCIA, ALEXIS 9
RAMIREZ, JOSE 7
GARCIA, JOCELYN 7
LOPEZ, ESBHEIDI A. 7
DE JESUS, VICTORIA 6
HUITRON, WILLIAM 9
SALDANA, TIMMY A. 9
MEZA, KARINA 9
AYALA ROJAS, DULCE M. 9
CARRAZCO MOLINA, YAHIR A. 9
MORALES-REYES, VICTOR E. 9
SERNA-CRUZ, DANIEL 8
ARNAL, MICHAEL R. 9
NAVARRO, JOCELIN G. 9
CAYETANO, YVONNE 9
JIMENEZ, CESAR 9
MORENO, LESLIE G. 9
ORDONEZ, HAYDEE Y. 9
ALVAREZ, DARLENE 6
FONSECA, MYA B. 9
BONILLA, IVIS M. 9
GALLEGOS, KAIN 9
ZAMUDIO, IRIS Y. 9
MARIN, ALFONZO D. 9
BENITEZ, ANTONIO J. 9
CORTES, MARK A. 6
PEREZ, DIANA 6
GODINEZ, DAMIAN H. 9
ALONZO, JUDITH B. 9
NAVA, ANGEL 9
SANCHEZ, NATALIA M. 9
MORALES, AARON S. 9
HERNANDEZ, GENESIS I. 9
ALVAREZ PENA, SAMANTHA 7
DIAZ-FIGUEROA, BRYAN 9
CRESCENCIO, FREDDY 9
FRANCO, MARIA JOSE 9
MORALES, EVELYN 9
ANAYA, DAYHANARA W. 9
MARAVILLAS-ROJAS, LEONARDO 9
ANAYA, DAYHANARA W. 9
ANAYA, JIMMY 8
SANCHEZ, DEYANARA B. 9
URIBE, ALEX A. 9
PEREZ, JADE N. 9
RODELA, JORGE 9
ROJAS, DAMARIS 9
SANCHEZ, DEYANARA B. 9
GARCIA, ALEJANDRO 9
GARCIA, ALEJANDRO 9
AVILA, JORGE D. 10
CARDENAS, LUCY S. 4
CASTELLANOS, HENRY A. 4
BRAVO, STEVEN S. 5
AYALA, JOHN A. 4
ANDRADE-GARCIA, ALINA 3
DE LA CRUZ, CHELSEA 8
AMAYA, ALLEN 9
ALFARO, DAVIS J. 7
ALVAREZ, DIAMOND A. 9
BIG SOLDIER, HEATHER A. 4
BARNES, JORDAN M. 3
PADILLA, ADRIAN 6
MONEY, DORSHONA H. 8

In [ ]: