def test_moved_occurrences(self): occurrences = self.recurring_reservation.get_occurrences(start=self.start, end=self.end) moved_occurrence = occurrences[1] span_pre = (moved_occurrence.start, moved_occurrence.end) span_post = [x + datetime.timedelta(hours=2) for x in span_pre] # check has_occurrence on both periods period_pre = Period([self.recurring_reservation], span_pre[0], span_pre[1]) period_post = Period([self.recurring_reservation], span_post[0], span_post[1]) self.assertTrue(period_pre.has_occurrences()) self.assertFalse(period_post.has_occurrences()) # move occurrence moved_occurrence.move(moved_occurrence.start+datetime.timedelta(hours=2), moved_occurrence.end+datetime.timedelta(hours=2)) occurrences = self.recurring_reservation.get_occurrences(start=self.start, end=self.end) self.assertTrue(occurrences[1].moved) # check has_occurrence on both periods (the result should be reversed) period_pre = Period([self.recurring_reservation], span_pre[0], span_pre[1]) period_post = Period([self.recurring_reservation], span_post[0], span_post[1]) self.assertFalse(period_pre.has_occurrences()) self.assertTrue(period_post.has_occurrences()) # trigger bug discovered by gautamadude - modifying recurring reservation # breaks link between a persistent occurrence and the occurrence chain # leaving an "orphaned" occurrence occurrences = self.recurring_reservation.get_occurrences(start=self.start, end=self.end) self.assertTrue(len(occurrences) == 3) self.recurring_reservation.start = datetime.datetime(2008, 1, 5, 8, 15) self.recurring_reservation.save() occurrences_later = self.recurring_reservation.get_occurrences(start=self.start, end=self.end) self.assertEquals(len(occurrences_later), len(occurrences))
def next_events(context, length=5, calendar=None, days=120): '''Inserts a list of the next five event occurrences from right now for a given calendar. Optionally, a length can be passed for a certain number of events to be returned. The calendar can also be 'None' to pull events from all calendars. The tag also takes a number of days for the period. The returned context is a list of events and is rendered using the _event_list.html template. ''' if not calendar: events = [] cals = Calendar.objects.all() while len(events) < length: for c in cals: period = Period(events=c.events, start=datetime.datetime.now(), end=(datetime.datetime.now() + timedelta(days=days))) for occ in period.get_occurrences(): events.append(occ) events.sort(lambda x, y: cmp(x.start, y.start)) context['events'] = events[0:length] else: period = Period(events=calendar.events, start=datetime.datetime.now(), end=(datetime.datetime.now() + timedelta(days=364))) context['events'] = period.get_occurrences()[0:length] context['today'] = datetime.datetime.now().date() return context
def test_moved_occurrences(self): occurrences = self.recurring_event.get_occurrences(start=self.start, end=self.end) moved_occurrence = occurrences[1] span_pre = (moved_occurrence.start, moved_occurrence.end) span_post = [x + datetime.timedelta(hours=2) for x in span_pre] # check has_occurrence on both periods period_pre = Period([self.recurring_event], span_pre[0], span_pre[1]) period_post = Period([self.recurring_event], span_post[0], span_post[1]) self.assertTrue(period_pre.has_occurrences()) self.assertFalse(period_post.has_occurrences()) # move occurrence moved_occurrence.move( moved_occurrence.start + datetime.timedelta(hours=2), moved_occurrence.end + datetime.timedelta(hours=2)) occurrences = self.recurring_event.get_occurrences(start=self.start, end=self.end) self.assertTrue(occurrences[1].moved) # check has_occurrence on both periods (the result should be reversed) period_pre = Period([self.recurring_event], span_pre[0], span_pre[1]) period_post = Period([self.recurring_event], span_post[0], span_post[1]) self.assertFalse(period_pre.has_occurrences()) self.assertTrue(period_post.has_occurrences())
def get_task_occurences(user): tasks = TaskViewSet.get_user_tasks(user) today = datetime.datetime.now() end_date = (today + datetime.timedelta(days=(7 - today.weekday() + 7))) this_period = Period(tasks.all(), today, end_date) result = this_period.get_occurrences() result.sort(key=lambda r: r.end) overdue = TaskViewSet.get_task_overdue(user) no_due_date = tasks.filter(end=datetime.datetime.fromtimestamp(0)) this_period_2 = Period( no_due_date.all(), datetime.datetime.fromtimestamp(-1), datetime.datetime.fromtimestamp(1) ) no_due_date_occurrences = this_period_2.get_occurrences() res = list( filter(lambda x: x.id is None or not x.task_occurrences.completed, result + overdue + no_due_date_occurrences) ) data = OccurrenceSerializer(res, many=True).data if data is not None: return list(filter(lambda x: ((x['event']['airport'] == None or x['event']['airport'] == user.aerosimple_user.airport_id) and (x['event']['assigned_role'] == None or x['event']['assigned_role']['airport_id'] == user.aerosimple_user.airport_id)), data)) # return data return []
def site_index(request, template_name='index.html'): # most future office hours to show MAX_FUTURE_OFFICE_HOURS = 30 # furthest into the future to display office hours MAX_FUTURE_DAYS = 30 users_available_now = User.objects.filter(profile__is_available=True) events = Event.objects.all() now = Period(events=events, start=datetime.now(), end=datetime.now() + timedelta(minutes=1)) occurences = now.get_occurrences() users_holding_office_hours_now = map(lambda x: x.event.creator, occurences) users = set(list(users_available_now) + users_holding_office_hours_now) future = Period(events=events, start=datetime.now(), end=datetime.now() + timedelta(days=MAX_FUTURE_DAYS)) upcoming_office_hours = [] already_saw = {} for i in future.get_occurrences(): if len(upcoming_office_hours) >= MAX_FUTURE_OFFICE_HOURS: break if already_saw.get(i.event.creator): continue upcoming_office_hours.append(i) already_saw[i.event.creator] = 1 upcoming_office_hours = upcoming_office_hours[:MAX_FUTURE_OFFICE_HOURS] return direct_to_template(request, template_name, locals())
def testPeriodFromPool(self): """ Test that period initiated with occurrence_pool returns the same occurrences as "straigh" period in a corner case whereby a period's start date is equal to the occurrence's end date """ start = datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc) end = datetime.datetime(2008, 1, 5, 10, 0, tzinfo=pytz.utc) parent_period = Period(Event.objects.all(), start, end) period = Period(parent_period.events, start, end, parent_period.get_persisted_occurrences(), parent_period.occurrences) self.assertEqual(parent_period.occurrences, period.occurrences)
def task_immediate_reminder(): """ tries to send a reminder for appointments happening in the next 45 minutes that have NOT been notified probably these were created very soon before the appointment start and thus were not caught by any other task The idea is to catch any appointments happening very soon that have NOT been notified """ t = timezone.localtime(timezone.now()) fro = t to = t + timedelta(minutes=45) period = Period( Event.objects.exclude(appointment=None).exclude( appointment__client=None).exclude( appointment__status=Appointment.NOTIFIED).exclude( appointment__status=Appointment.CANCELED), fro, to) event_objects = period.get_occurrences() event_ids = list(set([x.event.id for x in event_objects])) send_period_reminders(event_ids, sendsms=True, turn_off_reminders=True, mailgun_campaign_id="fi0cz")
def setUp(self): rule = Rule.objects.create(frequency="WEEKLY") cal = Calendar.objects.create(name="MyCal") Event.objects.create( title='Recent Event', start=datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), end_recurring_period=datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), rule=rule, calendar=cal, ) self.period = Period(events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc))
def task_hour_to_reminder(): """ tries to send a reminder approximately one hour before an appointment given a time, say 7AM we look for appointments that are happening between 46 minutes and 1 hour from the given time in our case 7:46AM and 8AM if time now i6 7:45 we get fro=8:31 and to = 8:45 we use 46 minutes to avoid cases where events happening at exactly *:15, *:30, *:45, or *:00 dont get multiple reminders The idea is to catch any appointments happening soon that have NOT been notified """ t = timezone.localtime(timezone.now()) fro = t + timedelta(minutes=46) to = t + timedelta(hours=1) period = Period( Event.objects.exclude(appointment=None).exclude( appointment__client=None).exclude( appointment__status=Appointment.NOTIFIED).exclude( appointment__status=Appointment.CANCELED).exclude( appointment__status=Appointment.CONFIRMED), fro, to) event_objects = period.get_occurrences() event_ids = list(set([x.event.id for x in event_objects])) send_period_reminders(event_ids, sendsms=True, turn_off_reminders=True, mailgun_campaign_id="fi0bd")
def setUp(self): self.day = Day( events=Event.objects.all(), date=datetime.datetime(datetime.datetime.now().year, 2, 7, 0, 0, tzinfo=pytz.utc)) self.day_out_of_limit = Day( events=Event.objects.all(), date=datetime.datetime(datetime.datetime.now().year + 3, 2, 7, 0, 0, tzinfo=pytz.utc)) self.day_out_of_limit_lower = Day( events=Event.objects.all(), date=datetime.datetime(datetime.datetime.now().year - 3, 2, 7, 0, 0, tzinfo=pytz.utc)) rule = Rule.objects.create(frequency='WEEKLY') self.cal = Calendar.objects.create(name='MyCal', slug='MyCalSlug') data = { 'title': 'Recent Event', 'start': datetime.datetime(datetime.datetime.now().year, 1, 5, 8, 0, tzinfo=pytz.utc), 'end': datetime.datetime(datetime.datetime.now().year, 1, 5, 9, 0, tzinfo=pytz.utc), 'end_recurring_period': datetime.datetime(datetime.datetime.now().year, 5, 5, 0, 0, tzinfo=pytz.utc), 'rule': rule, 'calendar': self.cal, } Event.objects.create(**data) self.period = Period(events=Event.objects.all(), start=datetime.datetime(datetime.datetime.now().year, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(datetime.datetime.now().year, 1, 21, 7, 0, tzinfo=pytz.utc))
def setUp(self): rule = Rule(frequency="WEEKLY") rule.save() cal = Calendar(name="MyCal") cal.save() data = { 'title': 'Recent Event', 'start': datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), 'end': datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), 'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), 'rule': rule, 'calendar': cal } recurring_event = Event(**data) recurring_event.save() self.period = Period(events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc))
def test_weeks_later_period(self): # prepare schedules = Schedule.objects.all() # do occurs = Period(schedules, start=(self.s3_start + timedelta(weeks=4)), end=(self.s3_end + timedelta(weeks=4))).get_occurrences() self.assertEqual(len(occurs), 1, msg='Should be only one schedule')
def json_events(request): ret = '' if request.user.is_authenticated(): pcal = get_personal_calendar(request.user) start = request.GET['start'] end = request.GET['end'] allowed_objects = set([]) perms = ['viewer', 'manager', 'creator'] ao = {} for p in perms: ao[p] = get_user_calendars(request.user, [p]) allowed_objects = allowed_objects.union(set(ao[p])) for obj in allowed_objects: evt = EventRelation.objects.get_events_for_object( obj.content_object) if obj.pk == pcal.pk or obj in ao['manager']: manager = True else: manager = False if obj.pk == pcal.pk or obj in ao['creator']: creator = True else: creator = False period = Period(events=evt, start=datetime.datetime.fromtimestamp( float(start)), end=datetime.datetime.fromtimestamp(float(end))) occurrences = [] for o in period.occurrences: if period.classify_occurrence(o): o.calendar_id = obj.pk o.calendar_name = obj.calendar.name if o.event.calendar_id == obj.calendar.pk: o.manager = manager o.creator = creator else: o.manager = False o.creator = False if o.id: o.details = EventDetails.objects.get_eventdetails_for_object( o) else: o.details = EventDetails.objects.get_eventdetails_for_object( o.event) if o.details.privacy == 2 and request.user != obj.owner: # Private event continue else: occurrences.append(o) if len(occurrences): ret += '"' + obj.calendar.slug + '": ' + \ jsondump_occurences(occurrences, request.user) + ',' ret = ret[:-1] ret = '{' + ret + '}' # json_data = simplejson.dumps(ret) return HttpResponse(ret)
def test_occurrences_with_TZ(self): start = self.MVD.localize(datetime.datetime(2017, 1, 13)) end = self.MVD.localize(datetime.datetime(2017, 1, 23)) period = Period(Event.objects.all(), start, end, tzinfo=self.MVD) self.assertEqual( ["%s to %s" % (o.start, o.end) for o in period.occurrences], [ '2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00', '2017-01-21 22:00:00-03:00 to 2017-01-21 23:00:00-03:00' ])
def get_event_occurrences_today(request): now = timezone.now() start = now end = now + datetime.timedelta(hours=1) occurrences = Period(Event.objects.all(), start, end).get_occurrences() # set the Zoom ID for the group session events to be the same as the previous one return { 'occurrences': occurrences, 'now': now, }
def is_available(self, date, duration, customer=None): if date.hour < settings.DAY_START or date.hour + int(duration) > settings.DAY_END: return False # Not operating on this hours. barber_schedule_data = [Event.objects.get(pk=item['event_id']) for item in EventRelation.objects.filter(event__calendar__name='barber_schedule').filter(object_id=self.id).values('event').values()] if not Day(barber_schedule_data, date).has_occurrences(): return False # Barber doesn't work this day. client_schedule_data = [Event.objects.get(pk=EventRelation.objects.filter(event__calendar__name='client_schedule').get(object_id=appointment.id).event_id) for appointment in Appointment.objects.filter(barber=self) if appointment.customer != customer] if Period(client_schedule_data, date + timedelta(minutes=1), date + timedelta(hours=int(duration)-1, minutes=59)).has_occurrences(): return False # Barber got another client at this time. return True
def render(self, context): try: true_cal = self.calendar.resolve(context) if type(true_cal) != Calendar: true_cal = Calendar.objects.get(slug=true_cal) period = Period(events=true_cal.events, start=datetime.datetime.now(), end=(datetime.datetime.now() + datetime.timedelta(days=365))) context[self.varname] = period.get_occurrences()[0:self.length] except template.VariableDoesNotExist: context[self.varname] = '' return ''
def view_profile(request, username, template_name='profiles/view_profile.html'): user = get_object_or_404(User, username=username) display_full_profile = _can_view_full_profile(request.user) events = Event.objects.filter(creator=user) start = datetime.now() end = start + timedelta(days=30) period = Period(events=events, start=start, end=end) office_hours = period.get_occurrences() return render_to_response(template_name, locals(), context_instance=RequestContext(request))
def setUp(self): self.events = Event.objects.filter(calendar__pk=2) self.period = Period(events=self.events, start=datetime.datetime(2014, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2016, 1, 21, 7, 0, tzinfo=pytz.utc))
def setUp(self): rule = Rule(frequency="WEEKLY") rule.save() data = { 'title': 'Recent Event', 'start': datetime.datetime(2008, 1, 5, 8, 0), 'end': datetime.datetime(2008, 1, 5, 9, 0), 'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0), 'rule': rule, } recurring_event = Event(**data) recurring_event.save() self.period = Period(events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0), end=datetime.datetime(2008, 1, 21, 7, 0))
def month_cal(context, year, month): request = context['request'] ret = [] if request.user.is_authenticated(): evt = EventRelation.objects.get_events_for_object(request.user) period = Period(events=evt, start=datetime.datetime(year, month, 1), end=datetime.datetime(year, month, 30)) occurrences = [] for o in period.occurrences: if period.classify_occurrence(o): occurrences.append(o) first_day_of_month = datetime.date(year, month, 1) last_day_of_month = get_last_day_of_month(year, month) first_day_of_calendar = first_day_of_month - \ datetime.timedelta(first_day_of_month.weekday()) last_day_of_calendar = last_day_of_month + \ datetime.timedelta(7 - last_day_of_month.weekday()) month_cal = [] week = [] week_headers = [] i = 0 day = first_day_of_calendar while day <= last_day_of_calendar: if i < 7: week_headers.append(day) cal_day = {} cal_day['day'] = day cal_day['event'] = False for occ in ret: if day >= occ.start.date() and day <= occ.end.date(): cal_day['event'] = True if day.month == month: cal_day['in_month'] = True else: cal_day['in_month'] = False week.append(cal_day) if day.weekday() == 6: month_cal.append(week) week = [] i += 1 day += datetime.timedelta(1) return {'calendar': month_cal, 'headers': week_headers}
def setUp(self): rule = Rule(frequency="WEEKLY") rule.save() cal = Room(name="MyCal") cal.save() data = { 'title': 'Recent Reservation', 'start': datetime.datetime(2008, 1, 5, 8, 0), 'end': datetime.datetime(2008, 1, 5, 9, 0), 'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0), 'rule': rule, 'room': cal } recurring_reservation = Reservation(**data) recurring_reservation.save() self.period = Period(reservations=Reservation.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0), end=datetime.datetime(2008, 1, 21, 7, 0))
def get_task_overdue(user): """ Get overdue tasks, ie. past ocurrences not persisted and not completed. When completing an ocurrence the Ocurrence instance is persisted, so ocurrence without pk are incompleted. """ tasks = TaskViewSet.get_user_tasks(user) today = datetime.datetime.now() this_period = Period( tasks.all(), datetime.datetime.fromtimestamp(0), today) result = list( filter(lambda x: x.id is None or not x.task_occurrences.completed, this_period.get_occurrences()) ) result.sort(key=lambda r: r.end) return result
def task_morning_reminders(): """ Sends a reminder to all the appointments happening today currently sends at 7am """ t = timezone.now().date() fro = datetime(year=t.year, month=t.month, day=t.day, hour=7, tzinfo=timezone.get_current_timezone()) to = fro + timedelta(1) period = Period( Event.objects.exclude(appointment=None).exclude( appointment__client=None).exclude( appointment__status=Appointment.CANCELED), fro, to) event_objects = period.get_occurrences() event_ids = list(set([x.event.id for x in event_objects])) send_period_reminders(event_ids, sendsms=True, mailgun_campaign_id="ffz23")
def delegated(self, request): tasks = Task.objects.filter( creator=self.request.user).exclude( assigned_user=self.request.user.aerosimple_user).exclude( assigned_role__in=self.request.user.aerosimple_user.roles.all()) today = datetime.datetime.combine( datetime.datetime.now(), datetime.datetime.min.time() ) end_date = (today + datetime.timedelta(days=(7 - today.weekday() + 7))) this_period = Period(tasks.all(), today, end_date) result = this_period.get_occurrences() result.sort(key=lambda r: r.end) data = OccurrenceSerializer(result, many=True).data if data is not None: return Response(list(filter(lambda x: ((x['event']['airport'] == None or x['event']['airport'] == self.request.user.aerosimple_user.airport_id) and (x['event']['assigned_role'] == None or x['event']['assigned_role']['airport_id'] == self.request.user.aerosimple_user.airport_id)), data))) # return data return []
def get_events_for_object(obj, start_date, end_date): occurrences = [] evt = EventRelation.objects.get_events_for_object(obj) period = Period(events=evt, start=start_date, end=end_date) for o in period.occurrences: if period.classify_occurrence(o): if o.id: o.details = EventDetails.objects.get_eventdetails_for_object(o) else: o.details = EventDetails.objects.get_eventdetails_for_object( o.event) occurrences.append(o) events_list = [] for occ in occurrences: ed = {} if occ.start.time().__str__() == '00:00:00' and occ.end.time().__str__() == '00:00:00': ed['allday'] = True else: ed['allday'] = False ed['title'] = occ.title ed['start'] = occ.start ed['end'] = occ.end ed['status'] = get_date_status( occ.start) # 'overdue', 'today' , 'tomorrow' or '' ed['description'] = occ.description ed['author'] = User.objects.get( pk=occ.event.creator_id).get_full_name() if occ.details.bgcolor: ed['backgroundColor'] = occ.details.bgcolor elif occ.details.category: ed['backgroundColor'] = occ.details.category.bgcolor ed['category'] = occ.details.category.name else: ed['backgroundColor'] = False ed['category'] = '' events_list.append(ed) return events_list
def test_get_occurrences_with_sorting_options(self): period = Period(events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc), sorting_options={"reverse": True}) occurrence_list = period.occurrences self.assertEqual( ["%s to %s" % (o.start, o.end) for o in occurrence_list], [ '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00', '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00', '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00', ])
def venue_event_feed(request, pk): venue = get_object_or_404(Venue, pk=pk) if request.is_ajax() and request.method == 'GET': if 'start' in request.GET and 'end' in request.GET: fro = timezone.make_aware( datetime.fromtimestamp(float(request.GET['start'])), timezone.get_current_timezone()) to = timezone.make_aware( datetime.fromtimestamp(float(request.GET['end'])), timezone.get_current_timezone()) period = Period( Event.objects.exclude(appointment=None).filter( appointment__customer=request.user.userprofile.customer). filter(appointment__venue=venue), fro, to) data = [{ 'id': x.event.appointment_set.first().pk, 'title': "{}".format( x.event.appointment_set.first().venue_display_name), 'userId': [x.event.appointment_set.first().venue.pk], 'start': x.start.isoformat(), 'end': x.end.isoformat(), 'clientId': x.event.appointment_set.first().clientId, 'status': x.event.appointment_set.first().status, 'tag': getattr(x.event.appointment_set.first().tag, 'html_name', ""), 'body': x.event.description } for x in period.get_occurrences() if x.event.appointment_set.first()] return HttpResponse(json.dumps(data), content_type="application/json") # if all fails raise Http404
def task_48hrbefore_reminders(): """ Sends a reminder to all the UN-NOTIFIED appointments happening in the next 48hrs currently sends at 6pm """ t = timezone.now().date() fro = datetime(year=t.year, month=t.month, day=t.day, hour=0, tzinfo=timezone.get_current_timezone()) fro = fro + timedelta(2) to = fro + timedelta(1) period = Period( Event.objects.exclude(appointment=None).exclude( appointment__client=None).exclude( appointment__status=Appointment.NOTIFIED).exclude( appointment__status=Appointment.CANCELED), fro, to) event_objects = period.get_occurrences() event_ids = list(set([x.event.id for x in event_objects])) send_period_reminders(event_ids, sendsms=True, mailgun_campaign_id="fi0bc")
def get_appointments_for(self, barber, start, end): client_schedule_data = [Event.objects.get(pk=EventRelation.objects.filter(event__calendar__name='client_schedule').get(object_id=appointment.id).event_id) for appointment in Appointment.objects.filter(barber=barber)] occurrences = Period(client_schedule_data, start + timedelta(minutes=1), end - timedelta(minutes=1)).get_occurrences() return [Event.objects.get(pk=occ.event_id) for occ in occurrences]