Example #1
0
 def form_valid(self, form):
     req = form.save(commit=False)
     req.trainee = trainee_from_user(self.request.user)
     req.save()
     message = "Created new web request."
     messages.add_message(self.request, messages.SUCCESS, message)
     return super(WebAccessCreate, self).form_valid(form)
Example #2
0
 def get_context_data(self, **kwargs):
     context = super(QuestionList, self).get_context_data(**kwargs)
     trainee = trainee_from_user(self.request.user)
     if is_TA(self.request.user) or (trainee.firstname == 'Tobi'
                                     and trainee.lastname == 'Abosede') or (
                                         trainee.firstname == 'Sofia'
                                         and trainee.lastname == 'Hunter'):
         faqs = HouseInspectionFaq.objects.none()
         for status in ['U', 'A', 'An', 'D']:
             faqs = chain(
                 faqs,
                 HouseInspectionFaq.objects.filter(status=status).filter(
                     date_assigned__gte=Term.current_term().get_date(0, 0)).
                 order_by('date_assigned').order_by('status'))
         context['faqs'] = faqs
     if not is_TA(self.request.user) and (
             trainee.firstname != 'Tobi' or trainee.lastname != 'Abosede'
     ) and (trainee.firstname != 'Sofia' or trainee.lastname != 'Hunter'):
         faqs = HouseInspectionFaq.objects.none()
         for status in ['A']:
             faqs = chain(
                 faqs,
                 HouseInspectionFaq.objects.filter(status=status).filter(
                     date_assigned__gte=Term.current_term().get_date(
                         0, 0)).order_by('date_assigned'))
         context['faqs'] = faqs
     return context
Example #3
0
 def post(self, request, *args, **kwargs):
     service_roll_forms = self.get_service_roll_forms(self.request.POST)
     if all(f.is_valid() for f in service_roll_forms):
         service_attendance = self.get_object()
         ServiceRoll.objects.filter(
             service_attendance=service_attendance).delete()
         for srf in service_roll_forms:
             sr = srf.save(commit=False)
             sr.service_attendance = service_attendance
             sr.save()
         return redirect(
             reverse('services:designated_service_hours',
                     kwargs={
                         'service_id': self.kwargs['service_id'],
                         'week': self.kwargs['week']
                     }))
     else:
         ctx = {
             'form':
             self.form_class(request.POST,
                             worker=trainee_from_user(
                                 self.request.user).worker)
         }
         ctx['button_label'] = 'Submit'
         ctx['page_title'] = 'Designated Service Hours'
         ctx['service_roll_forms'] = service_roll_forms
         return super(ServiceHours, self).render_to_response(ctx)
Example #4
0
    def get_context_data(self, **kwargs):
        if 'house_id' in kwargs.keys():
            house_id = kwargs['house_id']
            house = House.objects.get(pk=house_id)
        elif trainee_from_user(self.request.user):
            house = self.request.user.house
        else:
            house = House.objects.first()

        trainees = Trainee.objects.filter(house=house)
        if not self.request.user.has_group(['attendance_monitors']):
            trainees = trainees.filter(house=house).filter(
                self_attendance=False)

        kwargs['trainees'] = trainees
        kwargs['event_type'] = 'H'
        kwargs['monitor'] = 'HC'
        ctx = super(HouseRollsView, self).get_context_data(**kwargs)
        ctx['title'] = "House Rolls"
        ctx['selected_house_id'] = house.id
        if self.request.user.has_group(
            ['attendance_monitors', 'training_assistant']):
            ctx['houses'] = House.objects.filter(
                used=True).order_by("name").exclude(
                    name__in=['TC', 'MCC', 'COMMUTER']).values("pk", "name")
        return ctx
Example #5
0
  def get_context_data(self, **kwargs):
    if 'team_id' in kwargs.keys():
      team_id = kwargs['team_id']
      team = Team.objects.get(pk=team_id)
    elif trainee_from_user(self.request.user):
      team = self.request.user.team
    else:
      team = Team.objects.first()

    trainees = Trainee.objects.filter(team=team)
    if not self.request.user.has_group(['attendance_monitors']):
      trainees = trainees.filter(self_attendance=False)

    kwargs['trainees'] = trainees
    kwargs['event_type'] = 'T'
    kwargs['monitor'] = 'TM'
    ctx = super(TeamRollsView, self).get_context_data(**kwargs)
    ctx['title'] = "Team Rolls"
    ctx['selected_team_id'] = team.id
    if self.request.user.has_group(['attendance_monitors', 'training_assistant']):
      ctx['teams'] = Team.objects.all().order_by("type", "name").values("pk", "name")

    if not self.request.user.has_group(['attendance_monitors', 'training_assistant']):
      ctx['finalized'] = self.checkfinalize(trainees, kwargs['monitor'], ctx['current_week'])

    return ctx
Example #6
0
    def get_object(self, queryset=None):
        term = Term.current_term()
        worker = trainee_from_user(self.request.user).worker
        self.designated_assignments = worker.assignments.all().filter(
            service__designated=True).exclude(
                service__name__icontains="Breakfast")
        try:
            self.week = self.kwargs['week']
        except KeyError:
            self.week = term.term_week_of_date(datetime.now().date())

        # get service
        try:
            self.service_id = self.kwargs['service_id']
        except KeyError:
            self.service_id = self.designated_assignments[0].service.id

        self.service = Service.objects.get(id=self.service_id)

        # get the existing object or created a new one
        service_attendance = ServiceAttendance.objects.get_or_create(
            worker=worker,
            term=term,
            week=self.week,
            designated_service=self.service)[0]
        return service_attendance
Example #7
0
  def get_form(self, form_class=NewSummaryForm):
    """
    Returns an instance of the form to be used in this view.
    """
    kargs = self.get_form_kwargs()
    kargs['trainee'] = trainee_from_user(self.request.user)

    return form_class(**kargs)
Example #8
0
 def get_queryset(self):
   if 'trainee' in self.request.GET:
     trainee = Trainee.objects.get(pk=self.request.GET.get('trainee'))
   else:
     user = self.request.user
     trainee = trainee_from_user(user)
   events = trainee.events
   return events
Example #9
0
 def get_queryset(self):
   if is_TA(self.request.user):
     qs = WebRequest.objects.filter(status='P') | WebRequest.objects.filter(status='F')
     return qs.order_by('date_assigned')
   else:
     trainee = trainee_from_user(self.request.user)
     qset = WebRequest.objects.filter(trainee=trainee).order_by('status')
   return qset
Example #10
0
def has_designated_service(user):
  if is_trainee(user):
    worker = trainee_from_user(user).worker
    w_designated_services = worker.designated.all()
    if w_designated_services.exists():
      return True

  return None
Example #11
0
 def get_object(self, queryset=None):
     ct = Term.current_term()
     if is_trainee(self.request.user):
         trainee = trainee_from_user(self.request.user)
     else:
         trainee = Trainee.objects.first()
     obj, created = SemiAnnual.objects.get_or_create(trainee=trainee,
                                                     term=ct)
     return obj
Example #12
0
    def get_object(self, queryset=None):
        trainee = trainee_from_user(self.request.user)
        admin, created = InterimIntentionsAdmin.objects.get_or_create(
            term=Term.current_term())
        int_int, created = InterimIntentions.objects.get_or_create(
            trainee=trainee_from_user(self.request.user), admin=admin)

        if created:
            int_int.email = trainee.email
            int_int.cell_phone = trainee.meta.phone
            int_int.home_locality = trainee.locality.city.name
            int_int.home_address = trainee.meta.address.address1
            int_int.home_city = trainee.meta.address.city.name
            int_int.home_state = trainee.meta.address.city.get_state_display()
            int_int.home_zip = trainee.meta.address.zip_code
            int_int.save()

        return int_int
Example #13
0
 def get_initial(self):
   """
   Returns the initial data to use for forms on this view.
   """
   initial = super(ClassnotesCreateView, self).get_initial()
   initial['trainee'] = trainee_from_user(self.request.user)
   # initial['classname'] = classnotes.classname
   # initial['classdate'] = classnotes.classdate
   return initial
Example #14
0
 def get_queryset(self):
     trainee = trainee_from_user(self.request.user)
     if is_TA(self.request.user) or (trainee.firstname == 'Tobi'
                                     and trainee.lastname == 'Abosede') or (
                                         trainee.firstname == 'Sofia'
                                         and trainee.lastname
                                         == 'Hunter'):  # or Tobi or Hunter
         # FAQ.objects.filter(status='')
         qs = HouseInspectionFaq.objects.filter(
             status='U') | HouseInspectionFaq.objects.filter(
                 status='A') | HouseInspectionFaq.objects.filter(
                     status='An')
         return qs.order_by('date_assigned').order_by('status')
     else:
         trainee = trainee_from_user(self.request.user)
         qset = HouseInspectionFaq.objects.filter(trainee=trainee).order_by(
             'status'
         )  #pretty sure this never works b/c trainee is an object while trainee_name is a string
     return qset
Example #15
0
def hc_surveys(user):
  ret = False
  if is_trainee(user):
    tr = trainee_from_user(user)
    if tr.has_group(['HC']) and tr.type != 'C':
      term = Term.current_term()
      admins = HCSurveyAdmin.objects.filter(open_survey=True).filter(term=term)
      if admins.exists():
        ret = True
  return ret
Example #16
0
 def get_context_data(self, **kwargs):
   ctx = super(AttendancePersonal, self).get_context_data(**kwargs)
   listJSONRenderer = JSONRenderer()
   user = self.request.user
   trainee = trainee_from_user(user)
   if not trainee:
     trainee = Trainee.objects.filter(groups__name='attendance_monitors').first()
     ctx['actual_user'] = listJSONRenderer.render(TraineeForAttendanceSerializer(self.request.user).data)
   ctx.update(react_attendance_context(trainee))
   return ctx
Example #17
0
 def dispatch(self, request, *args, **kwargs):
     if request.method == 'GET' and not self.kwargs.get('pk', None):
         term = Term.current_term()
         if is_trainee(request.user):
             trainee = trainee_from_user(request.user)
         else:
             trainee = Trainee.objects.first()
         semi = SemiAnnual.objects.get_or_create(trainee=trainee,
                                                 term=term)[0]
         return redirect(reverse('semi:attendance', kwargs={'pk': semi.pk}))
     return super(AttendanceUpdate, self).dispatch(request, *args, **kwargs)
Example #18
0
def hc_surveys(user):
    ret = False
    if is_trainee(user) and trainee_from_user(user).house.gender not in [
            'C', None
    ]:
        term = Term.current_term()
        admins = HCSurveyAdmin.objects.filter(open_survey=True).filter(
            term=term)
        if admins.exists():
            ret = True
    return ret
def get_announcements(request):
  notifications = []
  if is_trainee(request.user):
    trainee = trainee_from_user(request.user)
    notifications = chain(discipline_announcements(trainee),
                          server_announcements(trainee),
                          bible_reading_announcements(trainee),
                          request_statuses(trainee),
                          attendance_announcements(trainee))
  # sort on severity level of message
  return sorted(notifications, lambda a, b: b[0] - a[0])
Example #20
0
 def get_queryset(self):
     trainee = trainee_from_user(self.request.user)
     files = AudioFile.objects.filter_list(self.week, trainee)
     attendance_record = trainee.attendance_record
     for f in files:
         # replace methods with computed values because trainee can't be passed in template
         f.classnotes = f.classnotes(trainee)
         f.request = f.request(trainee)
         f.has_leaveslip = f.has_leaveslip(trainee, attendance_record)
         f.can_download = f.can_download(f.request, f.has_leaveslip)
     return files
def class_popup(request):
  context_attr = 'is_in_class'
  in_class = False
  user = request.user
  if hasattr(user, 'type') and is_trainee(user):
    trainee = trainee_from_user(user)
    events = trainee.immediate_upcoming_event(time_delta=0)
    if events:
      event = events[0]
      if event.type == 'C':
        in_class = True
  return {context_attr: in_class, 'user': user}
Example #22
0
    def _get_session(self):
        if not self._exam_available():
            return None

        session = self._get_most_recent_session()
        # Create a new exam session if there is no editable exam session
        # TODO - Check if now - time_started is greater than exam.duration
        if session is None:
            session = Session(trainee=trainee_from_user(self.request.user),
                              exam=self._get_exam(),
                              is_submitted_online=True)
            session.save()

        return session
Example #23
0
def gospel_trip_trainee(request, pk):
  gt = get_object_or_404(GospelTrip, pk=pk)
  context = {'page_title': gt.name}

  if is_trainee(request.user):
    trainee = trainee_from_user(request.user)
  else:
    context['preview_trainees'] = Trainee.objects.all()
    trainee = Trainee.objects.get(id=request.GET.get('trainee', Trainee.objects.first().id))
    context['selected_trainee'] = trainee

  section_qs = Section.objects.filter(Q(gospel_trip=gt) & ~Q(show='HIDE'))
  question_qs = Question.objects.filter(Q(section__in=section_qs) & ~Q(answer_type="None"))
  answer_forms = []
  if request.method == "POST":
    for q in question_qs:
      answer = Answer.objects.get_or_create(trainee=trainee, gospel_trip=gt, question=q)[0]
      answer_forms.append(
        AnswerForm(request.POST, prefix=q.id, instance=answer, gospel_trip__pk=pk)
      )
    if all(f.is_valid() for f in answer_forms):
      for f in answer_forms:
        answer = f.save(commit=False)
        answer.gospel_trip = gt
        answer.trainee = trainee
        answer.question = Question.objects.get(id=f.prefix)
        answer.save()
      return HttpResponseRedirect(pk)
    else:
      context['answer_forms'] = answer_forms
  else:
    for q in question_qs:
      answer = Answer.objects.get_or_create(trainee=trainee, gospel_trip=gt, question=q)[0]
      answer_forms.append(AnswerForm(prefix=q.id, instance=answer, gospel_trip__pk=pk))
    context['answer_forms'] = answer_forms

  context['section_qs'] = section_qs
  context['pk'] = gt.id
  context['AIRPORT_CODES'] = json.dumps(get_airport_codes())
  context['AIRLINE_CODES'] = json.dumps(get_airline_codes())
  return render(request, 'gospel_trips/gospel_trips.html', context=context)
Example #24
0
def unfinalized_service(user):
  # return list of service_id and week
  if has_designated_service(user):
    current_term = Term.current_term()
    if date.today() < current_term.start:
      return None
    # current week = up to week we want to access + 1
    current_week = Term.reverse_date(current_term, datetime.date.today())[0]
    worker = trainee_from_user(user).worker
    designated_services = worker.designated.all()
    if date.today() <= current_term.startdate_of_week(current_week) + timedelta(1):
      # Cannot access past week's because today is less than Wednesday
      current_week = current_week - 1
    for service in designated_services:
      for week in range(0, current_week):
        serv_att = ServiceAttendance.objects.filter(designated_service=service, worker=worker, term=current_term, week=week)
        if not serv_att.exists():
          return [service.id, week]
        elif not serv_att.first().excused and serv_att.first().get_service_hours() == 0:
          return [service.id, week]
  return None
Example #25
0
    def get_object(self, queryset=None):
        term = Term.current_term()
        worker = trainee_from_user(self.request.user).worker
        self.w_designated_services = worker.designated.all()
        self.week = self.kwargs.get('week', None)
        self.service_id = self.kwargs.get('service_id', None)
        if not self.week:
            self.week = term.term_week_of_date(datetime.now().date())

        if not self.service_id:
            self.service_id = self.w_designated_services.first().id

        self.service = Service.objects.get(id=self.service_id)

        # get the existing object or created a new one
        service_attendance = ServiceAttendance.objects.get_or_create(
            worker=worker,
            term=term,
            week=self.week,
            designated_service=self.service)[0]
        return service_attendance
Example #26
0
def changeWeek(request):

    user = request.user
    trainee = trainee_from_user(user)
    service_db = {}
    designated_list = []

    if request.is_ajax():
        week_id = request.GET['week']
        current_week = int(week_id)
        current_week = current_week if current_week < LAST_WEEK else LAST_WEEK
        current_week = current_week if current_week > FIRST_WEEK else FIRST_WEEK
        cws = WeekSchedule.get_or_create_week_schedule(trainee, week_id)
    else:
        ct = Term.current_term()
        current_week = ct.term_week_of_date(date.today())
        cws = WeekSchedule.get_or_create_current_week_schedule(trainee)

    worker_assignments = Worker.objects.select_related(
        'trainee').prefetch_related(
            Prefetch('assignments',
                     queryset=Assignment.objects.filter(week_schedule=cws).
                     select_related('service').order_by('service__weekday'),
                     to_attr='week_assignments'))

    # Find services related to the user
    for current_worker in worker_assignments:
        trainee = str(trainee)
        if trainee == current_worker.full_name:
            for a in current_worker.week_assignments:
                if a.service.category.name == "Designated Services":
                    designated_list.append(a.service)
                else:
                    # service_db.setdefault(a.service.name, []).append((a.service.weekday, a.service_slot.name))
                    service_db.setdefault(a.service.name, a.service.weekday)

    service_data = json.dumps(service_db)
    return HttpResponse(service_data, content_type='application/json')
Example #27
0
def is_week_finalized(user, week):
    finalized = True
    term = Term.current_term()
    try:
      if is_trainee(user):
        trainee = trainee_from_user(user)
        today = date.today()
        term_week_code = str(term.id) + "_" + str(week)
        try:
          trainee_weekly_reading = BibleReading.objects.get(trainee=trainee).weekly_reading_status[term_week_code]
          json_weekly_reading = json.loads(trainee_weekly_reading)
        except (BibleReading.DoesNotExist, KeyError):
          trainee_weekly_reading = "{\"status\": \"_______\", \"finalized\": \"N\"}"
          json_weekly_reading = json.loads(trainee_weekly_reading)
        try:
          if today > term.startdate_of_week(week) + timedelta(8):
            if str(json_weekly_reading['finalized']) == 'N':
              finalized = False
        except TypeError:
          pass
    except AttributeError:
      pass
    return finalized
Example #28
0
 def get_queryset(self):
     user = self.request.user
     trainee = trainee_from_user(user)
     roll = trainee.current_rolls
     return roll
Example #29
0
    def get_context_data(self, **kwargs):
        lJRender = JSONRenderer().render
        ctx = super(RollsView, self).get_context_data(**kwargs)
        user = self.request.user
        trainee = trainee_from_user(user)

        if self.request.method == 'POST':
            selected_week = self.request.POST.get('week')
            event_id = self.request.POST.get('events')
            event = Event.objects.get(id=event_id)
            selected_date = event.date_for_week(int(selected_week))
            event.date = selected_date
            event.start_datetime = datetime.combine(event.date, event.start)
            event.end_datetime = datetime.combine(event.date, event.end)
        else:
            selected_date = date.today()
            selected_week = Event.week_from_date(selected_date)
            # try;
            events = trainee.immediate_upcoming_event(with_seating_chart=True)
            # TODO: - if trainee has no current event load other class that is occuring at the same time
            if len(events) > 0:
                event = events[0]
            else:
                event = None

        selected_week = int(selected_week)

        if event:
            chart = Chart.objects.filter(event=event).first()
            if chart:
                seats = Seat.objects.filter(
                    chart=chart).select_related('trainee')
                partial = Partial.objects.filter(
                    chart=chart).order_by('section_name')
                # Get roll with with for current event and today's date
                roll = Roll.objects.filter(event=event, date=selected_date)
                # TODO - Add group leave slips
                individualslips = IndividualSlip.objects.filter(rolls__in=roll,
                                                                status='A')
                trainees = Trainee.objects.filter(schedules__events=event)
                schedules = Schedule.get_all_schedules_in_weeks_for_trainees([
                    selected_week,
                ], trainees)

                w_tb = EventUtils.collapse_priority_event_trainee_table([
                    selected_week,
                ], schedules, trainees)

                t_set = EventUtils.get_trainees_attending_event_in_week(
                    w_tb, event, selected_week)

                for s in seats:
                    if s.trainee in t_set:
                        s.attending = True
                    else:
                        s.attending = False

                start_datetime = datetime.combine(selected_date, event.start)
                end_datetime = datetime.combine(selected_date, event.end)
                group_slip = GroupSlip.objects.filter(
                    end__gte=start_datetime,
                    start__lte=end_datetime,
                    status='A').prefetch_related('trainees')
                print group_slip, start_datetime, end_datetime
                trainee_groupslip = set()
                for gs in group_slip:
                    trainee_groupslip = trainee_groupslip | set(
                        gs.trainees.all())

                ctx['event'] = event
                ctx['event_bb'] = lJRender(EventWithDateSerializer(event).data)
                ctx['attendance_bb'] = lJRender(
                    RollSerializer(roll, many=True).data)
                ctx['individualslips_bb'] = lJRender(
                    IndividualSlipSerializer(individualslips, many=True).data)
                ctx['trainee_groupslip_bb'] = lJRender(
                    TraineeRollSerializer(trainee_groupslip, many=True).data)
                ctx['trainees_bb'] = lJRender(
                    TraineeRollSerializer(trainees, many=True).data)
                ctx['chart'] = chart
                ctx['chart_bb'] = lJRender(
                    ChartSerializer(chart, many=False).data)
                ctx['seats'] = seats
                ctx['seats_bb'] = lJRender(
                    SeatSerializer(seats, many=True).data)
                ctx['partial'] = partial
                ctx['partial_bb'] = lJRender(
                    PartialSerializer(partial, many=True).data)

        ctx['weekdays'] = WEEKDAYS
        ctx['date'] = selected_date
        ctx['week'] = selected_week
        ctx['day'] = selected_date.weekday()

        # ctx['leaveslips'] = chain(list(IndividualSlip.objects.filter(trainee=self.request.user.trainee).filter(events__term=CURRENT_TERM)), list(GroupSlip.objects.filter(trainee=self.request.user.trainee).filter(start__gte=CURRENT_TERM.start).filter(end__lte=CURRENT_TERM.end)))

        return ctx
Example #30
0
 def get_queryset(self):
   trainee = trainee_from_user(self.request.user)
   schedule = Schedule.objects.filter(trainees=trainee)
   return schedule