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 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 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 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 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 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_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 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 = future.get_occurrences() upcoming_office_hours = upcoming_office_hours[:MAX_FUTURE_OFFICE_HOURS] return render_to_response(template_name, locals(), context_instance=RequestContext(request))
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 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 get_queryset(self): pacific = pytz.timezone('US/Pacific') my_events = Event.objects.all() my_today = pacific.localize( datetime.datetime.now().replace(hour=0, minute=0) \ ) upcoming = Period( my_events, my_today, my_today+datetime.timedelta(days=30) ) event_id_list = [occurrence.event_id for occurrence in upcoming.get_occurrences()] return EventRelation.objects.filter(event_id__in=event_id_list)
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 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 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).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, mailgun_campaign_id="ffz23")
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_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).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="fi0cz")
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 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_queryset(self): pacific = pytz.timezone('US/Pacific') custom_date = self.request.GET.get('date', '') if custom_date: tomorrow_and_day_after = pacific.localize( datetime.datetime.strptime(custom_date, '%Y%m%d') \ + datetime.timedelta(days=1) ) else: tomorrow_and_day_after = pacific.localize( datetime.datetime.now().replace(hour=0, minute=0) \ + datetime.timedelta(days=1) ) my_events = Event.objects.all() upcoming = Period( my_events, tomorrow_and_day_after, tomorrow_and_day_after+datetime.timedelta(days=2) ) occurrence_list = upcoming.get_occurrences() event_list = [occurrence.event for occurrence in occurrence_list] # figure out an order_by based on content_object.entity.jurisdiction.name # Can't # But! ... # ordered = sorted(queryset, key=operator. \ # attrgetter('content_object.entity.jurisdiction.name')) # http://stackoverflow.com/questions/2412770/good-ways-to-sort-a-queryset-django queryset = EventRelation.objects.prefetch_related('content_object__entity__jurisdiction'). \ filter(event_id__in=event_list) ordered = sorted(queryset, key=operator \ .attrgetter('content_object.entity.jurisdiction.name', 'event.start')) for event_item in ordered: # replace u'\r\n' with u' ' in Agenda text event_item.content_object.agenda = event_item.content_object \ .agenda.replace(u'\r\n', u' ') return ordered
def get_queryset(self): event_qs = Event.objects.all() start, end = self.get_period_window() period = Period(event_qs, start, end) occurrences = period.get_occurrences() return occurrences