Esempio n. 1
0
def create_test_offering():
    """
    Create a CourseOffering (and related stuff) that can be used in tests with no fixtures
    """
    s = create_fake_semester('1144')
    u = Unit(label='BABL', name="Department of Babbling")
    u.save()
    o = CourseOffering(subject='BABL',
                       number='123',
                       section='F104',
                       semester=s,
                       component='LEC',
                       owner=u,
                       title='Babbling for Baferad Ferzizzles',
                       enrl_cap=100,
                       enrl_tot=5,
                       wait_tot=0)
    o.save()

    i = Person(first_name='Insley',
               last_name='Instructorberg',
               emplid=20000009,
               userid='instr')
    i.save()
    s = Person(first_name='Stanley',
               last_name='Studentson',
               emplid=20000010,
               userid='student')
    s.save()

    Member(offering=o, person=i, role='INST').save()
    Member(offering=o, person=s, role='STUD').save()

    return o
Esempio n. 2
0
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)
Esempio n. 3
0
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)
Esempio n. 4
0
def download_locations(request):
    units = Unit.sub_units(request.units)
    locations = Location.objects.visible(units)
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'inline; filename="locations-%s.csv"' % \
                                      (datetime.datetime.now().strftime('%Y%m%d'))
    writer = csv.writer(response)
    writer.writerow(['Unit', 'Campus', 'Building', 'Floor', 'Room Number', 'Square Meters', 'Room Type Description',
                     'Room Type Code', 'COU Code Description', 'Space Factor', 'COU Code Value', 'Infrastructure',
                     'Room Capacity', 'Category', 'Occupancy', 'Own/Leased', 'Comments', 'Current Booking',
                     'Active Grad Student(s)'])
    for l in locations:
        booking = l.get_current_booking()
        grad_count = None
        if booking:
            booker = booking.person
            grad_count = Supervisor.objects.filter(supervisor=booker, removed=False, student__current_status='ACTI').count()

        writer.writerow([l.unit.name, l.get_campus_display(), l.get_building_display(), l.floor, l.room_number,
                         l.square_meters, l.room_type.long_description, l.room_type.code,
                         l.room_type.COU_code_description, l.room_type.space_factor, l.room_type.COU_code_value,
                         l.get_infrastructure_display(), l.room_capacity, l.get_category_display(), l.occupancy_count,
                         l.get_own_or_lease_display(), l.comments, booking, grad_count])
    return response
Esempio n. 5
0
def add_booking(request, location_slug, from_index=0):
    location = get_object_or_404(Location, slug=location_slug, unit__in=Unit.sub_units(request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    if request.method == 'POST':
        form = BookingRecordForm(request.POST)
        if form.is_valid():
            booking = form.save(commit=False)
            booking.location = location
            booking.save(editor=editor)
            location.mark_conflicts()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Booking was created')
            l = LogEntry(userid=request.user.username,
                         description="Added booking %s for location %s" % (booking, location),
                         related_object=booking)
            l.save()
            if from_index == '1':
                return HttpResponseRedirect(reverse('space:index'))
            return view_location(request, location_slug)

        else:
            form.fields['start_time'].help_text = "Any previous bookings without an end time will also get its " \
                                                  "end time set to this."
    else:
        form = BookingRecordForm()
        form.fields['start_time'].help_text = "Any previous bookings without an end time will also get its " \
                                              "end time set to this."

    return render(request, 'space/new_booking.html', {'form': form, 'location': location, 'from_index': from_index})
Esempio n. 6
0
 def config_display(cls, units):
     committees = list(cls.all_config_fields(Unit.sub_units(units), 'committees'))
     unit_lookup = CommitteeMemberHandler._unit_lookup()
     for c in committees:
         c[3] = unit_lookup[c[3]]
     context = Context({'committees': committees})
     return cls.DISPLAY_TEMPLATE.render(context)
Esempio n. 7
0
def view(request, ra_slug):
    appointment = get_object_or_404(RAAppointment,
        Q(unit__in=Unit.sub_units(request.units)) | Q(hiring_faculty__userid=request.user.username),
        slug=ra_slug, deleted=False)
    student = appointment.person
    return render(request, 'ra/view.html',
        {'appointment': appointment, 'student': student, 'supervisor_only': not request.units})
Esempio n. 8
0
 def config_display(cls, units):
     committees = list(cls.all_config_fields(Unit.sub_units(units), 'committees'))
     unit_lookup = CommitteeMemberHandler._unit_lookup()
     for c in committees:
         c[3] = unit_lookup[c[3]]
     context = Context({'committees': committees})
     return cls.DISPLAY_TEMPLATE.render(context)
Esempio n. 9
0
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)
Esempio n. 10
0
def add_booking_attachment(request, booking_slug):
    booking = get_object_or_404(BookingRecord,
                                slug=booking_slug,
                                location__unit__in=Unit.sub_units(
                                    request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    form = BookingRecordAttachmentForm()
    context = {"booking": booking, "attachment_form": form}

    if request.method == "POST":
        form = BookingRecordAttachmentForm(request.POST, request.FILES)
        if form.is_valid():
            attachment = form.save(commit=False)
            attachment.booking_record = booking
            attachment.created_by = editor
            upfile = request.FILES['contents']
            filetype = upfile.content_type
            if upfile.charset:
                filetype += "; charset=" + upfile.charset
            attachment.mediatype = filetype
            attachment.save()
            return HttpResponseRedirect(
                reverse('space:view_booking',
                        kwargs={'booking_slug': booking.slug}))
        else:
            context.update({"attachment_form": form})

    return render(request, 'space/add_booking_record_attachment.html', context)
Esempio n. 11
0
def edit_booking(request, booking_slug):
    booking = get_object_or_404(BookingRecord,
                                slug=booking_slug,
                                location__unit__in=Unit.sub_units(
                                    request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    if request.method == 'POST':
        form = BookingRecordForm(request.POST, instance=booking)
        if form.is_valid():
            booking = form.save(commit=False)
            booking.save(editor=editor)
            booking.location.mark_conflicts()
            messages.add_message(request, messages.SUCCESS,
                                 'Booking was edited')
            l = LogEntry(userid=request.user.username,
                         description="Edited booking %s" % booking,
                         related_object=booking)
            l.save()
            return view_location(request, booking.location.slug)
    else:
        form = BookingRecordForm(instance=booking,
                                 initial={'person': booking.person.emplid})
    return render(request, 'space/edit_booking.html', {
        'form': form,
        'booking_slug': booking_slug,
        'location': booking.location
    })
Esempio n. 12
0
def new_unit_role(request, role=None):
    role_choices = [(r, ROLES[r]) for r in UNIT_ROLES]
    unit_choices = [(u.id, unicode(u)) for u in Unit.sub_units(request.units)]
    if request.method == 'POST':
        form = UnitRoleForm(request.POST)
        form.fields['role'].choices = role_choices
        form.fields['unit'].choices = unit_choices
        if form.is_valid():
            form.save()
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                         description=("new role: %s as %s in %s") %
                         (form.instance.person.userid, form.instance.role,
                          form.instance.unit),
                         related_object=form.instance)
            l.save()
            return HttpResponseRedirect(reverse(unit_role_list))
    else:
        form = UnitRoleForm()
        form.fields['role'].choices = role_choices
        form.fields['unit'].choices = unit_choices

    context = {
        'form': form,
        'UNIT_ROLES': UNIT_ROLES,
        'ROLE_DESCR': ROLE_DESCR
    }
    return render(request, 'coredata/new_unit_role.html', context)
Esempio n. 13
0
def unit_role_list(request):
    """
    Display list of who has what role (for department admins)
    """
    roles = Role.objects.filter(unit__in=Unit.sub_units(request.units),
                                role__in=UNIT_ROLES)
    return render(request, 'coredata/unit_roles.html', {'roles': roles})
Esempio n. 14
0
def download_locations(request):
    units = Unit.sub_units(request.units)
    locations = Location.objects.visible(units).select_related('unit', 'room_type')\
        .prefetch_related('safety_items', 'bookings', 'bookings__person')
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'inline; filename="locations-%s.csv"' % \
                                      (datetime.datetime.now().strftime('%Y%m%d'))
    writer = csv.writer(response)
    writer.writerow(['Unit', 'Campus', 'Building', 'Floor', 'Room Number', 'Square Meters', 'Room Type Description',
                     'Room Type Code', 'COU Code Description', 'Space Factor', 'COU Code Value', 'Infrastructure',
                     'Room Capacity', 'Category', 'Occupancy', 'Own/Leased', 'Safety Infrastructure Items', 'Comments',
                     'Current Booking', 'Active Grad Student(s)'])
    for l in locations:
        bookings = l.get_current_bookings()
        grad_count = None
        if bookings:
            grad_count = 0
            for b in bookings:
                booker = b.person
                grad_count += Supervisor.objects.filter(supervisor=booker, removed=False,
                                                        student__current_status='ACTI').count()

        writer.writerow([l.unit.name, l.get_campus_display(), l.get_building_display(), l.floor, l.room_number,
                         l.square_meters, l.room_type.long_description, l.room_type.code,
                         l.room_type.COU_code_description, l.room_type.space_factor, l.room_type.COU_code_value,
                         l.get_infrastructure_display(), l.room_capacity, l.get_category_display(), l.occupancy_count,
                         l.get_own_or_lease_display(), l.safety_items_display(), l.comments,
                         l.get_current_bookings_str(), grad_count])
    return response
Esempio n. 15
0
def add_booking(request, location_slug, from_index=0):
    location = get_object_or_404(Location, slug=location_slug, unit__in=Unit.sub_units(request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    if request.method == 'POST':
        form = BookingRecordForm(request.POST)
        if form.is_valid():
            booking = form.save(commit=False)
            booking.location = location
            booking.save(editor=editor)
            location.mark_conflicts()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Booking was created')
            l = LogEntry(userid=request.user.username,
                         description="Added booking %s for location %s" % (booking, location),
                         related_object=booking)
            l.save()
            if from_index == '1':
                return HttpResponseRedirect(reverse('space:index'))
            return view_location(request, location_slug)

        else:
            form.fields['start_time'].help_text = "Any previous bookings without an end time will also get its " \
                                                  "end time set to this."
    else:
        form = BookingRecordForm()
        form.fields['start_time'].help_text = "Any previous bookings without an end time will also get its " \
                                              "end time set to this."

    return render(request, 'space/new_booking.html', {'form': form, 'location': location, 'from_index': from_index})
Esempio n. 16
0
def person_info(request):
    """
    Get more info about this person, for AJAX updates on new RA form
    """
    result = {'programs': []}
    emplid = request.GET.get('emplid', None)
    if not emplid or not emplid.isdigit() or len(emplid) != 9:
        pass
    else:
        programs = []
        
        # GradPrograms
        emplid = request.GET['emplid']
        grads = GradStudent.objects.filter(person__emplid=emplid, program__unit__in=Unit.sub_units(request.units))
        for gs in grads:
            pdata = {
                     'program': gs.program.label,
                     'unit': gs.program.unit.name,
                     'status': gs.get_current_status_display(),
                     }
            programs.append(pdata)

        result['programs'] = programs
        
        # other SIMS info
        try:
            otherinfo = more_personal_info(emplid, needed=['citizen', 'visa'])
            result.update(otherinfo)
        except SIMSProblem, e:
            result['error'] = e.message
Esempio n. 17
0
def view_course_offerings(request, semester=None):
    """
    View to view all courses
    """
    if semester:
        semester = get_object_or_404(Semester, name=semester)
        semesters = None
    else:
        semester = Semester.get_semester(date=datetime.date.today() +
                                         datetime.timedelta(days=60))
        semesters = Semester.objects.filter(
            start__lte=datetime.date.today() +
            datetime.timedelta(days=365)).order_by('-end')[:6]

    if 'offeringsearch' in request.GET and request.GET[
            'offeringsearch'] and request.GET['offeringsearch'].isdigit():
        # handle the search for other offerings
        offering = get_object_or_404(CourseOffering,
                                     id=request.GET['offering'])
        return HttpResponseRedirect(
            reverse('advising:view_offering_notes',
                    kwargs={'course_slug': offering.slug}))

    subunits = Unit.sub_unit_ids(request.units)
    offerings = CourseOffering.objects.filter(owner__in=subunits,
                                              semester=semester)
    form = OfferingSearchForm()
    return render(
        request, 'advisornotes/view_course_offerings.html', {
            'offerings': offerings,
            'semester': semester,
            'semesters': semesters,
            'form': form
        })
Esempio n. 18
0
    def filter_queryset(self, qs):
        GET = self.request.GET

        # limit to those visible to this user
        qs = qs.filter(
            Q(unit__in=Unit.sub_units(self.request.units))
            | Q(hiring_faculty__userid=self.request.user.username)
        )
        qs = qs.exclude(deleted=True)

        # "current" contracts filter
        if 'current' in GET and GET['current'] == 'yes':
            today = datetime.date.today()
            slack = 14 # number of days to fudge the start/end
            qs = qs.filter(start_date__lte=today + datetime.timedelta(days=slack),
                           end_date__gte=today - datetime.timedelta(days=slack))

        # search box
        srch = GET.get('sSearch', None)
        if srch:
            # get RA set from haystack, and use it to limit our query.
            ra_qs = SearchQuerySet().models(RAAppointment).filter(text=srch)[:500]
            ra_qs = [r for r in ra_qs if r is not None]
            if ra_qs:
                # ignore very low scores: elasticsearch grabs too much sometimes
                max_score = max(r.score for r in ra_qs)
                ra_pks = (r.pk for r in ra_qs if r.score > max_score/5)
                qs = qs.filter(pk__in=ra_pks)
            else:
                qs = qs.none()

        return qs
Esempio n. 19
0
def person_info(request):
    """
    Get more info about this person, for AJAX updates on new RA form
    """
    result = {'programs': []}
    emplid = request.GET.get('emplid', None)
    if not emplid or not emplid.isdigit() or len(emplid) != 9:
        pass
    else:
        programs = []
        
        # GradPrograms
        emplid = request.GET['emplid']
        grads = GradStudent.objects.filter(person__emplid=emplid, program__unit__in=Unit.sub_units(request.units))
        for gs in grads:
            pdata = {
                     'program': gs.program.label,
                     'unit': gs.program.unit.name,
                     'status': gs.get_current_status_display(),
                     }
            programs.append(pdata)

        result['programs'] = programs
        
        # other SIMS info
        try:
            otherinfo = more_personal_info(emplid, needed=['citizen', 'visa'])
            result.update(otherinfo)
        except SIMSProblem, e:
            result['error'] = e.message
Esempio n. 20
0
def index(request):
    units = Unit.sub_units(request.units)
    locations = Location.objects.visible(units)
    room_types = RoomType.objects.visible(units)
    return render(request, 'space/index.html', {
        'locations': locations,
        'room_types': room_types
    })
Esempio n. 21
0
def download_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp
Esempio n. 22
0
def download_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    filename = attachment.contents.name.rsplit('/')[-1]
    resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype)
    resp['Content-Disposition'] = 'attachment; filename="' + filename + '"'
    resp['Content-Length'] = attachment.contents.size
    return resp
Esempio n. 23
0
 def __init__(self, request, *args, **kwargs):
     super(LocationForm, self).__init__(*args, **kwargs)
     unit_ids = [unit.id for unit in Unit.sub_units(request.units)]
     units = Unit.objects.filter(id__in=unit_ids)
     roomtypes = RoomType.objects.visible(units)
     self.fields['unit'].queryset = units
     self.fields['unit'].empty_label = None
     self.fields['room_type'].queryset = roomtypes
     self.fields['room_type'].empty_label = None
Esempio n. 24
0
def index(request):
    units = Unit.sub_units(request.units)
    locations = Location.objects.visible(units).select_related('room_type')\
        .prefetch_related('safety_items', 'bookings', 'bookings__person')
    room_types = RoomType.objects.visible(units).count() > 0
    return render(request, 'space/index.html', {
        'locations': locations,
        'room_types': room_types
    })
Esempio n. 25
0
 def __init__(self, request, *args, **kwargs):
     super(AssetChangeForm, self).__init__(*args, **kwargs)
     #  The following two lines look stupid, but they are not.  request.units contains a set of units.
     #  in order to be used this way, we need an actual queryset.
     #
     #  In this case, we also include subunits.  If you manage assets for a parent unit, chances are you may be
     #  adding/removing them for events in your children units.
     unit_ids = [unit.id for unit in Unit.sub_units(request.units)]
     units = Unit.objects.filter(id__in=unit_ids)
Esempio n. 26
0
 def __init__(self, request, *args, **kwargs):
     super(AssetChangeForm, self).__init__(*args, **kwargs)
     #  The following two lines look stupid, but they are not.  request.units contains a set of units.
     #  in order to be used this way, we need an actual queryset.
     #
     #  In this case, we also include subunits.  If you manage assets for a parent unit, chances are you may be
     #  adding/removing them for events in your children units.
     unit_ids = [unit.id for unit in Unit.sub_units(request.units)]
     units = Unit.objects.filter(id__in=unit_ids)
Esempio n. 27
0
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)
Esempio n. 28
0
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)
Esempio n. 29
0
def get_unit(acad_org, create=False):
    """
    Get the corresponding Unit
    """
    # there are some inconsistent acad_org values: normalize.
    if acad_org == 'GERON':
        acad_org = 'GERONTOL'
    elif acad_org == 'GEOG':
        acad_org = 'GEOGRAPH'
    elif acad_org == 'BUS':
        acad_org = 'BUS ADMIN'
    elif acad_org == 'HUM':
        acad_org = 'HUMANITIES'
    elif acad_org == 'EVSC':
        acad_org = 'ENVIRO SCI'

    try:
        unit = Unit.objects.get(acad_org=acad_org)
    except Unit.DoesNotExist:
        db = SIMSConn()
        db.execute(
            "SELECT descrformal FROM ps_acad_org_tbl "
            "WHERE eff_status='A' and acad_org=%s", (acad_org, ))

        name, = db.fetchone()
        if acad_org == 'COMP SCI':  # for test/demo imports
            label = 'CMPT'
        elif acad_org == 'ENG SCI':  # for test/demo imports
            label = 'ENSC'
        elif acad_org == 'ENVIRONMEN':  # for test/demo imports
            label = 'FENV'
        elif acad_org == 'DEAN GRAD':  # for test/demo imports
            label = 'GRAD'
        else:
            label = acad_org[:4].strip()

        if create:
            unit = Unit(acad_org=acad_org, label=label, name=name, parent=None)
            unit.save()
        else:
            raise KeyError("Unknown unit: acad_org=%s, label~=%s, name~=%s." %
                           (acad_org, label, name))

    return unit
Esempio n. 30
0
def create_true_core():
    """
    Just enough data to bootstrap a minimal environment.
    """
    import_semester_info(dry_run=False, verbose=False, long_long_ago=True, bootstrap=True)
    p = find_person('ggbaker')
    p.emplid = '200000100'
    p.save()
    u = Unit(label='UNIV', name='Simon Fraser University')
    u.save()
    r = Role(person=p, role='SYSA', unit=u)
    r.save()

    return itertools.chain(
        Semester.objects.filter(name__gt=SEMESTER_CUTOFF),
        Person.objects.filter(userid='ggbaker'),
        Unit.objects.all(),
        Role.objects.all(),
    )
Esempio n. 31
0
def chair_index(request):
    # discipline admin for these departments
    subunit_ids = Unit.sub_unit_ids(request.units)
    instr_cases = DisciplineCaseInstr.objects.filter(offering__owner__id__in=subunit_ids).select_related('owner')
    # can see cases either (1) in your unit, or (2) in subunits if the letter has been sent
    instr_cases = [c for c in instr_cases if (c.owner in request.units) or (c.letter_sent != 'WAIT')]
    instr_cases = [c.subclass() for c in instr_cases]

    context = {'instr_cases': instr_cases}
    return render_to_response("discipline/chair-index.html", context, context_instance=RequestContext(request))
Esempio n. 32
0
def get_unit(acad_org, create=False):
    """
    Get the corresponding Unit
    """
    # there are some inconsistent acad_org values: normalize.
    if acad_org == 'GERON':
        acad_org = 'GERONTOL'
    elif acad_org == 'GEOG':
        acad_org = 'GEOGRAPH'
    elif acad_org == 'BUS':
        acad_org = 'BUS ADMIN'
    elif acad_org == 'HUM':
        acad_org = 'HUMANITIES'
    elif acad_org == 'EVSC':
        acad_org = 'ENVIRO SCI'

    try:
        unit = Unit.objects.get(acad_org=acad_org)
    except Unit.DoesNotExist:
        db = SIMSConn()
        db.execute("SELECT descrformal FROM ps_acad_org_tbl "
                   "WHERE eff_status='A' and acad_org=%s", (acad_org,))
        
        name, = db.fetchone()
        if acad_org == 'COMP SCI': # for test/demo imports
            label = 'CMPT'
        elif acad_org == 'ENG SCI': # for test/demo imports
            label = 'ENSC'
        elif acad_org == 'ENVIRONMEN': # for test/demo imports
            label = 'FENV'
        elif acad_org == 'DEAN GRAD': # for test/demo imports
            label = 'GRAD'
        else:
            label = acad_org[:4].strip()

        if create:
            unit = Unit(acad_org=acad_org, label=label, name=name, parent=None)
            unit.save()
        else:
            raise KeyError("Unknown unit: acad_org=%s, label~=%s, name~=%s." % (acad_org, label, name))

    return unit
Esempio n. 33
0
def create_test_offering():
    """
    Create a CourseOffering (and related stuff) that can be used in tests with no fixtures
    """
    s = create_fake_semester('1144')
    u = Unit(label='BABL', name="Department of Babbling")
    u.save()
    o = CourseOffering(subject='BABL', number='123', section='F104', semester=s, component='LEC', owner=u,
                       title='Babbling for Baferad Ferzizzles', enrl_cap=100, enrl_tot=5, wait_tot=0)
    o.save()

    i = Person(first_name='Insley', last_name='Instructorberg', emplid=20000009, userid='instr')
    i.save()
    s = Person(first_name='Stanley', last_name='Studentson', emplid=20000010, userid='student')
    s.save()

    Member(offering=o, person=i, role='INST').save()
    Member(offering=o, person=s, role='STUD').save()

    return o
Esempio n. 34
0
def delete_unit_role(request, role_id):
    role = get_object_or_404(Role, pk=role_id, unit__in=Unit.sub_units(request.units), role__in=UNIT_ROLES)
    messages.success(request, 'Deleted role %s for %s.' % (role.get_role_display(), role.person.name()))
    #LOG EVENT#
    l = LogEntry(userid=request.user.username,
          description=("deleted role: %s for %s in %s") % (role.get_role_display(), role.person.name(), role.unit),
          related_object=role.person)
    l.save()
    
    role.delete()
    return HttpResponseRedirect(reverse(unit_role_list))
Esempio n. 35
0
def chair_index(request):
    # discipline admin for these departments
    subunit_ids = Unit.sub_unit_ids(request.units)
    has_global_role = 'UNIV' in (u.label for u in request.units)

    instr_cases = DisciplineCaseInstr.objects.filter(offering__owner__id__in=subunit_ids).select_related('owner')
    # can see cases either (1) in your unit, or (2) in subunits if the letter has been sent
    instr_cases = [c for c in instr_cases if (c.owner in request.units) or (c.letter_sent != 'WAIT')]
    instr_cases = [c.subclass() for c in instr_cases]

    context = {'instr_cases': instr_cases, 'has_global_role': has_global_role}
    return render(request, "discipline/chair-index.html", context)
Esempio n. 36
0
def delete_room_safety_item(request, safety_item_slug):
    safety_item = get_object_or_404(RoomSafetyItem, unit__in=Unit.sub_units(request.units), slug=safety_item_slug)
    if request.method == 'POST':
        safety_item.delete()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Safety item was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted safety item %s" % safety_item,
                     related_object=safety_item)
        l.save()
        return HttpResponseRedirect(reverse('space:manage_safety_items'))
Esempio n. 37
0
def create_true_core():
    """
    Just enough data to bootstrap a minimal environment.
    """
    import_semester_info(dry_run=False, verbose=False, long_long_ago=True, bootstrap=True)
    p = find_person('ggbaker')
    p.emplid = '200000100'
    p.first_name = 'Gregorʏ'
    p.pref_first_name = 'Greg'
    p.save()
    u = Unit(label='UNIV', name='Simon Fraser University')
    u.save()
    r = Role(person=p, role='SYSA', unit=u, expiry=role_expiry)
    r.save()

    return itertools.chain(
        Semester.objects.filter(name__gt=SEMESTER_CUTOFF),
        Person.objects.filter(userid='ggbaker'),
        Unit.objects.all(),
        Role.objects.all(),
    )
Esempio n. 38
0
def delete_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    attachment.hide()
    messages.add_message(request,
                         messages.SUCCESS,
                         'Attachment was deleted')
    l = LogEntry(userid=request.user.username,
                 description="Deleted attachment in booking %s" % booking,
                 related_object=attachment)
    l.save()
    return HttpResponseRedirect(reverse('space:view_booking', kwargs={'booking_slug': booking.slug}))
Esempio n. 39
0
def delete_booking_attachment(request, booking_slug, attachment_id):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    attachment = get_object_or_404(BookingRecordAttachment, booking_record=booking, pk=attachment_id)
    attachment.hide()
    messages.add_message(request,
                         messages.SUCCESS,
                         'Attachment was deleted')
    l = LogEntry(userid=request.user.username,
                 description="Deleted attachment in booking %s" % booking,
                 related_object=attachment)
    l.save()
    return HttpResponseRedirect(reverse('space:view_booking', kwargs={'booking_slug': booking.slug}))
Esempio n. 40
0
 def __init__(self, request, *args, **kwargs):
     super(AssetChangeForm, self).__init__(*args, **kwargs)
     #  The following two lines look stupid, but they are not.  request.units contains a set of units.
     #  in order to be used this way, we need an actual queryset.
     #
     #  In this case, we also include subunits.  If you manage assets for a parent unit, chances are you may be
     #  adding/removing them for events in your children units.
     unit_ids = [unit.id for unit in Unit.sub_units(request.units)]
     units = Unit.objects.filter(id__in=unit_ids)
     #  Get current events + any events in the last 12 weeks, that should give enough time to fix inventory based
     #  on events.
     self.fields['event'].queryset = OutreachEvent.objects.visible(units).\
         exclude(end_date__lt=datetime.datetime.today() - datetime.timedelta(weeks=12))
Esempio n. 41
0
def delete_room_safety_item(request, safety_item_slug):
    safety_item = get_object_or_404(RoomSafetyItem,
                                    unit__in=Unit.sub_units(request.units),
                                    slug=safety_item_slug)
    if request.method == 'POST':
        safety_item.delete()
        messages.add_message(request, messages.SUCCESS,
                             'Safety item was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted safety item %s" % safety_item,
                     related_object=safety_item)
        l.save()
        return HttpResponseRedirect(reverse('space:manage_safety_items'))
Esempio n. 42
0
def delete_location(request, location_id):
    location = get_object_or_404(Location,
                                 pk=location_id,
                                 unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        location.hidden = True
        location.save()
        messages.add_message(request, messages.SUCCESS, 'Location was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted location %s" % location,
                     related_object=location)
        l.save()
    return HttpResponseRedirect(reverse('space:index'))
Esempio n. 43
0
def delete_location(request, location_id):
    location = get_object_or_404(Location, pk=location_id, unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        location.hidden = True
        location.save()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Location was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted location %s" % location,
                     related_object=location)
        l.save()
    return HttpResponseRedirect(reverse('space:index'))
Esempio n. 44
0
def delete_roomtype(request, roomtype_id):
    roomtype = get_object_or_404(RoomType, pk=roomtype_id, unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        roomtype.hidden = True
        roomtype.save()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Room type was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted roomtype %s" % roomtype,
                     related_object=roomtype)
        l.save()
    return HttpResponseRedirect(reverse('space:list_roomtypes'))
Esempio n. 45
0
def delete_roomtype(request, roomtype_id):
    roomtype = get_object_or_404(RoomType, pk=roomtype_id, unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        roomtype.hidden = True
        roomtype.save()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Room type was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted roomtype %s" % roomtype,
                     related_object=roomtype)
        l.save()
    return HttpResponseRedirect(reverse('space:list_roomtypes'))
Esempio n. 46
0
def browse(request):
    units = Unit.sub_units(request.units)
    hiring_choices = [('all', 'All')] + possible_supervisors(units)
    project_choices = [('all', 'All')] + [(p.id, unicode(p)) for p in Project.objects.filter(unit__in=units, hidden=False)]
    account_choices = [('all', 'All')] + [(a.id, unicode(a)) for a in Account.objects.filter(unit__in=units, hidden=False)]
    if 'data' in request.GET:
        # AJAX query for data
        ras = RAAppointment.objects.filter(unit__in=units, deleted=False) \
                .select_related('person', 'hiring_faculty', 'project', 'account')
        if 'hiring_faculty' in request.GET and request.GET['hiring_faculty'] != 'all':
            ras = ras.filter(hiring_faculty__id=request.GET['hiring_faculty'])
        if 'project' in request.GET and request.GET['project'] != 'all':
            ras = ras.filter(project__id=request.GET['project'], project__unit__in=units)
        if 'account' in request.GET and request.GET['account'] != 'all':
            ras = ras.filter(account__id=request.GET['account'], account__unit__in=units)

        truncated = False
        if ras.count() > 200:
            ras = ras[:200]
            truncated = True
        data = []
        for ra in ras:
            radata = {
                'slug': ra.slug,
                'name': ra.person.sortname(),
                'hiring': ra.hiring_faculty.sortname(),
                'project': unicode(ra.project),
                'project_hidden': ra.project.hidden,
                'account': unicode(ra.account),
                'account_hidden': ra.account.hidden,
                'start': datefilter(ra.start_date, settings.GRAD_DATE_FORMAT),
                'end': datefilter(ra.end_date, settings.GRAD_DATE_FORMAT),
                'amount': '$'+unicode(ra.lump_sum_pay),
                }
            data.append(radata)
        
        response = HttpResponse(content_type="application/json")
        json.dump({'truncated': truncated, 'data': data}, response, indent=1)
        return response

    else:
        # request for page
        form = RABrowseForm()
        form.fields['hiring_faculty'].choices = hiring_choices
        form.fields['account'].choices = account_choices
        form.fields['project'].choices = project_choices
        context = {
            'form': form
            }
        return render(request, 'ra/browse.html', context)
Esempio n. 47
0
 def __init__(self, request, *args, **kwargs):
     super(LocationForm, self).__init__(*args, **kwargs)
     unit_ids = [unit.id for unit in Unit.sub_units(request.units)]
     units = Unit.objects.filter(id__in=unit_ids)
     roomtypes = RoomType.objects.visible(units)
     self.fields['unit'].queryset = units
     self.fields['unit'].empty_label = None
     self.fields['room_type'].queryset = roomtypes
     self.fields['room_type'].empty_label = None
     safety_items = RoomSafetyItem.objects.visible(units)
     self.fields['safety_items'].queryset = safety_items
     initial = kwargs.setdefault('initial', {})
     if 'instance' in kwargs:
         initial['safety_items'] = [c.pk for c in kwargs['instance'].safety_items.all()]
Esempio n. 48
0
def missing_instructors(request, unit_slug):
    unit = get_object_or_404(Unit, slug=unit_slug)
    if unit not in Unit.sub_units(request.units):
        return ForbiddenResponse(request, "Not an admin for this unit")

    # build a set of all instructors that don't have an instructor-appropriate role
    roles = dict(((r.person, r.role) for r in Role.objects.filter(
        unit=unit, role__in=INSTR_ROLES).select_related('person')))
    missing = set()
    long_ago = datetime.date.today() - datetime.timedelta(days=365 * 3)
    instructors = Member.objects.filter(role="INST", offering__owner=unit,
                                        offering__semester__start__gte=long_ago) \
                                .exclude(offering__component='CAN') \
                                .exclude(person__userid=None) \
                                .select_related('person')
    for i in instructors:
        if i.person not in roles:
            missing.add(i.person)
    missing = list(missing)
    missing.sort()
    initial = [{'person': p, 'role': None} for p in missing]

    if request.method == 'POST':
        formset = InstrRoleFormSet(request.POST, initial=initial)
        if formset.is_valid():
            count = 0
            for f in formset.forms:
                p = f.cleaned_data['person']
                r = f.cleaned_data['role']
                if r == "NONE" or p not in missing:
                    continue

                r = Role(person=p, role=r, unit=unit)
                r.save()
                count += 1

                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                             description=("new role: %s as %s") %
                             (p.userid, r),
                             related_object=r)
                l.save()
            messages.success(request,
                             'Set instructor roles for %i people.' % (count))
            return HttpResponseRedirect(reverse('coredata.views.unit_admin'))
    else:
        formset = InstrRoleFormSet(initial=initial)

    context = {'formset': formset, 'unit': unit}
    return render(request, 'coredata/missing_instructors.html', context)
Esempio n. 49
0
def edit_unit(request, unit_slug=None):
    if unit_slug:
        unit = get_object_or_404(Unit, slug=unit_slug)
    else:
        unit = Unit()
    
    if request.method == 'POST':
        form = UnitForm(instance=unit, data=request.POST)
        if form.is_valid():
            unit.slug = None
            form.save()
            messages.success(request, 'Edited unit %s.' % (unit.name))
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("edited unit %s") % (form.instance.slug),
                  related_object=unit)
            l.save()
            return HttpResponseRedirect(reverse(unit_list))
    else:
        form = UnitForm(instance=unit)
    
    context = {'form': form}
    return render(request, 'coredata/edit_unit.html', context)
Esempio n. 50
0
def delete_booking(request, booking_id):
    booking = get_object_or_404(BookingRecord, pk=booking_id, location__unit__in=Unit.sub_units(request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    if request.method == 'POST':
        booking.hidden = True
        booking.save(editor=editor)
        booking.location.mark_conflicts()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Booking was deleted')
        l = LogEntry(userid=request.user.username,
                     description="Deleted booking %s" % booking,
                     related_object=booking)
        l.save()
    return view_location(request, booking.location.slug)
Esempio n. 51
0
def send_memo(request, booking_slug, from_index=0):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    booking_memo = BookingMemo(booking_record=booking, created_by=editor)
    booking_memo.email_memo()
    booking_memo.save()
    messages.add_message(request,
                         messages.SUCCESS,
                         'Memo was sent')
    l = LogEntry(userid=request.user.username,
                 description="Send memo to %s" % booking.person,
                 related_object=booking_memo)
    l.save()
    if from_index == '1':
        return HttpResponseRedirect(reverse('space:view_location', kwargs={'location_slug': booking.location.slug}))
    return HttpResponseRedirect(reverse('space:view_booking', kwargs={'booking_slug': booking.slug}))
Esempio n. 52
0
def missing_instructors(request, unit_slug):
    unit = get_object_or_404(Unit, slug=unit_slug)
    if unit not in Unit.sub_units(request.units):
        return ForbiddenResponse(request, "Not an admin for this unit")

    # build a set of all instructors that don't have an instructor-appropriate role
    roles = dict(((r.person, r.role) for r in Role.objects.filter(unit=unit, role__in=INSTR_ROLES).select_related('person')))
    missing = set()
    long_ago = datetime.date.today() - datetime.timedelta(days=365*3)
    instructors = Member.objects.filter(role="INST", offering__owner=unit,
                                        offering__semester__start__gte=long_ago) \
                                .exclude(offering__component='CAN') \
                                .exclude(person__userid=None) \
                                .select_related('person')
    for i in instructors:
        if i.person not in roles:
            missing.add(i.person)
    missing = list(missing)
    missing.sort()
    initial = [{'person': p, 'role': None} for p in missing]

    if request.method == 'POST':
        formset = InstrRoleFormSet(request.POST, initial=initial)
        if formset.is_valid():
            count = 0
            for f in formset.forms:
                p = f.cleaned_data['person']
                r = f.cleaned_data['role']
                if r == "NONE" or p not in missing:
                    continue
                
                r = Role(person=p, role=r, unit=unit)
                r.save()
                count += 1

                #LOG EVENT#
                l = LogEntry(userid=request.user.username,
                      description=("new role: %s as %s") % (p.userid, r),
                      related_object=r)
                l.save()
            messages.success(request, 'Set instructor roles for %i people.' % (count))
            return HttpResponseRedirect(reverse('coredata.views.unit_admin'))
    else:
        formset = InstrRoleFormSet(initial=initial)

    context = {'formset': formset, 'unit': unit}
    return render(request, 'coredata/missing_instructors.html', context)
Esempio n. 53
0
def edit_room_safety_item(request, safety_item_slug):
    safety_item = get_object_or_404(RoomSafetyItem, unit__in=Unit.sub_units(request.units), slug=safety_item_slug)
    if request.method == 'POST':
        form = RoomSafetyItemForm(request, request.POST, instance=safety_item)
        if form.is_valid():
            item = form.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Safety item was saved')
            l = LogEntry(userid=request.user.username,
                         description="Edited safety item %s" % item,
                         related_object=item)
            l.save()
            return HttpResponseRedirect(reverse('space:manage_safety_items'))
    else:
        form = RoomSafetyItemForm(request, instance=safety_item)
    return render(request, 'space/edit_safety_item.html', {'form': form, 'safety_item_slug': safety_item_slug})
Esempio n. 54
0
def download_visas_csv(request):
    visas = Visa.objects.visible_by_unit(Unit.sub_units(request.units))
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'inline; filename="visas-%s.csv"' % datetime.now().strftime('%Y%m%d')
    writer = csv.writer(response)
    writer.writerow(['Person', 'Email', 'Unit', 'Start Date', 'End Date', 'Type', 'Validity'])
    for v in visas:
        person = v.person
        email = v.person.email()
        unit = v.unit.name
        start_date = v.start_date
        end_date = v.end_date
        visa_type = v.status
        validity = v.get_validity()
        writer.writerow([person, email, unit, start_date, end_date, visa_type, validity])

    return response
Esempio n. 55
0
def edit_roomtype(request, roomtype_slug):
    roomtype = get_object_or_404(RoomType, slug=roomtype_slug, unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        form = RoomTypeForm(request, request.POST, instance=roomtype)
        if form.is_valid():
            roomtype = form.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Room type was edited')
            l = LogEntry(userid=request.user.username,
                         description="Edited roomtype %s" % roomtype,
                         related_object=roomtype)
            l.save()
            return HttpResponseRedirect(reverse('space:list_roomtypes'))
    else:
        form = RoomTypeForm(request, instance=roomtype)
    return render(request, 'space/edit_roomtype.html', {'form': form, 'roomtype': roomtype})
Esempio n. 56
0
def edit_location(request, location_slug, from_index=0):
    location = get_object_or_404(Location, slug=location_slug, unit__in=Unit.sub_units(request.units))
    if request.method == 'POST':
        form = LocationForm(request, request.POST, instance=location)
        if form.is_valid():
            location = form.save()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Location was edited')
            l = LogEntry(userid=request.user.username,
                         description="Edited location %s" % location,
                         related_object=location)
            l.save()
            if from_index == '1':
                return HttpResponseRedirect(reverse('space:index'))
            return view_location(request, location.slug)
    else:
        form = LocationForm(request, instance=location)
    return render(request, 'space/edit_location.html', {'form': form, 'location': location, 'from_index': from_index})
Esempio n. 57
0
def edit_booking(request, booking_slug):
    booking = get_object_or_404(BookingRecord, slug=booking_slug, location__unit__in=Unit.sub_units(request.units))
    editor = get_object_or_404(Person, userid=request.user.username)
    if request.method == 'POST':
        form = BookingRecordForm(request.POST, instance=booking)
        if form.is_valid():
            booking = form.save(commit=False)
            booking.save(editor=editor)
            booking.location.mark_conflicts()
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Booking was edited')
            l = LogEntry(userid=request.user.username,
                         description="Edited booking %s" % booking,
                         related_object=booking)
            l.save()
            return view_location(request, booking.location.slug)
    else:
        form = BookingRecordForm(instance=booking, initial={'person': booking.person.emplid})
    return render(request, 'space/edit_booking.html', {'form': form, 'booking_slug': booking_slug,
                                                       'location': booking.location })
Esempio n. 58
0
def new_unit_role(request, role=None):
    role_choices = [(r,ROLES[r]) for r in UNIT_ROLES]
    unit_choices = [(u.id, unicode(u)) for u in Unit.sub_units(request.units)]
    if request.method == 'POST':
        form = UnitRoleForm(request.POST)
        form.fields['role'].choices = role_choices
        form.fields['unit'].choices = unit_choices
        if form.is_valid():
            form.save()
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("new role: %s as %s in %s") % (form.instance.person.userid, form.instance.role, form.instance.unit),
                  related_object=form.instance)
            l.save()
            return HttpResponseRedirect(reverse(unit_role_list))
    else:
        form = UnitRoleForm()
        form.fields['role'].choices = role_choices
        form.fields['unit'].choices = unit_choices
        
    context = {'form': form, 'UNIT_ROLES': UNIT_ROLES, 'ROLE_DESCR': ROLE_DESCR}
    return render(request, 'coredata/new_unit_role.html', context)
Esempio n. 59
0
def unit_address(request, unit_slug):
    unit = get_object_or_404(Unit, slug=unit_slug)
    if unit not in Unit.sub_units(request.units):
        return ForbiddenResponse(request, "Not an admin for this unit")
    
    if request.method == 'POST':
        form = UnitAddressForm(data=request.POST, unit=unit)
        if form.is_valid():
            #print form.cleaned_data
            form.copy_to_unit()
            unit.save()
            
            #LOG EVENT#
            l = LogEntry(userid=request.user.username,
                  description=("updated contact info for %s") % (unit.label),
                  related_object=unit)
            l.save()
            return HttpResponseRedirect(reverse('coredata.views.unit_admin'))
    else:
        form = UnitAddressForm(unit=unit)
    context = {'unit': unit, 'form': form}
    return render(request, "coredata/unit_address.html", context)
Esempio n. 60
0
def view_courses(request):
    """
    View to view all courses
    """
    if 'coursesearch' in request.GET and 'course' in request.GET \
            and request.GET['course'] and request.GET['course'].isdigit():
        # handle the search for other courses
        offering = get_object_or_404(Course, id=request.GET['course'])
        return HttpResponseRedirect(reverse('advisornotes.views.view_course_notes', kwargs={'unit_course_slug': offering.slug}))

    # all courses where a recent offering was owned by relevant units
    subunits = Unit.sub_unit_ids(request.units)
    old_sem = Semester.get_semester(datetime.date.today() - datetime.timedelta(days=365 * 2))
    offerings = CourseOffering.objects.filter(owner__in=subunits, semester__name__gte=old_sem.name) \
                                      .values('course').order_by().distinct()

    # all courses where there are notes from relevant units
    notes = ArtifactNote.objects.filter(unit__in=request.units).exclude(course__isnull=True) \
                                .values('course').order_by().distinct()
    
    with_note_ids = set(n['course'] for n in notes)
    course_ids = set(o['course'] for o in offerings)
    course_ids |= with_note_ids

    # all current CourseOfferings with notes: interested in those Courses too
    offering_notes = ArtifactNote.objects.filter(unit__in=request.units, course_offering__semester__name__gte=old_sem.name) \
                                        .values('course_offering__course').order_by().distinct()
    offering_note_ids = set(n['course_offering__course'] for n in offering_notes)
    with_note_ids |= offering_note_ids
    course_ids |= offering_note_ids
    
    courses = Course.objects.filter(id__in=course_ids)
    form = CourseSearchForm()

    return render(request,
        'advisornotes/view_courses.html',
        {'courses': courses, 'with_note_ids': with_note_ids, 'form': form}
    )