Example #1
0
    def resources_timeslot_import(self, request, tl, one, two, module, extra,
                                  prog):
        context = {}
        response = None

        controller = ResourceController(prog)

        import_mode = 'preview'
        if 'import_confirm' in request.POST and request.POST[
                'import_confirm'] == 'yes':
            import_mode = 'save'

        import_form = TimeslotImportForm(request.POST)
        if not import_form.is_valid():
            context['import_timeslot_form'] = import_form
        else:
            past_program = import_form.cleaned_data['program']
            start_date = import_form.cleaned_data['start_date']

            if past_program == prog:
                raise ESPError(
                    "You're trying to import timeslots from a program"
                    " to itself! Try a different program instead.",
                    log=False)

            #   Figure out timeslot dates
            new_timeslots = []
            prev_timeslots = past_program.getTimeSlots().order_by('start')
            time_delta = start_date - prev_timeslots[0].start.date()
            for orig_timeslot in prev_timeslots:
                new_timeslot = Event(
                    program=self.program,
                    event_type=orig_timeslot.event_type,
                    short_description=orig_timeslot.short_description,
                    description=orig_timeslot.description,
                    priority=orig_timeslot.priority,
                    start=orig_timeslot.start + time_delta,
                    end=orig_timeslot.end + time_delta,
                )
                #   Save the new timeslot only if it doesn't duplicate an existing one
                if import_mode == 'save' and not Event.objects.filter(
                        program=new_timeslot.program,
                        start=new_timeslot.start,
                        end=new_timeslot.end).exists():
                    new_timeslot.save()
                new_timeslots.append(new_timeslot)

            #   Render a preview page showing the resources for the previous program if desired
            context['past_program'] = past_program
            context['start_date'] = start_date.strftime('%m/%d/%Y')
            context['new_timeslots'] = new_timeslots
            if import_mode == 'preview':
                context['prog'] = self.program
                response = render_to_response(
                    self.baseDir() + 'timeslot_import.html', request, context)
            else:
                extra = 'timeslot'

        return (response, context)
Example #2
0
 def save(self, vr=None):
     if vr:
         ts = vr.timeslot
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data[
             'description']
         ts.save()
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.program = self.program
         vr.save()
     else:
         ts = Event()
         ts.anchor = self.program.anchor
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data[
             'description']
         ts.event_type, created = EventType.objects.get_or_create(
             description='Volunteer')
         ts.save()
         vr = VolunteerRequest()
         vr.program = self.program
         vr.timeslot = ts
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.save()
Example #3
0
 def save(self, vr=None):
     if vr:
         ts = vr.timeslot
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data[
             'description']
         ts.save()
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.program = self.program
         vr.save()
     else:
         ts = Event()
         ts.program = self.program
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data[
             'description']
         ts.event_type = EventType.get_from_desc('Volunteer')
         ts.save()
         vr = VolunteerRequest()
         vr.program = self.program
         vr.timeslot = ts
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.save()
    def resources_timeslot_import(self, request, tl, one, two, module, extra, prog):
        context = {}
        response = None

        controller = ResourceController(prog)

        import_mode = 'preview'
        if 'import_confirm' in request.POST and request.POST['import_confirm'] == 'yes':
            import_mode = 'save'

        import_form = TimeslotImportForm(request.POST)
        if not import_form.is_valid():
            context['import_timeslot_form'] = import_form
        else:
            past_program = import_form.cleaned_data['program']
            start_date = import_form.cleaned_data['start_date']

            #   Figure out timeslot dates
            new_timeslots = []
            prev_timeslots = past_program.getTimeSlots().order_by('start')
            time_delta = start_date - prev_timeslots[0].start.date()
            for orig_timeslot in prev_timeslots:
                new_timeslot = Event(
                    program = self.program,
                    event_type = orig_timeslot.event_type,
                    short_description = orig_timeslot.short_description,
                    description = orig_timeslot.description,
                    priority = orig_timeslot.priority,
                    start = orig_timeslot.start + time_delta,
                    end   = orig_timeslot.end + time_delta,
                )
                #   Save the new timeslot only if it doesn't duplicate an existing one
                if import_mode == 'save' and not Event.objects.filter(program=new_timeslot.program, start=new_timeslot.start, end=new_timeslot.end).exists():
                    new_timeslot.save()
                new_timeslots.append(new_timeslot)

            #   Render a preview page showing the resources for the previous program if desired
            context['past_program'] = past_program
            context['start_date'] = start_date.strftime('%m/%d/%Y')
            context['new_timeslots'] = new_timeslots
            if import_mode == 'preview':
                context['prog'] = self.program
                response = render_to_response(self.baseDir()+'timeslot_import.html', request, context)
            else:
                extra = 'timeslot'

        return (response, context)
Example #5
0
 def available_times(self, anchor=None):
     if anchor:
         event_list = filter(
             lambda x: self.is_available(timeslot=x),
             list(self.matching_times().filter(anchor=anchor)))
     else:
         event_list = filter(lambda x: self.is_available(timeslot=x),
                             list(self.matching_times()))
     return '<br /> '.join([unicode(e) for e in Event.collapse(event_list)])
Example #6
0
    def add_or_edit_timeslot(self, form):
        """ form is a TimeslotForm object   """
        if form.cleaned_data['id'] is not None:
            new_timeslot = Event.objects.get(id=form.cleaned_data['id'])
        else:
            new_timeslot = Event()

        form.save_timeslot(self.program, new_timeslot)
        return new_timeslot
Example #7
0
    def teacher_events(self, request, tl, one, two, module, extra, prog):
        context = {}

        if request.method == 'POST':
            data = request.POST

            if data['command'] == 'delete':
                #   delete timeslot
                ts = Event.objects.get(id=data['id'])
                ts.delete()

            elif data['command'] == 'add':
                #   add/edit timeslot
                form = TimeslotForm(data)
                if form.is_valid():
                    new_timeslot = Event()

                    # decide type
                    type = "training"

                    if data.has_key(
                            'submit') and data['submit'] == "Add Interview":
                        type = "interview"

                    form.save_timeslot(self.program, new_timeslot, type,
                                       self.qscs[type])
                else:
                    context['timeslot_form'] = form

        if 'timeslot_form' not in context:
            context['timeslot_form'] = TimeslotForm()

        interview_times = self.getTimes('interview').select_related(
            'anchor__userbit_qsc__user')
        training_times = self.getTimes('training').select_related(
            'anchor__userbit_qsc__user')

        for ts in list(interview_times) + list(training_times):
            ts.teachers = [
                x.user.first_name + ' ' + x.user.last_name + ' <' +
                x.user.email + '>' for x in self.bitsBySlot(ts.anchor)
            ]

        context['prog'] = prog
        context['interview_times'] = interview_times
        context['training_times'] = training_times

        return render_to_response(self.baseDir() + 'teacher_events.html',
                                  request, (prog, tl), context)
 def save(self, vr=None):
     if vr:
         ts = vr.timeslot
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data['description']
         ts.save()
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.program = self.program
         vr.save()
     else:
         ts = Event()
         ts.program = self.program
         ts.start = self.cleaned_data['start_time']
         ts.end = self.cleaned_data['end_time']
         ts.short_description = ts.description = self.cleaned_data['description']
         ts.event_type = EventType.get_from_desc('Volunteer')
         ts.save()
         vr = VolunteerRequest()
         vr.program = self.program
         vr.timeslot = ts
         vr.num_volunteers = self.cleaned_data['num_volunteers']
         vr.save()
Example #9
0
    def prepare(self, context={}):
        from esp.program.controllers.studentclassregmodule import RegistrationTypeController as RTC
        verbs = RTC.getVisibleRegistrationTypeNames(prog=self.program)
        regProf = RegistrationProfile.getLastForProgram(
            get_current_request().user, self.program)
        timeslots = self.program.getTimeSlots(
            types=['Class Time Block', 'Compulsory'])
        classList = ClassSection.prefetch_catalog_data(
            regProf.preregistered_classes(verbs=verbs))

        prevTimeSlot = None
        blockCount = 0

        user = get_current_request().user
        is_onsite = user.isOnsite(self.program)
        scrmi = self.program.studentclassregmoduleinfo

        #   Filter out volunteer timeslots
        timeslots = [
            x for x in timeslots if x.event_type.description != 'Volunteer'
        ]

        schedule = []
        timeslot_dict = {}
        for sec in classList:
            #   Get the verbs all the time in order for the schedule to show
            #   the student's detailed enrollment status.  (Performance hit, I know.)
            #   - Michael P, 6/23/2009
            #   if scrmi.use_priority:
            sec.verbs = sec.getRegVerbs(user, allowed_verbs=verbs)
            sec.verb_names = [v.name for v in sec.verbs]
            sec.is_enrolled = True if "Enrolled" in sec.verb_names else False

            # While iterating through the meeting times for a section,
            # we use this variable to keep track of the first timeslot.
            # In the section_dict appended to timeslot_dict,
            # we save whether or not this is the first timeslot for this
            # section. If it isn't, the student schedule will indicate
            # this, and will not display the option to remove the
            # section. This is to prevent students from removing what
            # they have mistaken to be duplicated classes from their
            # schedules.
            first_meeting_time = True

            for mt in sec.get_meeting_times().order_by('start'):
                section_dict = {
                    'section': sec,
                    'first_meeting_time': first_meeting_time
                }
                first_meeting_time = False
                if mt.id in timeslot_dict:
                    timeslot_dict[mt.id].append(section_dict)
                else:
                    timeslot_dict[mt.id] = [section_dict]

        for i in range(len(timeslots)):
            timeslot = timeslots[i]
            daybreak = False
            if prevTimeSlot != None:
                if not Event.contiguous(prevTimeSlot, timeslot):
                    blockCount += 1
                    daybreak = True

            if timeslot.id in timeslot_dict:
                cls_list = timeslot_dict[timeslot.id]
                doesnt_have_enrollment = not any(sec['section'].is_enrolled
                                                 for sec in cls_list)
                schedule.append((timeslot, cls_list, blockCount + 1,
                                 doesnt_have_enrollment))
            else:
                schedule.append((timeslot, [], blockCount + 1, False))

            prevTimeSlot = timeslot

        context['num_classes'] = len(classList)
        context['timeslots'] = schedule
        context['use_priority'] = scrmi.use_priority
        context['allow_removal'] = self.deadline_met('/Removal')

        return context
Example #10
0
 def available_times_html(self, program=None):
     return '<br /> '.join([
         unicode(e) for e in Event.collapse(self.available_times(program))
     ])
Example #11
0
    def availabilityForm(self, request, tl, one, two, prog, teacher, isAdmin):
        time_options = self.program.getTimeSlots(types=[self.event_type()])
        #   Group contiguous blocks
        if not Tag.getBooleanTag('availability_group_timeslots', default=True):
            time_groups = [list(time_options)]
        else:
            time_groups = Event.group_contiguous(list(time_options))

        blank = False

        available_slots = teacher.getAvailableTimes(self.program, True)
        # must set the ignore_classes=True parameter above, otherwise when a teacher tries to edit their
        # availability, it will show their scheduled times as unavailable.

        #   Fetch the timeslots the teacher is scheduled in and grey them out.
        #   If we found a timeslot that they are scheduled in but is not available, show a warning.
        taken_slots = []
        avail_and_teaching = []
        user_sections = teacher.getTaughtSections(self.program)
        conflict_found = False
        for section in user_sections:
            for timeslot in section.get_meeting_times():
                taken_slots.append(timeslot)
                if timeslot not in available_slots:
                    conflict_found = True
                else:
                    avail_and_teaching.append(timeslot)

        if request.method == 'POST':
            #   Process form
            post_vars = request.POST

            #   Reset teacher's availability
            teacher.clearAvailableTimes(self.program)
            #   But add back in the times they're teaching
            #   because those aren't submitted with the form
            for timeslot in avail_and_teaching:
                teacher.addAvailableTime(self.program, timeslot)

            #   Add in resources for the checked available times.
            timeslot_ids = map(int, post_vars.getlist('timeslots'))
            timeslots = Event.objects.filter(
                id__in=timeslot_ids).order_by('start')
            missing_tsids = set(timeslot_ids) - set(x.id for x in timeslots)
            if missing_tsids:
                raise ESPError(
                    'Received requests for the following timeslots that don\'t exist: %s'
                    % str(list(sorted(missing_tsids))),
                    log=False)

            blank = (not (bool(len(timeslot_ids) + len(avail_and_teaching))))
            if not blank:
                for timeslot in timeslots:
                    teacher.addAvailableTime(self.program, timeslot)

                #   Send an e-mail showing availability to the teacher (and the archive)
                ccc = ClassCreationController(self.program)
                ccc.send_availability_email(teacher)

                if isAdmin:
                    #   Return to the relevant check_availability page
                    return HttpResponseRedirect(
                        '/manage/%s/%s/check_availability?user=%s' %
                        (one, two, teacher.id))
                else:
                    #   Return to the main registration page
                    return self.goToCore(tl)

        #   Show new form

        if not (len(available_slots) or
                blank):  # I'm not sure whether or not we want the "or blank"
            #   If they didn't enter anything, make everything checked by default.
            available_slots = self.program.getTimeSlots(
                types=[self.event_type()])
            #   The following 2 lines mark the teacher as always available.  This
            #   is sometimes helpful, but not usually the desired behavior.
            #   for a in available_slots:
            #       teacher.addAvailableTime(self.program, a)

        context = {
            'groups': [{
                'selections': [{
                    'checked': (t in available_slots),
                    'taken': (t in taken_slots),
                    'slot': t
                } for t in group]
            } for group in time_groups]
        }
        context['num_groups'] = len(context['groups'])
        context['prog'] = self.program
        context['is_overbooked'] = (
            not self.isCompleted()
            and (teacher.getTaughtTime(self.program) > timedelta(0)))
        context['submitted_blank'] = blank
        context['conflict_found'] = conflict_found
        context['teacher_user'] = teacher

        return render_to_response(self.baseDir() + 'availability_form.html',
                                  request, context)
    def resources(self, request, tl, one, two, module, extra, prog):
        """ Main view for the resource module.
            Besides displaying resource information, the 'extra' slug at the
            end of the URL selects which aspect of resources to perform
            more detailed operations on.
        """

        #   First, run the handler specified at the end of the URL.
        #   (The handler specifies which type of model we are working with.)
        handlers = {
            'timeslot': self.resources_timeslot,
            'restype': self.resources_restype,
            'classroom': self.resources_classroom,
            'timeslot_import': self.resources_timeslot_import,
            'classroom_import': self.resources_classroom_import,
            'equipment': self.resources_equipment,
        }
        if extra in handlers:
            (response, context) = handlers[extra](request, tl, one, two, module, extra, prog)
        else:
            response = None
            context = {}

        #   Display the immediate response (e.g. a confirmation page) if the handler provided one
        if response:
            return response

        #   Group contiguous blocks of time for the program
        time_options = self.program.getTimeSlots(exclude_types=[])
        time_groups = Event.group_contiguous(list(time_options))

        #   Retrieve remaining context information
        context['timeslots'] = [{'selections': group} for group in time_groups]

        if 'timeslot_form' not in context:
            context['timeslot_form'] = TimeslotForm()

        context['resource_types'] = self.program.getResourceTypes()
        for c in context['resource_types']:
            if c.program is None:
                c.is_global = True

        if 'restype_form' not in context:
            context['restype_form'] = ResourceTypeForm()

        if 'classroom_form' not in context:
            context['classroom_form'] = ClassroomForm(self.program)

        if 'equipment_form' not in context:
            context['equipment_form'] = EquipmentForm(self.program)

        if 'import_form' not in context:
            context['import_form'] = ClassroomImportForm()

        if 'import_timeslot_form' not in context:
            context['import_timeslot_form'] = TimeslotImportForm()

        context['open_section'] = extra
        context['prog'] = self.program
        context['module'] = self

        #   Display default form
        return render_to_response(self.baseDir()+'resource_main.html', request, context)
    def studentreg2phase(self, request, tl, one, two, module, extra, prog):
        """
        Serves the two-phase student reg page. This page includes instructions
        for registration, and links to the phase1/phase2 sub-pages.
        """

        timeslot_dict = {}
        # Populate the timeslot dictionary with the priority to class title
        # mappings for each timeslot.
        priority_regs = StudentRegistration.valid_objects().filter(
            user=request.user, relationship__name__startswith='Priority')
        priority_regs = priority_regs.select_related(
            'relationship', 'section', 'section__parent_class')
        for student_reg in priority_regs:
            rel = student_reg.relationship
            title = student_reg.section.parent_class.title
            sec = student_reg.section
            times = sec.meeting_times.all().order_by('start')
            if times.count() == 0:
                continue
            timeslot = times[0].id
            if not timeslot in timeslot_dict:
                timeslot_dict[timeslot] = {rel: title}
            else:
                timeslot_dict[timeslot][rel] = title

        star_counts = {}
        interests = StudentSubjectInterest.valid_objects().filter(
            user=request.user, subject__parent_program=prog)
        interests = interests.select_related(
            'subject').prefetch_related('subject__sections__meeting_times')
        for interest in interests:
            cls = interest.subject
            for sec in cls.sections.all():
                times = sec.meeting_times.all()
                if len(times) == 0:
                    continue
                timeslot = min(times, key=lambda t: t.start).id
                if not timeslot in star_counts:
                    star_counts[timeslot] = 1
                else:
                    star_counts[timeslot] += 1

        # Iterate through timeslots and create a list of tuples of information
        prevTimeSlot = None
        blockCount = 0
        schedule = []
        timeslots = prog.getTimeSlots(types=['Class Time Block', 'Compulsory'])
        for i in range(len(timeslots)):
            timeslot = timeslots[i]
            if prevTimeSlot != None:
                if not Event.contiguous(prevTimeSlot, timeslot):
                    blockCount += 1

            if timeslot.id in timeslot_dict:
                priority_dict = timeslot_dict[timeslot.id]
                priority_list = sorted(priority_dict.items())
            else:
                priority_list = []
            if timeslot.id in star_counts:
                priority_list.append((
                    'Starred', "(%d classes)" % star_counts[timeslot.id]))
            schedule.append((timeslot, priority_list, blockCount + 1))

            prevTimeSlot = timeslot

        context = {}
        context['timeslots'] = schedule

        return render_to_response(
            self.baseDir()+'studentregtwophase.html', request, context)
    def prepare(self, context={}):
        from esp.program.controllers.studentclassregmodule import RegistrationTypeController as RTC
        verbs = RTC.getVisibleRegistrationTypeNames(prog=self.program)
        regProf = RegistrationProfile.getLastForProgram(
            get_current_request().user, self.program)
        timeslots = self.program.getTimeSlotList(exclude_compulsory=False)
        classList = ClassSection.prefetch_catalog_data(
            regProf.preregistered_classes(verbs=verbs))

        prevTimeSlot = None
        blockCount = 0

        if not isinstance(get_current_request().user, ESPUser):
            user = ESPUser(get_current_request().user)
        else:
            user = get_current_request().user

        is_onsite = user.isOnsite(self.program)
        scrmi = self.program.getModuleExtension('StudentClassRegModuleInfo')
        # Hack, to hide the Saturday night timeslots from grades 7-8
        if not is_onsite and not user.getGrade() > 8:
            timeslots = [x for x in timeslots if x.start.hour < 19]

        #   Filter out volunteer timeslots
        timeslots = [
            x for x in timeslots if x.event_type.description != 'Volunteer'
        ]

        schedule = []
        timeslot_dict = {}
        for sec in classList:
            #   TODO: Fix this bit (it was broken, and may need additional queries
            #   or a parameter added to ClassRegModuleInfo).
            show_changeslot = False

            #   Get the verbs all the time in order for the schedule to show
            #   the student's detailed enrollment status.  (Performance hit, I know.)
            #   - Michael P, 6/23/2009
            #   if scrmi.use_priority:
            sec.verbs = sec.getRegVerbs(user, allowed_verbs=verbs)

            for mt in sec.get_meeting_times():
                section_dict = {'section': sec, 'changeable': show_changeslot}
                if mt.id in timeslot_dict:
                    timeslot_dict[mt.id].append(section_dict)
                else:
                    timeslot_dict[mt.id] = [section_dict]

        user_priority = user.getRegistrationPriorities(
            self.program, [t.id for t in timeslots])
        for i in range(len(timeslots)):
            timeslot = timeslots[i]
            daybreak = False
            if prevTimeSlot != None:
                if not Event.contiguous(prevTimeSlot, timeslot):
                    blockCount += 1
                    daybreak = True

            if timeslot.id in timeslot_dict:
                cls_list = timeslot_dict[timeslot.id]
                schedule.append(
                    (timeslot, cls_list, blockCount + 1, user_priority[i]))
            else:
                schedule.append(
                    (timeslot, [], blockCount + 1, user_priority[i]))

            prevTimeSlot = timeslot

        context['num_classes'] = len(classList)
        context['timeslots'] = schedule
        context['use_priority'] = scrmi.use_priority
        context['allow_removal'] = self.deadline_met('/Removal')

        return context
Example #15
0
    def studentreg2phase(self, request, tl, one, two, module, extra, prog):
        """
        Serves the two-phase student reg page. This page includes instructions
        for registration, and links to the phase1/phase2 sub-pages.
        """

        context = {}
        timeslot_dict = {}
        # Populate the timeslot dictionary with the priority to class title
        # mappings for each timeslot.
        priority_regs = StudentRegistration.valid_objects().filter(
            user=request.user, relationship__name__startswith='Priority')
        priority_regs = priority_regs.select_related('relationship', 'section',
                                                     'section__parent_class')
        for student_reg in priority_regs:
            rel = student_reg.relationship
            title = student_reg.section.parent_class.title
            sec = student_reg.section
            times = sec.meeting_times.all().order_by('start')
            if times.count() == 0:
                continue
            timeslot = times[0].id
            if not timeslot in timeslot_dict:
                timeslot_dict[timeslot] = {rel: title}
            else:
                timeslot_dict[timeslot][rel] = title

        star_counts = {}
        interests = StudentSubjectInterest.valid_objects().filter(
            user=request.user, subject__parent_program=prog)
        interests = interests.select_related('subject').prefetch_related(
            'subject__sections__meeting_times')
        for interest in interests:
            cls = interest.subject
            for sec in cls.sections.all():
                times = sec.meeting_times.all()
                if len(times) == 0:
                    continue
                timeslot = min(times, key=lambda t: t.start).id
                if not timeslot in star_counts:
                    star_counts[timeslot] = 1
                else:
                    star_counts[timeslot] += 1

        # Iterate through timeslots and create a list of tuples of information
        prevTimeSlot = None
        blockCount = 0
        schedule = []
        timeslots = prog.getTimeSlots(types=['Class Time Block', 'Compulsory'])

        context['num_priority'] = prog.priorityLimit()
        context['num_star'] = Tag.getProgramTag("num_stars",
                                                program=prog,
                                                default=10)

        for i in range(len(timeslots)):
            timeslot = timeslots[i]
            if prevTimeSlot != None:
                if not Event.contiguous(prevTimeSlot, timeslot):
                    blockCount += 1

            if timeslot.id in timeslot_dict:
                priority_dict = timeslot_dict[timeslot.id]
                # (relationship, class_title) -> relationship.name
                priority_list = sorted(priority_dict.items(),
                                       key=lambda item: item[0].name)
            else:
                priority_list = []
            temp_list = []
            for i in range(0, context['num_priority']):
                if i < len(priority_list):
                    temp_list.append(
                        ("Priority " + str(i + 1), priority_list[i][1]))
                else:
                    temp_list.append(("Priority " + str(i + 1), ""))
            priority_list = temp_list
            star_count = 0
            if timeslot.id in star_counts:
                star_count = star_counts[timeslot.id]
            schedule.append(
                (timeslot, priority_list, blockCount + 1, star_count,
                 float(star_count) / context['num_star'] * 100))

            prevTimeSlot = timeslot

        context['timeslots'] = schedule

        return render_to_response(self.baseDir() + 'studentregtwophase.html',
                                  request, context)
Example #16
0
    def resources(self, request, tl, one, two, module, extra, prog):
        context = {}

        #   Process commands.  I know the code is mostly copied between the three options, and
        #   I will try to condense it intelligently when  I get the chance.
        if extra == 'timeslot':
            if request.GET.has_key('op') and request.GET['op'] == 'edit':
                #   pre-fill form
                current_slot = Event.objects.get(id=request.GET['id'])
                context['timeslot_form'] = TimeslotForm()
                context['timeslot_form'].load_timeslot(current_slot)

            if request.GET.has_key('op') and request.GET['op'] == 'delete':
                #   show delete confirmation page
                context['prog'] = self.program
                context['timeslot'] = Event.objects.get(id=request.GET['id'])
                return render_to_response(
                    self.baseDir() + 'timeslot_delete.html', request,
                    (prog, tl), context)

            if request.method == 'POST':
                data = request.POST

                if data['command'] == 'reallyremove':
                    #   delete timeslot
                    ts = Event.objects.get(id=data['id'])
                    ts.delete()

                elif data['command'] == 'addedit':
                    #   add/edit timeslot
                    form = TimeslotForm(data)
                    if form.is_valid():
                        if form.cleaned_data['id'] is not None:
                            new_timeslot = Event.objects.get(
                                id=form.cleaned_data['id'])
                        else:
                            new_timeslot = Event()

                        form.save_timeslot(self.program, new_timeslot)
                    else:
                        context['timeslot_form'] = form

        elif extra == 'restype':
            if request.GET.has_key('op') and request.GET['op'] == 'edit':
                #   pre-fill form
                current_slot = ResourceType.objects.get(id=request.GET['id'])
                context['restype_form'] = ResourceTypeForm()
                context['restype_form'].load_restype(current_slot)

            if request.GET.has_key('op') and request.GET['op'] == 'delete':
                #   show delete confirmation page
                context['prog'] = self.program
                context['restype'] = ResourceType.objects.get(
                    id=request.GET['id'])
                return render_to_response(
                    self.baseDir() + 'restype_delete.html', request,
                    (prog, tl), context)

            if request.method == 'POST':
                data = request.POST

                if data['command'] == 'reallyremove':
                    #   delete restype
                    ts = ResourceType.objects.get(id=data['id'])
                    ts.delete()

                elif data['command'] == 'addedit':
                    #   add/edit restype
                    form = ResourceTypeForm(data)

                    if form.is_valid():
                        if form.cleaned_data['id'] is not None:
                            new_restype = ResourceType.objects.get(
                                id=form.cleaned_data['id'])
                        else:
                            new_restype = ResourceType()

                        form.save_restype(self.program, new_restype)
                    else:
                        context['restype_form'] = form

        elif extra == 'classroom':
            if request.GET.has_key('op') and request.GET['op'] == 'edit':
                #   pre-fill form
                current_room = Resource.objects.get(id=request.GET['id'])
                context['classroom_form'] = ClassroomForm(self.program)
                context['classroom_form'].load_classroom(
                    self.program, current_room)

            if request.GET.has_key('op') and request.GET['op'] == 'delete':
                #   show delete confirmation page
                context['prog'] = self.program
                context['classroom'] = Resource.objects.get(
                    id=request.GET['id'])
                resources = self.program.getClassrooms().filter(
                    name=context['classroom'].name)
                context['timeslots'] = [r.event for r in resources]
                sections = ClassSection.objects.filter(
                    resourceassignment__resource__id__in=resources.values_list(
                        'id', flat=True)).distinct()

                context['sections'] = sections
                return render_to_response(
                    self.baseDir() + 'classroom_delete.html', request,
                    (prog, tl), context)

            if request.method == 'POST':
                data = request.POST

                if data['command'] == 'reallyremove':
                    #   delete classroom and associated resources
                    target_resource = Resource.objects.get(id=data['id'])
                    rooms = prog.getClassrooms().filter(
                        name=target_resource.name)
                    for room in rooms:
                        room.associated_resources().delete()
                    rooms.delete()

                elif data['command'] == 'addedit':
                    #   add/edit restype
                    form = ClassroomForm(self.program, data)

                    if form.is_valid():
                        form.save_classroom(self.program)
                    else:
                        context['classroom_form'] = form

        elif extra == 'classroom_import':
            import_mode = 'preview'
            if 'import_confirm' in request.POST and request.POST[
                    'import_confirm'] == 'yes':
                import_mode = 'save'

            import_form = ClassroomImportForm(request.POST)
            if not import_form.is_valid():
                context['import_form'] = import_form
            else:
                #   Attempt to match timeslots for the programs
                past_program = import_form.cleaned_data['program']
                ts_old = past_program.getTimeSlots().filter(
                    event_type__description__icontains='class').order_by(
                        'start')
                ts_new = self.program.getTimeSlots().filter(
                    event_type__description__icontains='class').order_by(
                        'start')
                ts_map = {}
                for i in range(min(len(ts_old), len(ts_new))):
                    ts_map[ts_old[i].id] = ts_new[i]

                resource_list = []
                #   Iterate over the resources in the previous program
                for res in past_program.getClassrooms():
                    #   If we know what timeslot to put it in, make a copy
                    if res.event.id in ts_map:
                        new_res = Resource()
                        new_res.name = res.name
                        new_res.res_type = res.res_type
                        new_res.num_students = res.num_students
                        new_res.is_unique = res.is_unique
                        new_res.user = res.user
                        new_res.event = ts_map[res.event.id]
                        #   Check to avoid duplicating rooms (so the process is idempotent)
                        if import_mode == 'save' and not Resource.objects.filter(
                                name=new_res.name,
                                event=new_res.event).exists():
                            new_res.save()
                        #   Note: furnishings are messed up, so don't bother copying those yet.
                        resource_list.append(new_res)

                #   Render a preview page showing the resources for the previous program if desired
                context['past_program'] = past_program
                if import_mode == 'preview':
                    context['prog'] = self.program
                    result = self.program.collapsed_dict(resource_list)
                    key_list = result.keys()
                    key_list.sort()
                    context['new_rooms'] = [result[key] for key in key_list]
                    return render_to_response(
                        self.baseDir() + 'classroom_import.html', request,
                        (prog, tl), context)
                else:
                    extra = 'classroom'

        elif extra == 'equipment':
            if request.GET.has_key('op') and request.GET['op'] == 'edit':
                #   pre-fill form
                equip = Resource.objects.get(id=request.GET['id'])
                context['equipment_form'] = EquipmentForm(self.program)
                context['equipment_form'].load_equipment(self.program, equip)

            if request.GET.has_key('op') and request.GET['op'] == 'delete':
                #   show delete confirmation page
                context['prog'] = self.program
                context['equipment'] = Resource.objects.get(
                    id=request.GET['id'])
                return render_to_response(
                    self.baseDir() + 'equipment_delete.html', request,
                    (prog, tl), context)

            if request.method == 'POST':
                data = request.POST

                if data['command'] == 'reallyremove':
                    #   delete this resource for all time blocks within the program
                    rl = Resource.objects.get(
                        id=data['id']).identical_resources().filter(
                            event__anchor=self.program_anchor_cached())
                    for r in rl:
                        r.delete()

                elif data['command'] == 'addedit':
                    #   add/edit restype
                    form = EquipmentForm(self.program, data)

                    if form.is_valid():
                        form.save_equipment(self.program)
                    else:
                        context['equipment_form'] = form

    #   Group contiguous blocks of time for the program
        time_options = self.program.getTimeSlots(exclude_types=[])
        time_groups = Event.group_contiguous(list(time_options))

        #   Retrieve remaining context information
        context['timeslots'] = [{'selections': group} for group in time_groups]

        if 'timeslot_form' not in context:
            context['timeslot_form'] = TimeslotForm()

        context['resource_types'] = self.program.getResourceTypes().exclude(
            priority_default=0).order_by('priority_default')
        for c in context['resource_types']:
            if c.program is None:
                c.is_global = True

        if 'restype_form' not in context:
            context['restype_form'] = ResourceTypeForm()

        if 'classroom_form' not in context:
            context['classroom_form'] = ClassroomForm(self.program)

        if 'equipment_form' not in context:
            context['equipment_form'] = EquipmentForm(self.program)

        if 'import_form' not in context:
            context['import_form'] = ClassroomImportForm()

        context['open_section'] = extra
        context['prog'] = self.program
        context['module'] = self

        #   Display default form
        return render_to_response(self.baseDir() + 'resource_main.html',
                                  request, (prog, tl), context)
Example #17
0
    def resources(self, request, tl, one, two, module, extra, prog):
        """ Main view for the resource module.
            Besides displaying resource information, the 'extra' slug at the
            end of the URL selects which aspect of resources to perform
            more detailed operations on.
        """

        #   First, run the handler specified at the end of the URL.
        #   (The handler specifies which type of model we are working with.)
        handlers = {
            'timeslot': self.resources_timeslot,
            'restype': self.resources_restype,
            'classroom': self.resources_classroom,
            'timeslot_import': self.resources_timeslot_import,
            'classroom_import': self.resources_classroom_import,
            'equipment': self.resources_equipment,
        }
        if extra in handlers:
            (response, context) = handlers[extra](request, tl, one, two,
                                                  module, extra, prog)
        else:
            response = None
            context = {}

        #   Display the immediate response (e.g. a confirmation page) if the handler provided one
        if response:
            return response

        #   Group contiguous blocks of time for the program
        time_options = self.program.getTimeSlots(exclude_types=[])
        time_groups = Event.group_contiguous(list(time_options))

        #   Retrieve remaining context information
        context['timeslots'] = [{'selections': group} for group in time_groups]

        if 'timeslot_form' not in context:
            context['timeslot_form'] = TimeslotForm()

        context['resource_types'] = self.program.getResourceTypes()
        for c in context['resource_types']:
            if c.program is None:
                c.is_global = True

        if 'restype_form' not in context:
            context['restype_form'] = ResourceTypeForm()

        if 'classroom_form' not in context:
            context['classroom_form'] = ClassroomForm(self.program)

        if 'equipment_form' not in context:
            context['equipment_form'] = EquipmentForm(self.program)

        if 'import_form' not in context:
            context['import_form'] = ClassroomImportForm()

        if 'import_timeslot_form' not in context:
            context['import_timeslot_form'] = TimeslotImportForm()

        context['open_section'] = extra
        context['prog'] = self.program
        context['module'] = self

        #   Display default form
        return render_to_response(self.baseDir() + 'resource_main.html',
                                  request, context)
Example #18
0
def group_events(event_list):
    result = Event.group_contiguous(event_list)
    return [Event.collapse(sublist) for sublist in result]
Example #19
0
 def available_times_html(self, anchor=None):
     return '<br /> '.join(
         [unicode(e) for e in Event.collapse(self.available_times(anchor))])
    def prepare(self, context={}):
        from esp.program.controllers.studentclassregmodule import RegistrationTypeController as RTC
        verbs = RTC.getVisibleRegistrationTypeNames(prog=self.program)
        regProf = RegistrationProfile.getLastForProgram(get_current_request().user, self.program)
        timeslots = self.program.getTimeSlots(types=['Class Time Block', 'Compulsory'])
        classList = ClassSection.prefetch_catalog_data(regProf.preregistered_classes(verbs=verbs))

        prevTimeSlot = None
        blockCount = 0

        user = get_current_request().user
        is_onsite = user.isOnsite(self.program)
        scrmi = self.program.studentclassregmoduleinfo

        #   Filter out volunteer timeslots
        timeslots = [x for x in timeslots if x.event_type.description != 'Volunteer']

        schedule = []
        timeslot_dict = {}
        for sec in classList:
            #   Get the verbs all the time in order for the schedule to show
            #   the student's detailed enrollment status.  (Performance hit, I know.)
            #   - Michael P, 6/23/2009
            #   if scrmi.use_priority:
            sec.verbs = sec.getRegVerbs(user, allowed_verbs=verbs)
            sec.verb_names = [v.name for v in sec.verbs]
            sec.is_enrolled = True if "Enrolled" in sec.verb_names else False

            # While iterating through the meeting times for a section,
            # we use this variable to keep track of the first timeslot.
            # In the section_dict appended to timeslot_dict,
            # we save whether or not this is the first timeslot for this
            # section. If it isn't, the student schedule will indicate
            # this, and will not display the option to remove the
            # section. This is to prevent students from removing what
            # they have mistaken to be duplicated classes from their
            # schedules.
            first_meeting_time = True

            for mt in sec.get_meeting_times().order_by('start'):
                section_dict = {'section': sec, 'first_meeting_time': first_meeting_time}
                first_meeting_time = False
                if mt.id in timeslot_dict:
                    timeslot_dict[mt.id].append(section_dict)
                else:
                    timeslot_dict[mt.id] = [section_dict]

        for i in range(len(timeslots)):
            timeslot = timeslots[i]
            daybreak = False
            if prevTimeSlot != None:
                if not Event.contiguous(prevTimeSlot, timeslot):
                    blockCount += 1
                    daybreak = True

            if timeslot.id in timeslot_dict:
                cls_list = timeslot_dict[timeslot.id]
                doesnt_have_enrollment = not any(sec['section'].is_enrolled
                                                 for sec in cls_list)
                schedule.append((timeslot, cls_list, blockCount + 1,
                                 doesnt_have_enrollment))
            else:
                schedule.append((timeslot, [], blockCount + 1, False))

            prevTimeSlot = timeslot

        context['num_classes'] = len(classList)
        context['timeslots'] = schedule
        context['use_priority'] = scrmi.use_priority
        context['allow_removal'] = self.deadline_met('/Removal')

        return context