Beispiel #1
0
    def get_queryset(self):
        if self.request.user.is_superuser:
            return Measure.objects.all().order_by('-vote_end')

        this_sem = Semester.get_this_semester()
        try:
            room = UserRoom.objects.filter(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__official_dorm=True,
            )[0].room
        except IndexError:
            # If they don't have a room, they're probably not eligible to vote.
            raise PermissionDenied()

        if self.request.user.highest_ashmc_role >= ASHMCRole.objects.get(title="Vice-President"):
            # VP's and higher can see all measures, except those that are dorm-specific
            # because ASHMC has no business within a dorm.
            return Measure.objects.filter(
                Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
                Q(vote_end__lte=datetime.datetime.now(pytz.utc)) | Q(is_open=False),
            ).order_by('-vote_end')

        return Measure.objects.filter(
            Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
            Q(restrictions__gradyears=self.request.user.student.class_of) | Q(restrictions__gradyears=None),
            # Only show measures which have already closed for voting
            vote_end__lte=datetime.datetime.now(pytz.utc),
        ).exclude(
            banned_accounts__id__exact=self.request.user.id,
        ).order_by('-vote_end')
Beispiel #2
0
 def _has_roles(self, user, titles):
     sem = Semester.get_this_semester()
     return ASHMCAppointment.objects.filter(
         reduce(lambda x, y: x | y, [Q(role__title=t) for t in titles]),
         user=user,
         semesters__id=sem.id,
     ).count() > 0
Beispiel #3
0
    def get_queryset(self):
        # Put the next-to-expire measures up front.

        this_sem = Semester.get_this_semester()

        if self.request.user.is_superuser:
            return Measure.objects.exclude(vote_end__lte=datetime.datetime.now(pytz.utc)).order_by('vote_end')

        try:
            room = UserRoom.objects.get(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__official_dorm=True,
            ).room

        except UserRoom.DoesNotExist:
            # So they don't have an official dorm room
            # that means they should be abroad.

            room = UserRoom.objects.get(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__code="ABR",
            ).room

        except Exception, e:
            # If they don't have a room, they're probably not eligible to vote.
            #raise PermissionDenied()
            logger.debug("%s %s", e, e.message)
            logger.info("blocked access to {}".format(self.request.user))
            raise PermissionDenied
Beispiel #4
0
    def get_queryset(self):
        # Put the next-to-expire measures up front.

        this_sem = Semester.get_this_semester()

        if self.request.user.is_superuser:
            return Measure.objects.exclude(vote_end__lte=datetime.datetime.now(
                pytz.utc)).order_by('vote_end')

        try:
            room = UserRoom.objects.get(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__official_dorm=True,
            ).room

        except UserRoom.DoesNotExist:
            # So they don't have an official dorm room
            # that means they should be abroad.

            room = UserRoom.objects.get(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__code="ABR",
            ).room

        except Exception, e:
            # If they don't have a room, they're probably not eligible to vote.
            #raise PermissionDenied()
            logger.debug("%s %s", e, e.message)
            logger.info("blocked access to {}".format(self.request.user))
            raise PermissionDenied
Beispiel #5
0
 def _has_roles(self, user, titles):
     sem = Semester.get_this_semester()
     return ASHMCAppointment.objects.filter(
         reduce(lambda x, y: x | y, [Q(role__title=t) for t in titles]),
         user=user,
         semesters__id=sem.id,
     ).count() > 0
Beispiel #6
0
    def get_queryset(self):
        # Put the next-to-expire measures up front.

        this_sem = Semester.get_this_semester()

        try:
            room = UserRoom.objects.filter(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__official_dorm=True,
            )[0].room
        except IndexError:
            # If they don't have a room, they're probably not eligible to vote.
            #raise PermissionDenied()
            logger.info("blocked access to {}".format(self.request.user))
            # Until we have roster data importing, this is bad
            pass

        return Measure.objects.exclude(
            # Immediately filter out expired measures. Otherwise shit gets weird.
            vote_end__lte=datetime.datetime.now(pytz.utc),
        ).filter(
            # Hide measures that the user has already voted in.
            ~Q(id__in=Vote.objects.filter(account=self.request.user).values_list('measure__id', flat=True)),
            Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
            Q(restrictions__gradyears=self.request.user.student.class_of) | Q(restrictions__gradyears=None),
            is_open=True,
            # Only show measures which have already opened for voting
            vote_start__lte=datetime.datetime.now(pytz.utc),
        ).exclude(
            banned_accounts__id__exact=self.request.user.id,
        ).order_by('vote_end')
Beispiel #7
0
    def get_queryset(self):
        if self.request.user.is_superuser:
            return Measure.objects.all().order_by('-vote_end')

        this_sem = Semester.get_this_semester()
        try:
            room = UserRoom.objects.filter(
                user=self.request.user,
                semesters__id=this_sem.id,
                room__dorm__official_dorm=True,
            )[0].room
        except IndexError:
            # If they don't have a room, they're probably not eligible to vote.
            raise PermissionDenied()

        if self.request.user.highest_ashmc_role >= ASHMCRole.objects.get(
                title="Vice-President"):
            # VP's and higher can see all measures, except those that are dorm-specific
            # because ASHMC has no business within a dorm.
            return Measure.objects.filter(
                Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
                Q(vote_end__lte=datetime.datetime.now(pytz.utc))
                | Q(is_open=False),
            ).order_by('-vote_end')

        return Measure.objects.filter(
            Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
            Q(restrictions__gradyears=self.request.user.student.class_of)
            | Q(restrictions__gradyears=None),
            # Only show measures which have already closed for voting
            vote_end__lte=datetime.datetime.now(pytz.utc),
        ).exclude(banned_accounts__id__exact=self.request.user.id, ).order_by(
            '-vote_end')
Beispiel #8
0
 def get_active_sections(self):
     """
     Creates a queryset of 'acceptable' :model:`courses.Section` associated
     with this course
     """
     qs = self.section_set.all()
     qs = qs.annotate(num_meetings=models.Count('meeting'))\
            .filter(num_meetings__gte=1)
     qs = qs.exclude(meeting__needs_attention=True)
     qs = qs.filter(semester=Semester.get_this_semester().next())
     return qs.order_by('number')
Beispiel #9
0
 def get_active_sections(self):
     """
     Creates a queryset of 'acceptable' :model:`courses.Section` associated
     with this course
     """
     qs = self.section_set.all()
     qs = qs.annotate(num_meetings=models.Count('meeting'))\
            .filter(num_meetings__gte=1)
     qs = qs.exclude(meeting__needs_attention=True)
     qs = qs.filter(semester=Semester.get_this_semester().next())
     return qs.order_by('number')
Beispiel #10
0
 def get_current_room(cls, user):
     from ASHMC.main.models import Semester
     sem = Semester.get_this_semester()
     try:
         return cls.objects.get(user=user, semesters__id=sem.id)
     except UserRoom.MultipleObjectsReturned:
         # The only way multiple objects should be returned is if one room
         # is the OFF Symbolic Room. So, they have an off-campus room:
         return cls.objects.get(
             user=user,
             semesters__id=sem.id,
             room__dorm__official_dorm=False,
         )
     except models.ObjectDoesNotExist:
         return None
Beispiel #11
0
 def get_current_room(cls, user):
     from ASHMC.main.models import Semester
     sem = Semester.get_this_semester()
     try:
         return cls.objects.get(user=user, semesters__id=sem.id)
     except UserRoom.MultipleObjectsReturned:
         # The only way multiple objects should be returned is if one room
         # is the OFF Symbolic Room. So, they have an off-campus room:
         return cls.objects.get(
             user=user,
             semesters__id=sem.id,
             room__dorm__official_dorm=False,
         )
     except models.ObjectDoesNotExist:
         return None
Beispiel #12
0
    def post(self, *args, **kwargs):
        tsuite = TransientSuite.objects.get(pk=kwargs['pk'])

        if kwargs['action'] == "leave":
            sem = Semester.get_this_semester()
            print sem
            tsm = TransientSuiteMembership.objects.get(
                user=self.request.user,
                tsuite=tsuite,
            )

            print tsm

            tsm.semesters.remove(sem)

        else:
            raise PermissionDenied()

        return redirect("main_home")
Beispiel #13
0
    def post(self, *args, **kwargs):
        tsuite = TransientSuite.objects.get(pk=kwargs['pk'])

        if kwargs['action'] == "leave":
            sem = Semester.get_this_semester()
            #print sem
            tsm = TransientSuiteMembership.objects.get(
                user=self.request.user,
                tsuite=tsuite,
            )

            #print tsm

            tsm.semesters.remove(sem)

        else:
            raise PermissionDenied()

        return redirect("main_home")
Beispiel #14
0
    def get_queryset(self):
        this_sem = Semester.get_this_semester()

        try:
            room = UserRoom.objects.filter(
                user=self.request.user,
                semesters__id=this_sem.id,
            )[0].room
        except IndexError:
            # If they don't have a room, they're probably not eligible to vote.
            raise PermissionDenied()

        return Measure.objects.filter(
            Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
            Q(restrictions__gradyears=self.request.user.student.class_of) | Q(restrictions__gradyears=None),
            # Only show measures which have already closed for voting
            vote_end__lte=datetime.datetime.now(pytz.utc),
        ).exclude(
            banned_accounts__id__exact=self.request.user.id,
        ).order_by('-vote_end')
    def handle(self, *args, **options):
        if len(args) > 0:
            measure_ids = args
        else:
            measure_ids = None

        if measure_ids:
            measures = Measure.objects.filter(id__in=measure_ids, )
        else:
            measures = Measure.objects.exclude(
                vote_end__lte=datetime.today(), ).filter(
                    is_open=True,
                    vote_start__lte=datetime.today() - timedelta(days=5),
                )

        for user in User.objects.filter(is_active=True, is_superuser=False):
            this_sem = Semester.get_this_semester()
            try:
                room = UserRoom.objects.get(
                    user=user,
                    semesters__id=this_sem.id,
                    room__dorm__official_dorm=True,
                ).room

            except UserRoom.DoesNotExist:
                # So they don't have an official dorm room
                # that means they should be abroad.

                try:
                    room = UserRoom.objects.get(
                        user=user,
                        semesters__id=this_sem.id,
                        room__dorm__code="ABR",
                    ).room
                except UserRoom.DoesNotExist:
                    continue

            # only send emails to people who haven't voted in
            # this measure
            delinquent_measures = measures.exclude(
                Q(id__in=Vote.objects.filter(account=user).values_list(
                    'measure__id', flat=True)), ).filter(
                        Q(restrictions__dorms=room.dorm)
                        | Q(restrictions__dorms=None),
                        Q(restrictions__gradyears=user.student.class_of)
                        | Q(restrictions__gradyears=None),
                    ).exclude(banned_accounts__id__exact=user.id, )

            if not delinquent_measures.exists():
                continue

            htmly = get_template("vote/reminder_email.html")
            plaintext = get_template("vote/reminder_email.txt")
            d = Context({'user': user, 'measures': delinquent_measures})
            subject = "A friendly ASHMC reminder"
            from_email = "*****@*****.**"
            to_email = user.email
            msg = EmailMultiAlternatives(
                subject,
                plaintext.render(d),
                from_email,
                [to_email],
            )
            msg.attach_alternative(htmly.render(d), "text/html")
            if not options.get('dry_run'):
                msg.send()

            print "sent reminder email to", user.id, "about", [
                m.id for m in delinquent_measures
            ]
Beispiel #16
0
 def set_writingintense(self, sem=None):
     if sem == None:
         sem = Semester.get_this_semester().next()
     self.section_set.filter(semester=sem).update(is_mudd_writingintense=True)
    def handle(self, *args, **options):
        if len(args) > 0:
            measure_ids = args
        else:
            measure_ids = None

        if measure_ids:
            measures = Measure.objects.filter(
                id__in=measure_ids,
            )
        else:
            measures = Measure.objects.exclude(
                vote_end__lte=datetime.today(),
            ).filter(
                is_open=True,
                vote_start__lte=datetime.today() - timedelta(days=5),
            )

        for user in User.objects.filter(is_active=True, is_superuser=False):
            this_sem = Semester.get_this_semester()
            try:
                room = UserRoom.objects.get(
                    user=user,
                    semesters__id=this_sem.id,
                    room__dorm__official_dorm=True,
                ).room

            except UserRoom.DoesNotExist:
                # So they don't have an official dorm room
                # that means they should be abroad.

                try:
                    room = UserRoom.objects.get(
                        user=user,
                        semesters__id=this_sem.id,
                        room__dorm__code="ABR",
                    ).room
                except UserRoom.DoesNotExist:
                    continue

            # only send emails to people who haven't voted in
            # this measure
            try:
                delinquent_measures = measures.exclude(
                    Q(id__in=Vote.objects.filter(account=user).values_list('measure__id', flat=True)),
                    ).filter(
                    Q(restrictions__dorms=room.dorm) | Q(restrictions__dorms=None),
                    Q(restrictions__gradyears=user.student.class_of) | Q(restrictions__gradyears=None),
                    ).exclude(
                        banned_accounts__id__exact=user.id,
                        )
            except:
                print user.username + " caused an exception:", sys.exc_info()[0]
                print "(S)He probably doesn't have a student object somehow"
                continue

            if not delinquent_measures.exists():
                continue

            htmly = get_template("vote/reminder_email.html")
            plaintext = get_template("vote/reminder_email.txt")
            d = Context({'user': user, 'measures': delinquent_measures})
            subject = "A friendly ASHMC reminder"
            from_email = "*****@*****.**"
            to_email = user.email
            msg = EmailMultiAlternatives(
                subject,
                plaintext.render(d),
                from_email,
                [to_email],
            )
            msg.attach_alternative(htmly.render(d), "text/html")
            if not options.get('dry_run'):
                msg.send()

            print "sent reminder email to", user.id, "about", [m.id for m in delinquent_measures]
Beispiel #18
0
 def get_current_room(cls, user):
     from ASHMC.main.models import Semester
     sem = Semester.get_this_semester()
     return cls.objects.get(user=user, semesters__id=sem.id)
Beispiel #19
0
def create_user_related_things(*args, **kwargs):
    if 'user' not in kwargs or 'ldap_user' not in kwargs:
        return

    new_user = kwargs['user']
    print new_user, new_user.email
    # don't repopulate if we've already done the dance.
    if Student.objects.filter(user=new_user).count():
        logger.debug("skipping student {}".format(new_user))
        return

    logger.info("new student {}".format(new_user))

    try:
        this_sem = Semester.get_this_semester()
        workbook = xlrd.open_workbook(settings.ROSTER_DIRECTORY + "{}.xlsx".format(
            this_sem.verbose_unicode()
        ))
    except IOError:
        logger.error("could not open workbook {}".format(this_sem.verbose_unicode()))
        return

    s = workbook.sheets()[0]

    # On what row does the actual information start?
    ROSTER_ROW_START = settings.ROSTER_ROW_START

    # TODO: make this more programmatic?
    FIELD_ORDERING = settings.ROSTER_FIELD_ORDERING

    senior = GradYear.senior_class(
        sem=this_sem,
    ).year
    if settings.DEBUG:
        print "\tsenior year:", senior
    CLASS_TO_GRADYEAR = {
        'FE': senior + 3,
        'FF': senior + 3,
        'FR': senior + 3,
        'SO': senior + 2,
        'JR': senior + 1,
        'SR': senior,
    }
    try:
        for r in xrange(ROSTER_ROW_START, s.nrows):
            row = s.row(r)

            if row[FIELD_ORDERING.index('Email')].value != new_user.email:
                logger.debug("\tSkipping row", r, row[FIELD_ORDERING.index('Email')].value)
                continue

            logger.debug("creating user-related things...")
            year = CLASS_TO_GRADYEAR[row[FIELD_ORDERING.index('Class')].value]

            gradyear, _ = GradYear.objects.get_or_create(
                year=year,
            )

            hmc = Campus.objects.get(code='HM')

            studentid = None
            new_student, _ = Student.objects.get_or_create(
                user=new_user,
                class_of=gradyear,
                at=hmc,
                studentid=studentid,
                phonenumber=row[FIELD_ORDERING.index('Phone')].value,
                #birthdate=datetime.datetime.strptime(row[FIELD_ORDERING.index('Birthdate')].value, '%b %d, %Y').date(),
            )

            dormcode = row[FIELD_ORDERING.index('Dorm')].value.split(' ')

            if dormcode[0] != '':
                # Roster has CGUA, whereas DB has CGA.
                if dormcode[0] == "CGU":
                    dormcode = ' '.join(dormcode)
                else:
                    dormcode = dormcode[0]

                try:
                    dorm = Dorm.objects.get(code__iexact=dormcode)
                except ObjectDoesNotExist:
                    try:
                        dorm = Dorm.objects.get(name__istartswith=dormcode)
                    except (ObjectDoesNotExist, MultipleObjectsReturned):
                        logger.error(
                            "ldap population failed for {} (on failed dorm lookup {})".format(new_user, dormcode)
                        )
                        return

                room, _ = DormRoom.objects.get_or_create(
                    dorm=dorm,
                    number=row[FIELD_ORDERING.index("Room")].value,
                )

                if dorm.code in Dorm.all_objects.filter(official_dorm=False).values_list('code', flat=True)\
                  and dorm.code != "ABR":
                    # If they're off-campus, make sure they're 'symbollically'
                    # a part of the Offcampus dorm.
                    symoff, _ = DormRoom.objects.get_or_create(
                        dorm__code="OFF",
                        number="Symbolic Room",
                    )

                    # Symroom is going to be full of people.
                    symroomur, _ = UserRoom.objects.get_or_create(
                        user=new_user,
                        room=symoff,
                    )
                    symroomur.semesters.add(this_sem)

                ur, _ = UserRoom.objects.get_or_create(
                    user=new_user,
                    room=room,
                )
                ur.semesters.add(this_sem)

            return
    except Exception, e:
        # Don't interrupt core service, no matter what.
        logger.error("caught unhandled exception {}: {}".format(e, e.message))
        return
Beispiel #20
0
 def set_writingintense(self, sem=None):
     if sem == None:
         sem = Semester.get_this_semester().next()
     self.section_set.filter(semester=sem).update(
         is_mudd_writingintense=True)