def get_context_data(self, **kwargs): context = super(DisciplineListView, self).get_context_data(**kwargs) try: context['current_period'] = Period(Term.current_term()).period_of_date(datetime.now().date()) except ValueError: # ValueError thrown if current date is not in term (interim) # return last period of previous period context['current_period'] = Period.last_period() return context
def post(self, request, *args, **kwargs): """'approve' when an approve button is pressed 'delete' when a delete button is pressed 'attend_assign' when assgning discipline from AttendanceAssign""" if 'approve' in request.POST: for value in request.POST.getlist('selection'): Discipline.objects.get(pk=value).approve_all_summary() messages.success(request, "Checked Discipline(s) Approved!") if 'delete' in request.POST: for value in request.POST.getlist('selection'): Discipline.objects.get(pk=value).delete() messages.success(request, "Checked Discipline(s) Deleted!") if 'trainee_pk' in request.POST: trainee_pk = request.POST.getlist('trainee_pk') ls_count = request.POST.getlist('ls_count') period = int(request.POST.get('period')) for idx, pk in enumerate(trainee_pk): discipline = Discipline( infraction='AT', quantity=ls_count[idx], due=Period(Term.current_term()).start(period + 1) + timedelta(weeks=1), # Due on the second Monday of the next period offense='MO', trainee=Trainee.objects.get(pk=pk)) try: discipline.save() except IntegrityError: logger.error('Abort trasanction error') transaction.rollback() messages.success(request, "Discipline Assigned According to Attendance!") return self.get(request, *args, **kwargs)
def calculate_summary(trainee, period): """this function examines the Schedule belonging to trainee and search through all the Events and Rolls. Returns the number of summary a trainee needs to be assigned over the given period.""" num_A = 0 num_T = 0 num_summary = 0 current_term = Term.current_term() for roll in trainee.rolls.all(): if roll.date >= Period(current_term).start( period) and roll.date <= Period(current_term).end(period): if roll.status == 'A': num_A += 1 elif roll.status == 'L' or roll.status == 'T' or roll.status == 'U': num_T += 1 if num_A >= 2: num_summary += num_A if num_T >= 5: num_summary += num_T - 3 return num_summary
def assignDiscipline(): try: logger.info("Start task") term = Term.current_term() period = Period(term).period_of_date(date.today()) for trainee in Trainee.objects.filter(is_active=True).all(): amount = 0 amount += trainee.calculate_summary(period) logger.info('%s : %d life studies' % (trainee.full_name, amount)) Discipline.assign_attendance_summaries(trainee, period, amount) except Exception, msg: logger.error(msg)
def get_context_data(self, **kwargs): """this adds outstanding_trainees, a dictionary {trainee : num_summary} for the template to display the trainees who need will have outstanding summaries""" context = super(AttendanceAssign, self).get_context_data(**kwargs) period = int(self.kwargs['period']) context['period'] = period p = Period(Term.current_term()) context['start_date'] = p.start(period) context['end_date'] = p.end(period) context['period_list'] = list() for period_num in range(1, 11): context['period_list'].append((period_num, p.start(period_num), p.end(period_num))) return context
def post(self, request, *args, **kwargs): self.object_list = Trainee.objects.all() context = super(AttendanceAssign, self).get_context_data(*args, **kwargs) """Preview button was pressed""" if 'preview_attendance_assign' in request.POST: period = int(request.POST['select_period']) context['period'] = period p = Period(Term.current_term()) start_date = p.start(period) end_date = p.end(period) context['start_date'] = start_date context['end_date'] = end_date context['period_list'] = list() for period_num in range(1, 11): context['period_list'].append((period_num, p.start(period_num), p.end(period_num))) context['preview_return'] = 1 # outstanding_trainees = list() context['outstanding_trainees'] = list() '''FILTERING OUT TRAINEES BASED ON INDIVIDUAL LEAVESLIPS''' rolls = Roll.objects.all() rolls = rolls.filter(date__gte=start_date, date__lte=end_date) t = timeit_inline("summary calculation") t.start() for trainee in Trainee.objects.all(): # print trainee # num_summary += trainee.calculate_summary(period num_summary = 0 num_summary += trainee.calculate_summary(period) if num_summary > 0: print trainee, num_summary context['outstanding_trainees'].append((trainee, num_summary)) t.end() return render(request, 'lifestudies/attendance_assign.html', context)
def get_attendance_record(self, period=None): from leaveslips.models import GroupSlip c_term = Term.current_term() rolls = self.rolls.exclude(status='P').filter( date__gte=c_term.start, date__lte=c_term.end).order_by( 'event', 'date').distinct('event', 'date').prefetch_related('event') ind_slips = self.individualslips.filter(status__in=['A', 'S']) att_record = [] # list of non 'present' events excused_timeframes = [] # list of groupslip time ranges excused_rolls = [] # prevents duplicate rolls def attendance_record(att, start, end, event): return { 'attendance': att, 'start': start, 'end': end, 'event': event, } def reformat(slip): s = str( datetime.combine(slip['rolls__date'], slip['rolls__event__start'])).replace( ' ', 'T') e = str( datetime.combine(slip['rolls__date'], slip['rolls__event__end'])).replace(' ', 'T') return (s, e) group_slips = GroupSlip.objects.filter(trainees=self, status__in=['A', 'S']) rolls = rolls.order_by('event__id', 'date').distinct( 'event__id', 'date') # may not need to order if period is not None: # works without period, but makes calculate_summary really slow p = Period(c_term) start_date = p.start(period) end_date = p.end(period) startdt = datetime.combine(start_date, datetime.min.time()) enddt = datetime.combine(end_date, datetime.max.time()) rolls = rolls.filter( date__gte=start_date, date__lte=end_date) # rolls for current period ind_slips = ind_slips.filter( rolls__in=[d['id'] for d in rolls.values('id')]) group_slips = group_slips.filter(start__lte=enddt, end__gte=startdt) rolls = rolls.values('event__id', 'event__start', 'event__end', 'event__name', 'status', 'date') ind_slips = ind_slips.values('rolls__event__id', 'rolls__event__start', 'rolls__event__end', 'rolls__date', 'rolls__event__name', 'id') excused_timeframes = group_slips.values('start', 'end') # first, individual slips for slip in ind_slips: if slip['rolls__event__id'] is None: continue start, end = reformat(slip) att_record.append( attendance_record('E', start, end, slip['rolls__event__id'])) excused_rolls.append( (slip['rolls__event__id'], slip['rolls__date'])) for roll in rolls: excused = False for excused_roll in excused_rolls: if roll['event__id'] == excused_roll[0] and roll[ 'date'] == excused_roll[ 1]: # Check if roll is excused using the roll's event and the roll's date excused = True break if excused is False: if roll['status'] == 'A': # absent rolls att_record.append( attendance_record( 'A', str(roll['date']) + 'T' + str(roll['event__start']), str(roll['date']) + 'T' + str(roll['event__end']), roll['event__id'])) else: # tardy rolls att_record.append( attendance_record( 'T', str(roll['date']) + 'T' + str(roll['event__start']), str(roll['date']) + 'T' + str(roll['event__end']), roll['event__id'])) # now, group slips for record in att_record: if record['event'] is None: continue if record['attendance'] != 'E': start_dt = parser.parse(record['start']) end_dt = parser.parse(record['end']) for tf in excused_timeframes: if EventUtils.time_overlap(start_dt, end_dt, tf['start'], tf['end']): record['attendance'] = 'E' return att_record
def generate_panels(context): user = context['user'] if user.is_anonymous(): return "" ls = Discipline.objects.filter(trainee=user) num_ls = 0 for l in ls: num_ls = num_ls + l.get_num_summary_due() lifestudies_panel = Panel( name='Life Studies', # to temp fix -1 due life studies, TODO fix -1 summaries needed # num= num_ls num=num_ls if num_ls > 0 else 0, url=reverse('lifestudies:discipline_list'), ) classnotes_panel = Panel( name='Class Notes', num=Classnotes.objects.filter(Q(trainee=user) & ~Q(status='A')).count(), url=reverse('classnotes:classnotes_list') ) # try and except to accomodate for superuser p = Period(Term.current_term()).period_of_date(date.today()) uet = uea = 0 try: att_rcd = trainee_from_user(user).get_attendance_record(p) for att in att_rcd: if att['attendance'] in ['A', 'T']: excused = filter(lambda a: a['start'] == att['start'], att_rcd) if len(excused) < 2: if att['attendance'] == 'A': uea += 1 elif att['attendance'] == 'T': uet += 1 except AttributeError: pass unexcusedtardies_panel = Panel( name='Unexcused Tardies', num=uet, url=reverse('attendance:attendance-submit') ) unexcusedabsences_panel = Panel( name='Unexcused Absences', num=uea, url=reverse('attendance:attendance-submit') ) ls_pending = 0 ls_ip = IndividualSlip.objects.filter(trainee=user, status='P') ls_gp = GroupSlip.objects.filter(trainees=user, status='P') ls_pending = sum([1 if p in slip.periods else 0 for slip in ls_ip] + [1 if p in slip.periods else 0 for slip in ls_gp]) leaveslips_panel = Panel( name='Leave Slips Pending', num=ls_pending, url=reverse('attendance:attendance-submit') ) panels = [leaveslips_panel, unexcusedtardies_panel, unexcusedabsences_panel, lifestudies_panel, classnotes_panel] return panels