Exemplo n.º 1
0
    def mutate(self, info, token, school):
        user = info.context.user
        if user.is_authenticated() and user.is_staff:
            try:
                school = School.objects.get(guid=school)
            except School.DoesNotExist:
                raise Exception('Invalid school')
            try:
                account = AccountProfile.objects.get(guid=token)
                if school in account.assoc_school_list.all():
                    account.is_active = True
                    account.save()

                    send_html_email(
                        'email_welcome_approved_teacher.html',
                        {'account': account, 'school': school},
                        'Your NCI Account have been activated',
                        [account.email]
                    )

                    return ApproveTeacher(account=account)
                else:
                    raise Exception('Doesn\'t belong to this school ')
            except AccountProfile.DoesNotExist:
                raise Exception('Invalid token')

        raise Exception('Not authorized')
Exemplo n.º 2
0
 def mutate(self, info, **kwargs):
     try:
         account = AccountProfile.objects.get(email=kwargs.get('email'))
         uid = urlsafe_base64_encode(force_bytes(account.id)).decode()
         token = token_generator.make_token(account)
         link = 'https://app.discovernci.org/reset/%s/%s' % (uid, token)
         send_html_email(
             'email_password_reset.html',
             {'account': account, 'link': link},
             'Password reset on discovernci.org',
             [account.email]
         )
         return ResetPasswordRequest(ok=True)
     except AccountProfile.DoesNotExist:
         raise Exception('Invalid credentials')
Exemplo n.º 3
0
    def mutate(self, info, **kwargs):

        try:
            account = AccountProfile.objects.get(guid=kwargs.get('token', None))
        except AccountProfile.DoesNotExist:
            raise Exception('Invalid credentials')

        email_payload = {
            'account': account.__dict__,
            'message': kwargs.get('message', None)
        }

        send_html_email(
            'email_staff_tech_support.html',
            email_payload,
            'NCI Technical Support Inquiry',
            settings.TECH_SUPPORT_TO_LIST
        )

        return SubmitTechSupportMessage(success='Message sent')
Exemplo n.º 4
0
    def mutate(self, info, **kwargs):
        if not info.context.user.is_authenticated():
            raise Exception('Not signed in')

        try:
            student = Student.objects.get(pk=kwargs.get('studentId'))
            field_trip = FieldTrip.objects.get(pk=kwargs.get('fieldTripId'))
        except Student.DoesNotExist:
            raise Exception('Invalid student details')
        except FieldTrip.DoesNotExist:
            raise Exception('Invalid field trip details')

        action = kwargs.get('action', None)
        if action == 'register':
            field_trip.student_list.add(student)

            # Send user a confirmation email
            send_html_email(
                'email_fieldtrip_registration_confirmation.html',
                {
                    'account': info.context.user,
                    'student': student,
                    'school': student.current_school,
                    'fieldtrip': field_trip
                },
                '%s is registered to attend a field trip to Nature\'s Classroom Institute'
                % student.name,
                [
                    info.context.user.email,
                ]  # TODO: should this instead be student.guardian_list?
            )

        if action == 'deregister':
            field_trip.student_list.remove(student)

        return FieldTripRegistration(success='successfully %sed' % action)
Exemplo n.º 5
0
    def mutate(self, info, **kwargs):
        user = info.context.user
        if not info.context.user.is_authenticated():
            raise Exception('Invalid credentials')

        contact_method = kwargs.get('contactMethod')

        send_html_email(
            'email_fieldtrip_request.html', {
                'account': user,
                'school': user.assoc_school_list.first(),
                'contact_method': contact_method
            }, 'NCI Field Trip Request', [
                user.email,
            ])

        send_html_email(
            'email_staff_fieldtrip_request.html', {
                'account': user,
                'school': user.assoc_school_list.first(),
                'contact_method': contact_method
            }, 'NCI Field Trip Request', settings.STAFF_TO_LIST)

        return FieldTripRequest(success='true')
Exemplo n.º 6
0
    def mutate(self, info, **kwargs):
        email = kwargs.get('email')

        # Let's make sure they aren't already in the system.
        try:
            matches = AccountProfile.objects.filter(email__iexact=email)
            if matches.count() > 0:
                raise Exception("This email address is already registered. Try logging in with it?")
        except AccountProfile.DoesNotExist:
            pass

        account = AccountProfile.objects.create_user(email=email, password=kwargs.get('password'))
        account.name = kwargs.get('name')

        account.account_type = kwargs.get('accountType')
        if account.account_type == 'teacher':
            account.is_active = False

        phone = kwargs.get('phone', None)
        if phone:
            account.phone = phone

        account.date_joined = timezone.now()
        account.modified = timezone.now()
        account.save()

        # Associate the school with this account
        school = School.objects.get(pk=kwargs.get('currentSchool'))
        account.assoc_school_list.add(school)

        email_payload = {'account': account.__dict__, 'school': school.__dict__}

        # Optionally add the user to our MailChimp subscriber list
        mailchimp_status = None
        if kwargs.get('newsletterSignup', None):
            mailchimp_status = 'subscribed'
            client = MailChimp('nciw', '12a1da954758b91006fc998424ebb72b-us9')
            client.lists.members.create('7fab981cdc', {
                'email_address': account.email,
                'status': 'subscribed',
                'merge_fields': {
                    'FNAME': account.get_first_name(),
                    'LNAME': account.get_last_name(),
                    'MMERGE4': school.name,
                    'MMERGE10': account.phone
                }
            })

        # Teachers must either be whitelisted or require manual approval
        if (account.account_type == 'teacher'):
            email_template = 'email_staff_new_teacher_account.html'
            email_subject = 'APPROVAL REQUEST: New Teacher NCI Account Sign up for %s' % school.name

            # Circle back and see if they are whitelisted
            if account.email.lower() in school.email_whitelist.lower():
                email_template = 'email_staff_new_whitelisted_teacher_account.html'
                email_subject = 'New Teacher NCI Account Sign up for %s (pre-approved)' % school.name
                account.is_active = True
                account.save()

            # Notify EE Staff of a new teacher sign up
            send_html_email(
                email_template,
                email_payload,
                email_subject,
                settings.STAFF_TO_LIST
            )

        elif (account.account_type == 'parent'):

            # Send user a  Welcome/confirmation email
            send_html_email(
                'email_welcome_new_signup.html',
                email_payload,
                'Welcome to Nature\'s Classroom Institute',
                [account.email, ]
            )

        auth_login(info.context, account)

        return CreateAccountProfile(
            account=account,
            mailchimp=mailchimp_status
        )
Exemplo n.º 7
0
    def mutate(self, info, **kwargs):
        if not info.context.user.is_authenticated():
            raise GraphQLError('Unauthorized')

        # print(kwargs.get('medicationSet'))
        # [{
        #    'id': 412,
        #    'administrationTimes': '1, 2, 5',
        #    'administrationTimesOther': 'As needed',
        #    'medicationName': 'Cookies',
        #    'amount': None,
        #    'amountHuman': '2 Cookies',
        #    'amountUnit': None,
        #    'getAmountUnitDisplay': None,
        #    'notes': "First ask her if she's 'being a candy?' if she hesitates with an answer, give her two cookies and comfort her."
        # }]

        # Student object (s)
        current_school = School.objects.get(pk=kwargs.get('currentSchoolId'))
        name = kwargs.get('name')
        dob = parse(kwargs.get('dob')).date()

        try:
            s = Student.objects.get(id=kwargs.get('id'))
        except Student.DoesNotExist:

            # Check for pre-existing Student record.
            # This is a costly command as the Name and date of birth fields are
            # encrypted. So we grab all Students from school, and then compare
            # both fields. An email gets sent to Staff and msg displayed that
            # user may already be entered and that we'll be in touch soon.
            for classmate in current_school.student_set.all():
                if (classmate.name == name) and (classmate.dob == dob):
                    # send email to Tech Support (with person information about
                    # who is duplicated, who is trying to register the student,
                    # and who has the student registered
                    send_html_email(
                        'email_duplicate_student_record.html', {
                            'existing_record': classmate,
                            'user': info.context.user.email
                        }, 'Duplicate Student Record Attempt',
                        settings.TECH_SUPPORT_TO_LIST)

                    # Display error message to parent to contact NCI, student
                    # may already be registered.
                    raise GraphQLError(
                        'This student may already have a record on-file. Our staff will be notified and be in contact with you shortly. Sorry for the trouble. You can close this window.'
                    )

            # Otherwisse, let's create a brand new student object!
            s = Student()

        s.name = name
        s.dob = dob
        s.current_school = current_school
        s.classroom = kwargs.get('classroom')
        s.photo_waiver = kwargs.get('photoWaiver')
        s.waiver_agreement = kwargs.get('waiverAgreement')
        s.medical_agreement = kwargs.get('medicalAgreement')
        s.save()

        # MedicalRecord object (mr)
        try:
            mr = MedicalRecord.objects.get(student=s)
        except MedicalRecord.DoesNotExist:
            mr = MedicalRecord(student=s)
        mr.gender = kwargs.get('gender')
        mr.height = kwargs.get('height')
        mr.weight = kwargs.get('weight')

        if kwargs.get('lastTetanus'):
            mr.last_tetanus = parse(kwargs.get('lastTetanus')).date()
        mr.no_tetanus_vaccine = kwargs.get('noTetanusVaccine', False)
        mr.recent_trauma = kwargs.get('recentTrauma', '')
        mr.restrictions = kwargs.get('restrictions', '')
        mr.non_rx_type = kwargs.get('nonRxType')
        mr.non_rx_notes = kwargs.get('nonRxNotes', '')
        mr.allergies = kwargs.get('allergies')
        mr.food_allergens = kwargs.get('foodAllergens')
        mr.allergies_expanded = kwargs.get('allergiesExpanded', '')
        mr.dietary_needs = kwargs.get('dietaryNeeds', '')
        mr.dietary_caution = kwargs.get('dietaryCaution', False)
        mr.save()

        # If dietary_caution is True, we notify Staff right away
        if mr.dietary_caution:
            send_html_email('email_staff_dietary_caution.html', {'student': s},
                            'CONTACT REQUEST: Student Dietary Concerns',
                            settings.TECH_SUPPORT_TO_LIST)

        # Medication objects (med)
        medication_list_str = kwargs.get('medicationSet', None)
        if medication_list_str:
            medication_list = ast.literal_eval(medication_list_str)
            for med in medication_list:
                try:
                    # FIXME: scaling issue, pk will eventually collide with getRandId()
                    medication = Medication.objects.get(pk=med['id'])
                except Medication.DoesNotExist:
                    medication = Medication()
                medication.administration_times = ', '.join(
                    str(x) for x in med['administrationTimes']),
                medication.administration_times_other = str(
                    med['administrationTimesOther'])
                medication.medication_name = str(med['medicationName'])
                medication.amount_human = str(med['amountHuman'])
                medication.notes = str(med['notes'])
                medication.medical_record = mr

                medication.save()

        # Health Insurance object (ins)
        # Either attach the student to an existing object (insId), or create a
        # new one and attach them to that.
        ins = None
        if kwargs.get('insId'):
            ins = Insurance.objects.get(pk=kwargs.get('insId'))
        elif kwargs.get('insPolicyNum'):
            try:
                ins = Insurance.objects.get(
                    company_name=kwargs.get('insCompanyName'),
                    policy_num=kwargs.get('insPolicyNum'),
                    group_num=kwargs.get('insGroupNum'),
                    holder_name=kwargs.get('insHolderName'))
            except Insurance.DoesNotExist:
                ins = Insurance(company_name=kwargs.get('insCompanyName'),
                                policy_num=kwargs.get('insPolicyNum'),
                                group_num=kwargs.get('insGroupNum'),
                                holder_name=kwargs.get('insHolderName'))
                if kwargs.get('isParentGuardian'):
                    ins.account = info.context.user
                else:
                    ins.account = AccountProfile.objects.get(
                        email=kwargs.get('parentGuardianEmail'))
                ins.save()

        # Add the Student to the Insurance's dependents list
        if ins:
            ins.dependents_list.add(s)

        # Add a Parent/Guardian to the Students guardian list
        if kwargs.get('isParentGuardian'):
            s.guardian_list.add(info.context.user)
        else:
            s.guardian_list.add(
                AccountProfile.objects.get(
                    email=kwargs.get('parentGuardianEmail')))

        return AddOrModifyStudent(student=s, medical_record=mr, insurance=ins)