def new_student(request, userid): person = get_object_or_404(Person, find_userid_or_emplid(userid)) semester = Semester.next_starting() semesterconfig = SemesterConfig.get_config(request.units, semester) student = get_object_or_404(Person, find_userid_or_emplid(userid)) initial = { 'person': student.emplid, 'start_date': semesterconfig.start_date(), 'end_date': semesterconfig.end_date(), 'hours': 80 } scholarship_choices, hiring_faculty_choices, unit_choices, project_choices, account_choices, program_choices = \ _appointment_defaults(request.units, emplid=student.emplid) gss = GradStudent.objects.filter(person=student) if gss: gradstudent = gss[0] initial['sin'] = gradstudent.person.sin() raform = RAForm(initial=initial) raform.fields['person'] = forms.CharField(widget=forms.HiddenInput()) raform.fields['scholarship'].choices = scholarship_choices raform.fields['hiring_faculty'].choices = hiring_faculty_choices raform.fields['unit'].choices = unit_choices raform.fields['project'].choices = project_choices raform.fields['account'].choices = account_choices raform.fields['program'].choices = program_choices return render(request, 'ra/new.html', {'raform': raform, 'person': person})
def student_courses_download(request, userid): student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = classes_data(student.emplid) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'inline; filename="%s-%s-courses.csv"' % ( userid, datetime.datetime.now().strftime('%Y%m%d')) writer = csv.writer(response) writer.writerow(['Employee ID', 'Last Name', 'First Name']) writer.writerow([student.emplid, student.last_name, student.first_name]) writer.writerow([]) writer.writerow([ 'Semester', 'Subject', 'Catalogue Number', 'Description', 'Official Grade', 'Units Taken' ]) if 'courses' in data: for crse in data['courses']: strm = crse.get('strm') or '' descr = crse.get('descr') or '' subject = crse.get('subject') or '' catalog_nbr = crse.get('catalog_nbr') or '' crse_grade_off = crse.get('crse_grade_off') or '' unt_taken = crse.get('unt_taken') or 0 writer.writerow( [strm, subject, catalog_nbr, descr, crse_grade_off, unt_taken]) return response
def student_appointments(request, userid): student = get_object_or_404(Person, find_userid_or_emplid(userid)) appointments = RAAppointment.objects.filter(person=student, unit__in=Unit.sub_units(request.units), deleted=False).order_by("-created_at") grads = GradStudent.objects.filter(person=student, program__unit__in=Unit.sub_units(request.units)) context = {'appointments': appointments, 'student': student, 'grads': grads} return render(request, 'ra/student_appointments.html', context)
def new_visa(request, emplid=None): if request.method == 'POST': form = VisaForm(request, request.POST) if form.is_valid(): visa = form.save(commit=False) visa.save() messages.add_message(request, messages.SUCCESS, 'Visa was created.' ) l = LogEntry(userid=request.user.username, description="added visa: %s" % (visa), related_object=visa.person ) l.save() return HttpResponseRedirect(reverse('visas:list_all_visas')) else: if emplid: person = Person.objects.get(find_userid_or_emplid(emplid)) form = VisaForm(request, initial={'person': person}) else: form = VisaForm(request) return render(request, 'visas/new_visa.html', {'form': form})
def new_visa(request, emplid=None): if request.method == 'POST': form = VisaForm(request, request.POST) if form.is_valid(): visa = form.save(commit=False) visa.save() messages.add_message(request, messages.SUCCESS, u'Visa was created.' ) l = LogEntry(userid=request.user.username, description="added visa: %s" % (visa), related_object=visa.person ) l.save() return HttpResponseRedirect(reverse('visas:list_all_visas')) else: if emplid: person = Person.objects.get(find_userid_or_emplid(emplid)) form = VisaForm(request, initial={'person': person}) else: form = VisaForm(request) return render(request, 'visas/new_visa.html', {'form': form})
def student_courses_download(request, userid): student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = classes_data(student.emplid) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'inline; filename="%s-%s-courses.csv"' % (userid, datetime.datetime.now().strftime('%Y%m%d')) writer = csv.writer(response) writer.writerow(['Employee ID', 'Last Name', 'First Name']) writer.writerow([student.emplid, student.last_name, student.first_name]) writer.writerow([]) writer.writerow(['Semester', 'Subject', 'Catalogue Number', 'Description', 'Official Grade', 'Units Taken']) if 'courses' in data: for crse in data['courses']: strm = crse.get('strm') or '' descr = crse.get('descr') or '' subject = crse.get('subject') or '' catalog_nbr = crse.get('catalog_nbr') or '' crse_grade_off = crse.get('crse_grade_off') or '' unt_taken = crse.get('unt_taken') or 0 writer.writerow([strm, subject, catalog_nbr, descr, crse_grade_off, unt_taken]) return response
def student_info(request, userid=None): # everything-about-this-student view if not userid and 'q' in request.GET: # redirect query string away return HttpResponseRedirect(reverse('dashboard.views.student_info', kwargs={'userid': request.GET['q']})) elif not userid: # display search screen return render(request, "dashboard/student_info_search.html", {}) student = get_object_or_404(Person, find_userid_or_emplid(userid)) user = Person.objects.get(userid=request.user.username) all_instr = [m.offering for m in Member.objects.exclude(offering__component='CAN').filter(person=user, role='INST').select_related('offering')] all_ta = [m.offering for m in Member.objects.exclude(offering__component='CAN').filter(person=user, role='TA').select_related('offering')] student_instr = Member.objects.exclude(offering__component='CAN').filter(person=student, role='STUD', offering__in=all_instr).select_related('offering', 'person') student_ta = Member.objects.exclude(offering__component='CAN').filter(person=student, role='STUD', offering__in=all_ta).select_related('offering', 'person') ta_instr = Member.objects.exclude(offering__component='CAN').filter(person=student, role='TA', offering__in=all_instr).select_related('offering', 'person') supervisors = Supervisor.objects.filter(student__person=student, supervisor=user, removed=False) anything = student_instr or student_ta or ta_instr or supervisors if not anything: # match get_object_or_404 behaviour to not leak info raise Http404('No Person matches the given query.') context = { 'student': student, 'student_instr': student_instr, 'student_ta': student_ta, 'ta_instr': ta_instr, 'supervisors': supervisors, } return render(request, "dashboard/student_info.html", context)
def student_notes(request, userid): try: student = Person.objects.get(find_userid_or_emplid(userid)) except Person.DoesNotExist: student = get_object_or_404(NonStudent, slug=userid) if request.POST and 'note_id' in request.POST: # the "hide note" box was checked: process note = get_object_or_404(AdvisorNote, pk=request.POST['note_id'], unit__in=request.units) note.hidden = request.POST['hide'] == "yes" note.save() if isinstance(student, Person): notes = AdvisorNote.objects.filter( student=student, unit__in=request.units).order_by("-created_at") form_subs = FormSubmission.objects.filter( initiator__sfuFormFiller=student, form__unit__in=Unit.sub_units(request.units), form__advisor_visible=True) visits = AdvisorVisit.objects.filter( student=student, unit__in=request.units).order_by('-created_at') # decorate with .entry_type (and .created_at if not present so we can sort nicely) for n in notes: n.entry_type = 'NOTE' for fs in form_subs: fs.entry_type = 'FORM' fs.created_at = fs.last_sheet_completion() items = list(itertools.chain(notes, form_subs)) items.sort(key=lambda x: x.created_at, reverse=True) nonstudent = False else: notes = AdvisorNote.objects.filter( nonstudent=student, unit__in=request.units).order_by("-created_at") visits = AdvisorVisit.objects.filter( nonstudent=student, unit__in=request.units).order_by('-created_at') for n in notes: n.entry_type = 'NOTE' items = notes nonstudent = True show_transcript = False # For demo purposes only. # if 'UNIV' in [u.label for u in request.units]: # show_transcript = True template = 'advisornotes/student_notes.html' context = { 'items': items, 'student': student, 'userid': userid, 'nonstudent': nonstudent, 'show_transcript': show_transcript, 'units': request.units, 'visits': visits } return render(request, template, context)
def clean_admin_userid(self): userid = self.cleaned_data['admin_userid'] try: person = Person.objects.get(find_userid_or_emplid(userid)) except Person.DoesNotExist: raise forms.ValidationError( 'Cannot find a person with that userid.') return person
def list_all_visas(request, emplid=None): if emplid: person = Person.objects.get(find_userid_or_emplid(emplid)) visa_list = Visa.objects.visible_given_user(person) else: person = None visa_list = Visa.objects.visible_by_unit(request.units) context = {'visa_list': visa_list, 'person': person} return render(request, 'visas/view_visas.html', context)
def user_summary(request, userid): query = find_userid_or_emplid(userid) user = get_object_or_404(Person, query) memberships = Member.objects.filter(person=user) roles = Role.objects.filter(person=user).exclude(role="NONE") context = {'user': user, 'memberships': memberships, 'roles': roles} return render(request, "coredata/user_summary.html", context)
def list_all_visas(request, emplid=None): if emplid: person = Person.objects.get(find_userid_or_emplid(emplid)) visa_list = Visa.objects.visible_given_user(person) else: person = None visa_list = Visa.objects.visible_by_unit(Unit.sub_units(request.units)) context = {'visa_list': visa_list, 'person': person} return render(request, 'visas/view_visas.html', context)
def download_file(request, course_slug, activity_slug, component_slug=None, submission_id=None, userid=None): course = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(course.activity_set, slug=activity_slug, deleted=False) staff = False if is_course_staff_by_slug(request, course_slug): staff = True # find the appropriate submission object if submission_id: # explicit request: get that one. try: submission_info = SubmissionInfo.from_submission_id(submission_id) except ValueError: return NotFoundResponse(request) elif userid: # userid specified: get their most recent submission student = get_object_or_404(Person, find_userid_or_emplid(userid)) submission_info = SubmissionInfo(student=student, activity=activity, include_deleted=staff) else: return NotFoundResponse(request) if not submission_info.have_submitted( ) or submission_info.activity != activity: return NotFoundResponse(request) if not submission_info.accessible_by(request): return ForbiddenResponse(request) # create the result if component_slug: # download single component if specified submission_info.get_most_recent_components() submitted_components = [ subcomp for comp, subcomp in submission_info.components_and_submitted() if subcomp and comp.slug == component_slug ] if not submitted_components: return NotFoundResponse(request) submitted_component = submitted_components[0] return submitted_component.download_response( slug=submission_info.submissions[0].file_slug()) else: # no component specified: give back the full ZIP file. return submission_info.generate_student_zip()
def student_courses(request, userid): """ List of courses now (and in surrounding semesters) """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) context = { 'userid': userid, 'student': student, } return render(request, 'advisornotes/student_courses.html', context)
def student_transfers(request, userid): """ List of transfer credits for a given student """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) context = { 'userid': userid, 'student': student, } return render(request, 'advisornotes/student_transfers.html', context)
def new_student(request, userid): person = get_object_or_404(Person, find_userid_or_emplid(userid)) semester = Semester.next_starting() semesterconfig = SemesterConfig.get_config(request.units, semester) student = get_object_or_404(Person, find_userid_or_emplid(userid)) initial = {'person': student.emplid, 'start_date': semesterconfig.start_date(), 'end_date': semesterconfig.end_date(), 'hours': 80 } scholarship_choices, hiring_faculty_choices, unit_choices, project_choices, account_choices =_appointment_defaults(request.units, emplid=student.emplid) gss = GradStudent.objects.filter(person=student) if gss: gradstudent = gss[0] initial['sin'] = gradstudent.person.sin() raform = RAForm(initial=initial) raform.fields['person'] = forms.CharField(widget=forms.HiddenInput()) raform.fields['scholarship'].choices = scholarship_choices raform.fields['hiring_faculty'].choices = hiring_faculty_choices raform.fields['unit'].choices = unit_choices raform.fields['project'].choices = project_choices raform.fields['account'].choices = account_choices return render(request, 'ra/new.html', { 'raform': raform, 'person': person })
def student_info(request, userid=None): # everything-about-this-student view if not userid and 'q' in request.GET: # redirect query string away return HttpResponseRedirect( reverse('dashboard.views.student_info', kwargs={'userid': request.GET['q']})) elif not userid: # display search screen return render(request, "dashboard/student_info_search.html", {}) student = get_object_or_404(Person, find_userid_or_emplid(userid)) user = Person.objects.get(userid=request.user.username) all_instr = [ m.offering for m in Member.objects.exclude(offering__component='CAN').filter( person=user, role='INST').select_related('offering') ] all_ta = [ m.offering for m in Member.objects.exclude(offering__component='CAN').filter( person=user, role='TA').select_related('offering') ] student_instr = Member.objects.exclude(offering__component='CAN').filter( person=student, role='STUD', offering__in=all_instr).select_related('offering', 'person') student_ta = Member.objects.exclude(offering__component='CAN').filter( person=student, role='STUD', offering__in=all_ta).select_related('offering', 'person') ta_instr = Member.objects.exclude(offering__component='CAN').filter( person=student, role='TA', offering__in=all_instr).select_related('offering', 'person') supervisors = Supervisor.objects.filter(student__person=student, supervisor=user, removed=False) anything = student_instr or student_ta or ta_instr or supervisors if not anything: # match get_object_or_404 behaviour to not leak info raise Http404('No Person matches the given query.') context = { 'student': student, 'student_instr': student_instr, 'student_ta': student_ta, 'ta_instr': ta_instr, 'supervisors': supervisors, } return render(request, "dashboard/student_info.html", context)
def student_transfers_data(request, userid): """ AJAX request for transfer data, etc. (queries SIMS directly) """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = transfer_data(student.emplid) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='application/json;charset=utf-8') json.dump(data, response, indent=1) return response
def student_more_info_short(request, userid): """ Same as above, but with a more limited subset of info. """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = more_personal_info(student.emplid, needed=['programs', 'gpa', 'citizen', 'gender']) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='application/json') json.dump(data, response) return response
def _override_ownership_confirm(request, course, activity, userid, group_slug, old_owner, urlencode): if group_slug == None: group = None student = get_object_or_404(Person, find_userid_or_emplid(userid)) else: student = None groups = Group.objects.all().filter(courseoffering=course) group = get_object_or_404(groups, slug=group_slug) return render(request, "submission/override_ownership_confirm.html", {"course":course, "activity":activity, "student":student, "group":group, "old_owner":old_owner, "true":True, "urlencode":urlencode, "userid":userid})
def student_more_info(request, userid): """ AJAX request for contact info, etc. (queries SIMS directly) """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = more_personal_info(student.emplid) except SIMSProblem as e: data = {'error': unicode(e)} response = HttpResponse(content_type='application/json') json.dump(data, response) return response
def student_courses_data(request, userid): """ AJAX request for course data, etc. (queries SIMS directly) """ student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = course_data(student.emplid) except SIMSProblem as e: data = {'error': unicode(e)} #data = {'error': 'Feature temporarily disabled.'} # disable while privacy concerns are worked out response = HttpResponse(content_type='application/json;charset=utf-8') json.dump(data, response, encoding='utf-8', indent=1) return response
def record_advisor_visit(request, userid, unit_slug): unit = get_object_or_404(Unit, slug=unit_slug, id__in=(u.id for u in request.units)) advisor = get_object_or_404(Person, userid=request.user.username) try: student = Person.objects.get(find_userid_or_emplid(userid)) nonstudent = None except Person.DoesNotExist: nonstudent = get_object_or_404(NonStudent, slug=userid) student = None visit = AdvisorVisit(student=student, nonstudent=nonstudent, unit=unit, advisor=advisor, version=ADVISOR_VISIT_VERSION) visit.save() return HttpResponseRedirect(reverse('advising:edit_visit_initial', kwargs={'visit_slug': visit.slug}))
def record_advisor_visit(request, userid, unit_slug): unit = get_object_or_404(Unit, slug=unit_slug, id__in=(u.id for u in request.units)) advisor = get_object_or_404(Person, userid=request.user.username) try: student = Person.objects.get(find_userid_or_emplid(userid)) nonstudent = None except Person.DoesNotExist: nonstudent = get_object_or_404(NonStudent, slug=userid) student = None av = AdvisorVisit(student=student, nonstudent=nonstudent, program=None, advisor=advisor, unit=unit) av.save() messages.add_message(request, messages.SUCCESS, u'%s advisor visit recorded on %s.' % (unit.informal_name(), datetime.date.today())) return HttpResponseRedirect(reverse('advisornotes.views.student_notes', kwargs={'userid': userid}))
def download_file(request, course_slug, activity_slug, component_slug=None, submission_id=None, userid=None): course = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(course.activity_set, slug = activity_slug, deleted=False) staff = False if is_course_staff_by_slug(request, course_slug): staff = True # find the appropriate submission object if submission_id: # explicit request: get that one. submission = get_submission(submission_id) if not submission or submission.activity!=activity: return NotFoundResponse(request) submitted_components = get_submission_components(submission, activity, include_deleted=staff) elif userid: # userid specified: get their most recent submission student = get_object_or_404(Person, find_userid_or_emplid(userid)) submission, submitted_components = get_current_submission(student, activity, include_deleted=staff) if not submission: return NotFoundResponse(request) else: return NotFoundResponse(request) # make sure this user is allowed to see the file if staff: pass elif isinstance(submission, GroupSubmission): membership = submission.group.groupmember_set.filter(student__person__userid=request.user.username, activity=activity, confirmed=True) if not membership: return ForbiddenResponse(request) elif isinstance(submission, StudentSubmission): if submission.member.person.userid != request.user.username: return ForbiddenResponse(request) # create the result if component_slug: # download single component if specified # get the actual component: already did the searching above, so just look in that list components = [sub for comp,sub in submitted_components if sub and sub.component.slug==component_slug] if not components: return NotFoundResponse(request) return components[0].download_response() else: # no component specified: give back the full ZIP file. return generate_zip_file(submission, submitted_components)
def student_notes(request, userid): try: student = Person.objects.get(find_userid_or_emplid(userid)) except Person.DoesNotExist: student = get_object_or_404(NonStudent, slug=userid) if request.POST and 'note_id' in request.POST: # the "hide note" box was checked: process note = get_object_or_404(AdvisorNote, pk=request.POST['note_id'], unit__in=request.units) note.hidden = request.POST['hide'] == "yes" note.save() if isinstance(student, Person): notes = AdvisorNote.objects.filter(student=student, unit__in=request.units).order_by("-created_at") alerts = Alert.objects.filter(person=student, alerttype__unit__in=request.units, hidden=False).order_by("-created_at") form_subs = FormSubmission.objects.filter(initiator__sfuFormFiller=student, form__unit__in=Unit.sub_units(request.units), form__advisor_visible=True) # decorate with .entry_type (and .created_at if not present so we can sort nicely) for n in notes: n.entry_type = 'NOTE' for a in alerts: a.entry_type = 'ALERT' for fs in form_subs: fs.entry_type = 'FORM' fs.created_at = fs.last_sheet_completion() items = list(itertools.chain(notes, alerts, form_subs)) items.sort(key=lambda x: x.created_at, reverse=True) nonstudent = False else: notes = AdvisorNote.objects.filter(nonstudent=student, unit__in=request.units).order_by("-created_at") for n in notes: n.entry_type = 'NOTE' items = notes nonstudent = True show_transcript = False if 'UNIV' in [u.label for u in request.units]: show_transcript = True template = 'advisornotes/student_notes.html' if 'compact' in request.GET: template = 'advisornotes/student_notes_compact.html' context = {'items': items, 'student': student, 'userid': userid, 'nonstudent': nonstudent, 'show_transcript': show_transcript, 'units': request.units} return render(request, template, context)
def new_note(request, userid): try: student = Person.objects.get(find_userid_or_emplid(userid)) except Person.DoesNotExist: student = get_object_or_404(NonStudent, slug=userid) unit_choices = [(u.id, str(u)) for u in request.units] if request.method == 'POST': form = AdvisorNoteForm(data=request.POST, files=request.FILES, student=student) form.fields['unit'].choices = unit_choices if form.is_valid(): note = form.save(commit=False) if isinstance(student, Person): note.student = student else: note.nonstudent = student note.advisor = Person.objects.get(userid=request.user.username) if 'file_attachment' in request.FILES: upfile = request.FILES['file_attachment'] note.file_mediatype = upfile.content_type if form.cleaned_data['email_student']: _email_student_note(note) note.emailed = True note.save() #LOG EVENT# l = LogEntry(userid=request.user.username, description=("new note for %s by %s") % (form.instance.student, request.user.username), related_object=form.instance) l.save() messages.add_message(request, messages.SUCCESS, 'Note created.') return _redirect_to_notes(student) else: form = AdvisorNoteForm(student=student) form.fields['unit'].choices = unit_choices return render(request, 'advisornotes/new_note.html', { 'form': form, 'student': student, 'userid': userid })
def student_transfers_download(request, userid): student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = transfer_data(student.emplid) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition'] = 'inline; filename="%s-%s-transfers.csv"' % ( userid, datetime.datetime.now().strftime('%Y%m%d')) writer = csv.writer(response) writer.writerow(['Employee ID', 'Last Name', 'First Name']) writer.writerow([student.emplid, student.last_name, student.first_name]) writer.writerow([]) writer.writerow([ 'Description', 'School Subject', 'Course Number', 'Transfer Equivalency Group', 'Transfer Status', 'Subject', 'Catalogue Number', 'Transfer Grade Input', 'Transfer Official Grade', 'External Grade Input', 'External Official Grade', 'Units Transferred' ]) if 'transfers' in data: for trns in data['transfers']: descr = trns.get('descr') or '' school_subject = trns.get('school_subject') or '' crse_nbr = trns.get('crse_nbr') or '' trsnf_equivlncy_grp = trns.get('trsnf_equivlncy_grp') or '' transfr_stat = trns.get('transfr_stat') or '' subject = trns.get('subject') or '' catalog_nbr = trns.get('catalog_nbr') or '' tcd_grade_input = trns.get('tcd_grade_input') or '' tcd_grade_off = trns.get('tcd_grade_off') or '' ec_grade_input = trns.get('ec_grade_input') or '' ec_grade_off = trns.get('ec_grade_off') or '' unt_trnsfr = trns.get('unt_trnsfr') or 0 writer.writerow([ descr, school_subject, crse_nbr, trsnf_equivlncy_grp, transfr_stat, subject, catalog_nbr, tcd_grade_input, tcd_grade_off, ec_grade_input, ec_grade_off, unt_trnsfr ]) return response
def clean_people(self): text = self.cleaned_data['people'] emplids = text.strip().split() people = [] for e in emplids: # this is going to be slow if there's a big list try: person = Person.objects.get(find_userid_or_emplid(e)) except Person.DoesNotExist: try: person = add_person(int(e)) if person is None: raise forms.ValidationError( 'Cannot find a person emplid/userid %r.' % (e, )) except (ValueError, SIMSProblem): raise forms.ValidationError( 'Cannot find a person emplid/userid %r.' % (e, )) people.append(person) return people
def download_file(request, course_slug, activity_slug, component_slug=None, submission_id=None, userid=None): course = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(course.activity_set, slug = activity_slug, deleted=False) staff = False if is_course_staff_by_slug(request, course_slug): staff = True # find the appropriate submission object if submission_id: # explicit request: get that one. try: submission_info = SubmissionInfo.from_submission_id(submission_id) except ValueError: return NotFoundResponse(request) elif userid: # userid specified: get their most recent submission student = get_object_or_404(Person, find_userid_or_emplid(userid)) submission_info = SubmissionInfo(student=student, activity=activity, include_deleted=staff) else: return NotFoundResponse(request) if not submission_info.have_submitted() or submission_info.activity != activity: return NotFoundResponse(request) if not submission_info.accessible_by(request): return ForbiddenResponse(request) # create the result if component_slug: # download single component if specified submission_info.get_most_recent_components() submitted_components = [subcomp for comp, subcomp in submission_info.components_and_submitted() if subcomp and comp.slug == component_slug] if not submitted_components: return NotFoundResponse(request) submitted_component = submitted_components[0] return submitted_component.download_response(slug=submission_info.submissions[0].file_slug()) else: # no component specified: give back the full ZIP file. return submission_info.generate_student_zip()
def new_note(request, userid): try: student = Person.objects.get(find_userid_or_emplid(userid)) except Person.DoesNotExist: student = get_object_or_404(NonStudent, slug=userid) unit_choices = [(u.id, unicode(u)) for u in request.units] if request.method == 'POST': form = advisor_note_factory(student, request.POST, request.FILES) form.fields['unit'].choices = unit_choices if form.is_valid(): note = form.save(commit=False) if isinstance(student, Person): note.student = student else: note.nonstudent = student note.advisor = Person.objects.get(userid=request.user.username) if 'file_attachment' in request.FILES: upfile = request.FILES['file_attachment'] note.file_mediatype = upfile.content_type if isinstance(student, Person) and form.cleaned_data['email_student']: _email_student_note(note) note.emailed = True note.save() #LOG EVENT# l = LogEntry(userid=request.user.username, description=(u"new note for %s by %s") % (form.instance.student, request.user.username), related_object=form.instance) l.save() messages.add_message(request, messages.SUCCESS, 'Note created.') return _redirect_to_notes(student) else: form = advisor_note_factory(student) form.fields['unit'].choices = unit_choices return render(request, 'advisornotes/new_note.html', {'form': form, 'student': student, 'userid': userid})
def student_transfers_download(request, userid): student = get_object_or_404(Person, find_userid_or_emplid(userid)) try: data = transfer_data(student.emplid) except SIMSProblem as e: data = {'error': str(e)} response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'inline; filename="%s-%s-transfers.csv"' % (userid, datetime.datetime.now().strftime('%Y%m%d')) writer = csv.writer(response) writer.writerow(['Employee ID', 'Last Name', 'First Name']) writer.writerow([student.emplid, student.last_name, student.first_name]) writer.writerow([]) writer.writerow(['Description', 'School Subject', 'Course Number', 'Transfer Equivalency Group', 'Transfer Status', 'Subject', 'Catalogue Number', 'Transfer Grade Input', 'Transfer Official Grade', 'External Grade Input', 'External Official Grade', 'Units Transferred']) if 'transfers' in data: for trns in data['transfers']: descr = trns.get('descr') or '' school_subject = trns.get('school_subject') or '' crse_nbr = trns.get('crse_nbr') or '' trsnf_equivlncy_grp = trns.get('trsnf_equivlncy_grp') or '' transfr_stat = trns.get('transfr_stat') or '' subject = trns.get('subject') or '' catalog_nbr = trns.get('catalog_nbr') or '' tcd_grade_input = trns.get('tcd_grade_input') or '' tcd_grade_off = trns.get('tcd_grade_off') or '' ec_grade_input = trns.get('ec_grade_input') or '' ec_grade_off = trns.get('ec_grade_off') or '' unt_trnsfr = trns.get('unt_trnsfr') or 0 writer.writerow([descr, school_subject, crse_nbr, trsnf_equivlncy_grp, transfr_stat, subject, catalog_nbr, tcd_grade_input, tcd_grade_off, ec_grade_input, ec_grade_off, unt_trnsfr]) return response
def assets_from_csv(request, data, save=False): # Create a unit map so we don't do a lookup for each line, since most likely all items will just be from one or two # units unit_lookup = {} # Create a category map, so we can map the given string to a proper category: category_lookup = {} for cat in CATEGORY_CHOICES: category_lookup[cat[1].upper()] = cat[0] # The request should still have the units for which the user has the correct role line_counter = 0 ROW_LENGTH = 25 for row in data: line_counter += 1 row_length = len(row) if row_length != ROW_LENGTH: raise ValidationError( "Row on line %i has %i columns, whereas it should have exactly %i." % (line_counter, row_length, ROW_LENGTH)) # Instead of raising a validation for any over-long string, simply truncate them. name = row[0][:150] if not name: raise ValidationError("Line %i: Item has no name." % line_counter) unit_abbrv = row[1][:4] if unit_abbrv in unit_lookup: unit = unit_lookup[unit_abbrv.upper()] else: try: unit = Unit.objects.get(label=unit_abbrv.upper()) except Unit.DoesNotExist: raise ValidationError( "Line %i: Could not find unit matching '%s'." % (line_counter, unit_abbrv)) unit_lookup[unit_abbrv.upper()] = unit if unit not in request.units: raise ValidationError( "Line %i: You do not have permission to add items for the unit %s." % (line_counter, unit.name)) brand = row[2][:60] or None description = row[3][:400] or None serial = row[4][:60] or None tag = row[5][:60] or None express_service_code = row[6][:60] or None quantity_string = row[7] if quantity_string: try: quantity = int(quantity_string) except ValueError: raise ValidationError( "Line %i: Quantity '%s' cannot be converted to an integer." % (line_counter, quantity_string)) else: quantity = None min_qty_string = row[8] if min_qty_string: try: min_qty = int(min_qty_string) except ValueError: raise ValidationError( "Line %i: Minimum re-order quantity '%s' cannot be converted to an integer." % (line_counter, min_qty_string)) else: min_qty = None qty_ordered_string = row[9] if qty_ordered_string: try: qty_ordered = int(qty_ordered_string) except ValueError: raise ValidationError( "Line %i: Quantity on order '%s' cannot be converted to an integer." % (line_counter, qty_ordered_string)) else: qty_ordered = None min_vendor_qty_string = row[10] if min_vendor_qty_string: try: min_vendor_qty = int(min_vendor_qty_string) except ValueError: raise ValidationError( "Line %i: Minimum vendor quantity '%s' cannot be converted to an integer." % (line_counter, min_vendor_qty_string)) else: min_vendor_qty = None last_order_date_string = row[11] if last_order_date_string: try: last_order_date = parser.parse(last_order_date_string) except ValueError: raise ValidationError( "Line %i: Last order date '%s' cannot be converted to proper date." % (line_counter, last_order_date_string)) else: last_order_date = None price_string = row[12] if price_string: try: price = round(float(price_string), 2) except ValueError: raise ValidationError( "Line %i: Price '%s' cannot be converted to proper floating decimal value." % (line_counter, price_string)) else: price = None category_string = row[13] if not category_string: raise ValidationError( "Line %i: You must provide a category for your item." % line_counter) if category_string.upper() in category_lookup: category = category_lookup[category_string.upper()] else: raise ValidationError("Line %i: Category '%s' not found." % (line_counter, category_string)) location = row[14][:150] or None po = row[15][:60] or None account = row[16][:60] or None vendor = row[17][:400] or None calibration_date_string = row[18] if calibration_date_string: try: calibration_date = parser.parse(calibration_date_string) except ValueError: raise ValidationError( "Line %i: Calibration date '%s' cannot be converted to proper date." % (line_counter, calibration_date_string)) else: calibration_date = None eol_date_string = row[19] if eol_date_string: try: eol_date = parser.parse(eol_date_string) except ValueError: raise ValidationError( "Line %i: End of Life date '%s' cannot be converted to proper date." % (line_counter, eol_date_string)) else: eol_date = None notes = row[20][:400] or None service_records = row[21][:600] or None user_string = row[22] if user_string: try: user = Person.objects.get(find_userid_or_emplid(user_string)) except Person.DoesNotExist: raise ValidationError( "Line %i: User with user ID or employee ID '%s' not found." % (line_counter, user_string)) else: user = None date_shipped_string = row[23] if date_shipped_string: try: date_shipped = parser.parse(date_shipped_string) except ValueError: raise ValidationError( "Line %i: Date shipped '%s' cannot be converted to proper date." % (line_counter, date_shipped_string)) else: date_shipped = None # Common things we would expect to be in the column to mean yes/true in_use = row[24].lower() in ("yes", "true", "y", "t", "1") # And now, the world's most repetitively redundant constructor, but it should hopefully be robust. asset = Asset(name=name, unit=unit, brand=brand, description=description, serial=serial, tag=tag, express_service_code=express_service_code, quantity=quantity, min_qty=min_qty, qty_ordered=qty_ordered, min_vendor_qty=min_vendor_qty, last_order_date=last_order_date, price=price, category=category, location=location, po=po, account=account, vendor=vendor, calibration_date=calibration_date, eol_date=eol_date, notes=notes, service_records=service_records, user=user, date_shipped=date_shipped, in_use=in_use) if save: asset.save() l = LogEntry(userid=request.user.username, description="Added asset %s via file upload." % asset.name, related_object=asset) l.save() return line_counter
def _show_components_student(request, course_slug, activity_slug, userid=None, template="dashboard_student.html", staff=False): """ Show all the component submission history of this activity """ if userid == None: userid = request.user.username course = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(course.activity_set,slug=activity_slug, deleted=False) student = get_object_or_404(Person, find_userid_or_emplid(userid)) cansubmit = True submission, submitted_components = get_current_submission(student, activity, include_deleted=staff) if len(submitted_components) == 0: return NotFoundResponse(request) if submission and activity.due_date and activity.due_date < submission.created_at: late = submission.created_at - activity.due_date else: late = 0 if activity.group: gm = GroupMember.objects.filter(student__person=student, activity=activity, confirmed=True) if gm: group = gm[0].group member = gm[0].student else: group = None #cansubmit = False #messages.add_message(request, messages.INFO, "This is a group submission. You cannot submit since you aren't in a group.") else: group = None # activity should be submitable cansubmit = cansubmit and activity.submitable() if not cansubmit: messages.add_message(request, messages.ERROR, "This activity is not submittable.") return render(request, "submission/" + template, {"course":course, "activity":activity, "submission": submission, "submitted_components":submitted_components, "userid":userid, "late":late, "student":student, "group":group, "cansubmit":cansubmit}) # get all components of activity component_list = select_all_components(activity) component_list.sort() component_form_list=[] if request.method == 'POST': component_form_list = make_form_from_list(component_list, request=request) submitted_comp = [] # list all components which has content submitted in the POST not_submitted_comp = [] #list allcomponents which has no content submitted in the POST if not activity.group: new_sub = StudentSubmission() # the submission foreign key for newly submitted components new_sub.member = get_object_or_404(Member, offering__slug=course_slug, person__userid=request.user.username) elif gm: new_sub = GroupSubmission() new_sub.group = group new_sub.creator = member else: messages.add_message(request, messages.ERROR, "This is a group submission. You cannot submit since you aren't in a group.") return ForbiddenResponse(request) new_sub.activity = activity # begin validating uploaded data submitted_comp = [] not_submitted_comp = [] # validate forms one by one for data in component_form_list: component = data['comp'] form = data['form'] if form.is_valid(): sub = form.save(commit=False) sub.component = component submitted_comp.append(sub) else: # hack to replace the "required" message to something more appropriate for k,v in form.errors.items(): for i,e in enumerate(v): if e == "This field is required.": v[i] = "Nothing submitted." not_submitted_comp.append(component) # check duplicate filenames here all_ok = False while not all_ok: all_ok = True d = {} for c,s in submitted_components: d[c] = s and s.get_filename() for s in submitted_comp: d[s.component] = s.get_filename() # a list holding all file names file_name_list = [a[1] for a in d.items() if a[1] is not None] to_be_removed = [] for (i, s) in enumerate(submitted_comp): if file_name_list.count(s.get_filename()) > 1: all_ok = False to_be_removed.append(i) not_submitted_comp.append(s.component) #HACK: modify the 'errors' field in the form for data in component_form_list: if s.component == data['comp']: # assume we have only one field for submission form field_name = data['form'].fields.keys()[0] data['form']._errors[field_name] = ErrorList([u"This file has the same name as another file in your submission."]) # remove those has errors in submitted_comp to_be_removed.reverse() for t in to_be_removed: submitted_comp.pop(t) # all okay now # end validating, begin saving if len(submitted_comp) > 0: new_sub.save() for sub in submitted_comp: sub.submission = new_sub sub.save() #LOG EVENT# if activity.group: group_str = " as a member of group %s" % new_sub.group.name else: group_str = "" l = LogEntry(userid=request.user.username, description=u"submitted for %s %s%s" % (activity, sub.component.title, group_str), related_object=sub) l.save() if len(not_submitted_comp) == 0: messages.add_message(request, messages.SUCCESS, "Your submission was successful.") return HttpResponseRedirect(reverse(show_components, args=[course_slug, activity_slug])) return render(request, "submission/submission_error.html", {"course":course, "activity":activity, "component_list":component_form_list, "submitted_comp":submitted_comp, "not_submitted_comp":not_submitted_comp}) else: #not POST if activity.group and gm: messages.add_message(request, messages.INFO, "This is a group submission. You will submit on behalf of the group %s." % group.name) component_form_list = make_form_from_list(component_list) return render(request, "submission/" + template, {'component_form_list': component_form_list, "course": course, "activity": activity, "submission": submission, "submitted_components":submitted_components, "userid":userid, "late":late, "student":student, "group":group, "cansubmit":cansubmit, "is_staff":staff})