def getStudentProfileForm():
    studentID = ObjectId(request.json['student_id'])
    form_id = ObjectId(request.json['form_id'])

    form_data = FormsDOM.getFormData(ObjectId(form_id))

    blank_form_id = FormsDOM.getBlankFormId(form_id)
    blank_form_data = blankFormsDOM.getFormData(blank_form_id)

    parent_id = FormsDOM.getInfo(form_id, 'parent_id')
    parent_profile = parentsDOM.getParentProfile(parent_id)
    cleaned_parent_profile = {}
    cleaned_parent_profile['first_name'] = parent_profile['first_name']
    cleaned_parent_profile['last_name'] = parent_profile['last_name']
    cleaned_parent_profile['email'] = parent_profile['email']

    form_info = {}
    form_info['name'] = blankFormsDOM.getFormName(blank_form_id)
    form_info['last_updated'] = FormsDOM.getLastUpdated(form_id)
    form_info['completed'] = FormsDOM.isComplete(form_id)

    isAuthorizedBool = isAuthorized(get_token_auth_header(),
                                    ['developer', 'admin'])
    return {
        'form_data': form_data,
        'blank_form_data': blank_form_data,
        'basic_info': studentsDOM.getBasicInfo(studentID),
        'parent_profile': cleaned_parent_profile,
        'form_info': form_info,
        'isAuthorized': isAuthorizedBool,
    }
def resendForm(studentId, newBlankFormIds):
    blankFormIds = map(lambda form: FormsDOM.getBlankFormId(form),
                       studentsDOM.getForms(studentId))

    uniqueBlankFormIds = set(blankFormIds)

    parentIds = studentsDOM.getParents(studentId)

    formIds = []

    additionalBlankForms = []

    for newBlankFormId in newBlankFormIds:
        if newBlankFormId not in uniqueBlankFormIds:
            for parentId in parentIds:
                currID = FormsDOM.createForm(newBlankFormId, None, None, True,
                                             False, [], parentId)
                formIds.append(currID)
            additionalBlankForms.append(newBlankFormId)

    for formId in formIds:
        studentsDOM.addNewFormId(studentId, formId)

    # return parentIds
    return parentIds
def deleteStudents(toDeleteStudents):
    parentsToUpdate = set()
    for student in toDeleteStudents:
        studentsDOM.deleteStudent(student['_id'])
        for formId in student['form_ids']:
            parentsToUpdate.add((FormsDOM.getParentID(formId), student['_id']))
            FormsDOM.deleteForm(formId)

    for (parentId, studentId) in parentsToUpdate:
        parentsDOM.removeStudentId(parentId, studentId)
def submitForm():
    curr_link = request.json['curr_link']
    try:
        parentId = parentsDOM.get(currLink=curr_link)
    except AssertionError as e:
        raise AuthError({'wrong link': True}, 401)

    form_id = request.json['form_id']
    answer_data = request.json['answer_data']
    FormsDOM.updateFormData(form_id, answer_data)
    return '0'
def submitForm():
    curr_link = request.json['curr_link']
    try:
        parent_id = parentsDOM.get(currLink=curr_link)
    except AssertionError as e:
        raise AuthError({'wrong link': True}, 401)

    if parentsDOM.isExpired(parent_id):
        emailParent(parent_id, '', 'Your updated link is below:')
        raise AuthError({'expired': True}, 426)

    form_id = request.json['form_id']
    answer_data = request.json['answer_data']
    FormsDOM.updateFormData(form_id, answer_data)
    return '0'
def getStudents():
    blankFormIds = list(
        map(lambda currForm: ObjectId(currForm['id']),
            request.json['blankForms']))
    noBlankFormFilter = len(
        blankFormIds) == 0  # hoping caching will reduce complexity

    students = studentsDOM.getStudents()
    studentsWithForms = []
    for student in students:
        if noBlankFormFilter:
            forms_completed = 0
            for form in student['form_ids']:
                if FormsDOM.isComplete(form):
                    forms_completed += 1
            student['forms_completed'] = str(forms_completed) + "/" + str(
                len(student['form_ids']))
            student['completion_rate'] = forms_completed / len(
                student['form_ids'])
            del student['form_ids']
            studentsWithForms.append(student)

        else:
            forms_completed = 0
            forms_available = 0
            for form in student['form_ids']:
                currFormBlankFormId = FormsDOM.getBlankFormId(form)
                if currFormBlankFormId in blankFormIds:
                    if (FormsDOM.isComplete(form)):
                        forms_completed += 1
                    forms_available += 1

            if forms_available > 0:
                student['forms_completed'] = str(forms_completed) + "/" + str(
                    forms_available)
                student['completion_rate'] = forms_completed / forms_available
                del student['form_ids']
                studentsWithForms.append(student)
    return {
        'students': studentsWithForms,
        'authorized': isAuthorized(get_token_auth_header(),
                                   ['developer', 'admin']),
        'forms': blankFormsDOM.getAll(),
    }
def resetForm():
    form_id = ObjectId(request.json['form_id'])
    newData = FormsDOM.clearForm(form_id)

    newData['_id'] = str(newData['_id'])
    newData['blank_forms_id'] = str(newData['blank_forms_id'])
    newData['parent_id'] = str(newData['parent_id'])

    return {
        'new_form_info': newData,
    }
def getForm():
    curr_link = request.json['curr_link']
    try:
        parentId = parentsDOM.get(currLink=curr_link)
    except AssertionError as e:
        raise AuthError({'wrong link': True}, 401)

    if parentsDOM.isExpired(parent_id):
        emailParent(parent_id, '', 'Your updated link is below:')
        raise AuthError({'expired': True}, 426)

    form_id = ObjectId(request.json['form_id'])
    blank_form_id = FormsDOM.getBlankFormId(form_id)
    blank_form_data = blankFormsDOM.getFormData(blank_form_id)
    form_data = FormsDOM.getFormData(form_id)

    return {
        'blank_form_data': blank_form_data,
        'form_data': form_data,
        'submitted': form_data != [],
    }
def getStudentForms():
    student_id = ObjectId(request.json['student_id'])
    curr_link = request.json['parent_key']
    try:
        parentId = parentsDOM.get(currLink=curr_link)
    except AssertionError as e:
        raise AuthError({'wrong link': True}, 401)

    if studentsDOM.isArchived(student_id):
        raise AuthError({'archived': True}, 401)

    if parentsDOM.isExpired(parent_id):
        emailParent(parent_id, '', 'Your updated link is below:')
        raise AuthError({'expired': True}, 426)

    form_ids = studentsDOM.getAllFormIds(student_id)
    form_data = []
    for id in form_ids:
        if parent_id == FormsDOM.getParentId(id):
            blank_form_data = FormsDOM.getBlankFormId(
                id)  # will assert if formid does not exist
            form_data.append({
                'form_id': str(id),
                'form_name': FormsDOM.getFormName(id),
                'last_updated': FormsDOM.getLastUpdated(id),
                'last_viewed': FormsDOM.getLastViewed(id),
                'completed': FormsDOM.isComplete(id)
            })
    return {
        'form_data': form_data,
        'student_info': studentsDOM.getBasicInfo(student_id),
    }
def addStudent():
    student = request.json['studentData']

    parentIds = []
    parents = request.json['parentData']
    for parent in parents:
        currID = None
        if parentsDOM.exists(parent['email']):
            currID = parentsDOM.get(email=parent['email'])
        else:
            currID = parentsDOM.createParent(parent['firstName'],
                                             parent['lastName'],
                                             parent['email'])
        parentIds.append(currID)

    formIds = []
    for form in request.json['forms']:
        for parentId in parentIds:
            id = form['id']
            # createForm(id, date, required, comp, data, parentID):
            currID = FormsDOM.createForm(ObjectId(id), None, None, True, False,
                                         [], parentId)
            formIds.append(currID)

    dateOfBirth = datetime.strptime(student['dob'], '%m/%d/%Y')
    studentId = studentsDOM.createStudent(student['firstName'],
                                          student['middleName'],
                                          student['lastName'], dateOfBirth,
                                          int(student['grade']), formIds,
                                          parentIds, student['class'])

    for parentId in parentIds:
        parentsDOM.addStudentId(parentId, studentId)

    # send emails
    failed = []

    for parentId in parentIds:
        failed = failed + emailParent(parentId)

    return {
        'failed': failed,
    }
def testFormCreateForm():
    newData = {'0': 1000}
    FormsDOM.createForm('1000', '1212-12-12', True, 123, 0.22, newData)
    actual = FormsDOM.getFormData('1000')
    return newData == actual
def testFormUpdateFormData():
    expected = {'0': 0, '1': 1, '2': 0, '3': 1, '123': 321}
    FormsDOM.updateFormData('010', 123, 321)
    actual = FormsDOM.getFormData('010')
    return actual == expected
def testFormDeleteForm():
    expected = None
    FormsDOM.deleteForm('020')
    actual = FormsDOM.getFormData('020')
    return expected == actual
def testFormGetFormData():
    expected = {'0': 0, '1': 1, '2': 0, '3': 1}
    actual = FormsDOM.getFormData('000')
    return expected == actual
def testFormGetInfo():
    expected = True
    actual = FormsDOM.getInfo('000', 'required')
    return expected == actual
def changeStatus():
    form_id = ObjectId(request.json['form_id'])
    status = request.json['form_status']
    FormsDOM.changeCompletion(form_id, status)
    newStatus = not status
    return {'status': newStatus}
def getForms():
    return {'forms': FormsDOM.getForms()}
def submitFormAuth():
    form_id = request.json['form_id']
    answer_data = request.json['answer_data']
    FormsDOM.updateFormData(form_id, answer_data)
    return '0'
def getStudentProfile():
    studentID = ObjectId(request.json['id'])
    students_forms = studentsDOM.getForms(studentID)
    forms = []
    for formId in students_forms:
        curr_form_data_raw = FormsDOM.getForm(formId)
        formName = blankFormsDOM.getBlankFormName(
            curr_form_data_raw['blank_forms_id'])
        formYear = blankFormsDOM.getFormYear(
            curr_form_data_raw['blank_forms_id'])
        formTag = blankFormsDOM.getFormTag(
            curr_form_data_raw['blank_forms_id'])
        curr_form_data = dict()
        curr_form_data['form_name'] = str(formName)
        curr_form_data['form_year'] = str(formYear)
        curr_form_data['form_tag'] = str(formTag)
        curr_form_data['form_id'] = str(curr_form_data_raw['_id'])
        curr_form_data['blank_forms_id'] = str(
            curr_form_data_raw['blank_forms_id'])
        curr_form_data['last_updated'] = curr_form_data_raw['last_updated']
        curr_form_data['completed'] = FormsDOM.isComplete(formId)
        parent_data = parentsDOM.getParentProfile(
            ObjectId(curr_form_data_raw['parent_id']))
        curr_form_data['p_first_name'] = parent_data['first_name']
        curr_form_data['p_last_name'] = parent_data['last_name']
        curr_form_data['p_email'] = parent_data['email']
        forms.append(curr_form_data)

    parentIds = studentsDOM.getParents(studentID)
    parents = []
    for parentId in parentIds:
        parent = parentsDOM.getParentProfile(parentId)
        studentsOfParent = []
        for currStudentID in parent['student_ids']:
            student = studentsDOM.getFullInfo(currStudentID)
            forms_completed = 0
            for form in student['form_ids']:
                if FormsDOM.isComplete(form):
                    forms_completed += 1
            student['forms_completed'] = str(forms_completed) + "/" + str(
                len(student['form_ids']))
            student['completion_rate'] = forms_completed / len(
                student['form_ids'])
            cleanedStudent = {}
            cleanedStudent['id'] = str(student['_id'])
            cleanedStudent['first_name'] = student['first_name']
            cleanedStudent['middle_name'] = student['middle_name']
            cleanedStudent['last_name'] = student['last_name']
            cleanedStudent['DOB'] = student['DOB']
            cleanedStudent['grade'] = student['grade']
            cleanedStudent['archived'] = student['archived']
            cleanedStudent['forms_completed'] = student['forms_completed']
            cleanedStudent['completion_rate'] = student['completion_rate']
            studentsOfParent.append(cleanedStudent)
        cleanedParent = {}
        cleanedParent['id'] = str(parentId)
        cleanedParent['children'] = studentsOfParent
        cleanedParent['first_name'] = parent['first_name']
        cleanedParent['last_name'] = parent['last_name']
        cleanedParent['email'] = parent['email']
        parents.append(cleanedParent)
    return {
        'forms': forms,
        'basic_info': studentsDOM.getBasicInfo(studentID),
        'blank_forms': blankFormsDOM.getAll(),
        'parents': parents,
        'authorized': isAuthorized(get_token_auth_header(),
                                   ['developer', 'admin']),
        'tags': utilitiesDOM.getTags(),
        'years': utilitiesDOM.getYears(),
    }