Ejemplo n.º 1
0
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")
Ejemplo n.º 2
0
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")
Ejemplo n.º 3
0
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")
Ejemplo n.º 4
0
class TestPeriod(TestCase):
    def setUp(self):
        rule = Rule.objects.create(frequency="WEEKLY")
        cal = Calendar.objects.create(name="MyCal")
        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,
        }
        Event.objects.create(**data)
        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_get_occurrences(self):
        occurrence_list = self.period.occurrences
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in occurrence_list], [
                '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00',
                '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00',
                '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00',
            ])

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual(
            [(occ_dict["class"], occ_dict["occurrence"].start,
              occ_dict["occurrence"].end) for occ_dict in occurrence_dicts],
            [(1, datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc),
              datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc)),
             (1, datetime.datetime(2008, 1, 12, 8, 0, tzinfo=pytz.utc),
              datetime.datetime(2008, 1, 12, 9, 0, tzinfo=pytz.utc)),
             (1, datetime.datetime(2008, 1, 19, 8, 0, tzinfo=pytz.utc),
              datetime.datetime(2008, 1, 19, 9, 0, tzinfo=pytz.utc))])

    def test_has_occurrence(self):
        self.assertTrue(self.period.has_occurrences())
        slot = self.period.get_time_slot(
            datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc),
            datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc))
        self.assertFalse(slot.has_occurrences())
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
    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))
Ejemplo n.º 7
0
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())
Ejemplo n.º 8
0
def json_period(request, calender_id):
    calendar = get_object_or_404(Calendar, pk=calender_id)
    ts_start = float(request.GET.get("start", None))
    ts_end = float(request.GET.get("end", None))
    # if not request.is_ajax(): raise Http404

    # period = Month(GET_EVENTS_FUNC(request,calendar)
    # ,date=datetime.datetime(year=2008,month=11,day=1)
    # ,date=datetime.datetime.now()
    # )

    period = Period(
        GET_EVENTS_FUNC(request, calendar),
        start=datetime.datetime.fromtimestamp(ts_start),
        end=datetime.datetime.fromtimestamp(ts_end),
    )

    context = {"calendar": calendar, "occurences": period.get_occurrence_partials()}  # {occurence,class}
    dates = [
        {
            "title": occ["occurrence"].title,
            "start": occ["occurrence"].start.isoformat(),
            "end": occ["occurrence"].end.isoformat(),
            "allDay": False,
        }
        for occ in period.get_occurrence_partials()
    ]

    return HttpResponse(json.dumps(dates), mimetype="application/json")
Ejemplo n.º 9
0
 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))
Ejemplo n.º 10
0
 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))
Ejemplo n.º 11
0
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))
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
 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 ''
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
 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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
class TestPeriod(TestCase):
    def setUp(self):
        rule = Rule.objects.create(frequency="WEEKLY")
        cal = Calendar.objects.create(name="MyCal")
        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,
        }
        Event.objects.create(**data)
        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_get_occurrences(self):
        occurrence_list = self.period.occurrences
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in occurrence_list],
            [
                '2008-01-05 08:00:00+00:00 to 2008-01-05 09:00:00+00:00',
                '2008-01-12 08:00:00+00:00 to 2008-01-12 09:00:00+00:00',
                '2008-01-19 08:00:00+00:00 to 2008-01-19 09:00:00+00:00',
            ]
        )

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual(
            [
                (occ_dict["class"], occ_dict["occurrence"].start, occ_dict["occurrence"].end)
                for occ_dict in occurrence_dicts
            ],
            [
                (1,
                 datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc),
                 datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc)),
                (1,
                 datetime.datetime(2008, 1, 12, 8, 0, tzinfo=pytz.utc),
                 datetime.datetime(2008, 1, 12, 9, 0, tzinfo=pytz.utc)),
                (1,
                 datetime.datetime(2008, 1, 19, 8, 0, tzinfo=pytz.utc),
                 datetime.datetime(2008, 1, 19, 9, 0, tzinfo=pytz.utc))
            ])

    def test_has_occurrence(self):
        self.assertTrue(self.period.has_occurrences())
        slot = self.period.get_time_slot(
            datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc),
            datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc))
        self.assertFalse(slot.has_occurrences())
Ejemplo n.º 18
0
 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)
Ejemplo n.º 19
0
    def test_occurrences_sub_period_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)

        sub_start = self.MVD.localize(datetime.datetime(2017, 1, 13))
        sub_end = self.MVD.localize(datetime.datetime(2017, 1, 15))
        sub_period = period.get_time_slot(sub_start, sub_end)
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in sub_period.occurrences],
            ['2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00'])
Ejemplo n.º 20
0
class TestPeriod(TestCase):
    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),
            'end': datetime.datetime(2008, 1, 5, 9, 0),
            'end_recurring_period': datetime.datetime(2008, 5, 5, 0, 0),
            '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),
                             end=datetime.datetime(2008, 1, 21, 7, 0))

    def test_get_occurrences(self):
        occurrence_list = self.period.occurrences
        expected = [
            '2008-01-05 08:00:00 to 2008-01-05 09:00:00',
            '2008-01-12 08:00:00 to 2008-01-12 09:00:00',
            '2008-01-19 08:00:00 to 2008-01-19 09:00:00',
        ]
        self.assertEqual(["%s to %s" % (o.start, o.end) for o in occurrence_list], expected)

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual(
            [(occ_dict["class"],
            occ_dict["occurrence"].start,
            occ_dict["occurrence"].end)
            for occ_dict in occurrence_dicts],
            [
                (1,
                 datetime.datetime(2008, 1, 5, 8, 0),
                 datetime.datetime(2008, 1, 5, 9, 0)),
                (1,
                 datetime.datetime(2008, 1, 12, 8, 0),
                 datetime.datetime(2008, 1, 12, 9, 0)),
                (1,
                 datetime.datetime(2008, 1, 19, 8, 0),
                 datetime.datetime(2008, 1, 19, 9, 0))
            ])

    def test_has_occurrence(self):
        self.assert_(self.period.has_occurrences())
        slot = self.period.get_time_slot(datetime.datetime(2008, 1, 4, 7, 0),
                                         datetime.datetime(2008, 1, 4, 7, 12))
        self.failIf(slot.has_occurrences())
Ejemplo n.º 21
0
    def test_occurrences_sub_period_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)

        sub_start = self.MVD.localize(datetime.datetime(2017, 1, 13))
        sub_end = self.MVD.localize(datetime.datetime(2017, 1, 15))
        sub_period = period.get_time_slot(sub_start, sub_end)
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in sub_period.occurrences],
            ['2017-01-14 22:00:00-03:00 to 2017-01-14 23:00:00-03:00'])
Ejemplo n.º 22
0
 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 ''
Ejemplo n.º 23
0
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))
Ejemplo n.º 24
0
class TestPeriod(TestCase):
    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 test_get_occurrences(self):
        occurrence_list = self.period.occurrences
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in occurrence_list],
            [
                "2008-01-05 08:00:00 to 2008-01-05 09:00:00",
                "2008-01-12 08:00:00 to 2008-01-12 09:00:00",
                "2008-01-19 08:00:00 to 2008-01-19 09:00:00",
            ],
        )

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual(
            [
                (occ_dict["class"], occ_dict["occurrence"].start, occ_dict["occurrence"].end)
                for occ_dict in occurrence_dicts
            ],
            [
                (1, datetime.datetime(2008, 1, 5, 8, 0), datetime.datetime(2008, 1, 5, 9, 0)),
                (1, datetime.datetime(2008, 1, 12, 8, 0), datetime.datetime(2008, 1, 12, 9, 0)),
                (1, datetime.datetime(2008, 1, 19, 8, 0), datetime.datetime(2008, 1, 19, 9, 0)),
            ],
        )

    def test_has_occurrence(self):
        self.assert_(self.period.has_occurrences())
        slot = self.period.get_time_slot(datetime.datetime(2008, 1, 4, 7, 0), datetime.datetime(2008, 1, 4, 7, 12))
        self.failIf(slot.has_occurrences())
Ejemplo n.º 25
0
 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())
     # trigger bug discovered by gautamadude - modifying recurring event
     # breaks link between a persistent occurrence and the occurrence chain
     # leaving an "orphaned" occurrence
     occurrences = self.recurring_event.get_occurrences(start=self.start,
                                 end=self.end)
     self.assertTrue(len(occurrences) == 3)
     self.recurring_event.start = datetime.datetime(2008, 1, 5, 8, 15)
     self.recurring_event.save()
     occurrences_later = self.recurring_event.get_occurrences(start=self.start,
                                 end=self.end)
     self.assertEquals(len(occurrences_later), len(occurrences))
Ejemplo n.º 26
0
 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))
Ejemplo n.º 27
0
 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))
Ejemplo n.º 28
0
    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')

        Event.objects.create(
            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,
        )
        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):
        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(frequency='WEEKLY')
        rule.save()
        self.cal = Calendar(name='MyCal', slug='MyCalSlug')
        self.cal.save()

        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,
        }
        recurring_event = Event(**data)
        recurring_event.save()
        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))
Ejemplo n.º 30
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}
Ejemplo n.º 31
0
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")
Ejemplo n.º 32
0
class TestPeriod(TestCase):
    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 test_get_occurrences(self):
        occurrence_list = self.period.occurrences
        self.assertEqual(
            ["%s to %s" % (o.start, o.end) for o in occurrence_list], [
                '2008-01-05 08:00:00 to 2008-01-05 09:00:00',
                '2008-01-12 08:00:00 to 2008-01-12 09:00:00',
                '2008-01-19 08:00:00 to 2008-01-19 09:00:00'
            ])

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual([(occ_dict["class"], occ_dict["occurrence"].start,
                           occ_dict["occurrence"].end)
                          for occ_dict in occurrence_dicts],
                         [(1, datetime.datetime(2008, 1, 5, 8, 0),
                           datetime.datetime(2008, 1, 5, 9, 0)),
                          (1, datetime.datetime(2008, 1, 12, 8, 0),
                           datetime.datetime(2008, 1, 12, 9, 0)),
                          (1, datetime.datetime(2008, 1, 19, 8, 0),
                           datetime.datetime(2008, 1, 19, 9, 0))])

    def test_has_occurrence(self):
        self.assert_(self.period.has_occurrences())
        slot = self.period.get_time_slot(datetime.datetime(2008, 1, 4, 7, 0),
                                         datetime.datetime(2008, 1, 4, 7, 12))
        self.failIf(slot.has_occurrences())
Ejemplo n.º 33
0
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))
Ejemplo n.º 34
0
 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))
Ejemplo n.º 35
0
 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')
Ejemplo n.º 36
0
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,
    }
Ejemplo n.º 37
0
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")
Ejemplo n.º 38
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
Ejemplo n.º 39
0
    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',
            ])
Ejemplo n.º 40
0
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")
Ejemplo n.º 41
0
    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 []
Ejemplo n.º 42
0
Archivo: api.py Proyecto: somair/zorna
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
Ejemplo n.º 43
0
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
Ejemplo n.º 44
0
    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 []
Ejemplo n.º 45
0
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())
Ejemplo n.º 46
0
    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
Ejemplo n.º 47
0
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
Ejemplo n.º 48
0
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")
Ejemplo n.º 49
0
    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
Ejemplo n.º 50
0
 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))
Ejemplo n.º 51
0
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
Ejemplo n.º 52
0
 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))
Ejemplo n.º 53
0
class TestTemplateTags(TestCase):
    def setUp(self):
        self.day = Day(events=Event.objects.all(),
                       date=datetime.datetime(2008, 2, 7, 0, 0, tzinfo=pytz.utc))
        rule = Rule(frequency="WEEKLY")
        rule.save()
        self.cal = Calendar(name="MyCal", slug="MyCalSlug")
        self.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': self.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_querystring_for_datetime(self):
        date = datetime.datetime(2008, 1, 1, 0, 0, 0)
        query_string = querystring_for_date(date, autoescape=True)
        self.assertEqual(escape("?year=2008&month=1&day=1&hour=0&minute=0&second=0"),
            query_string)

    def test_prev_url(self):
        query_string = prev_url("month_calendar", 'MyCalSlug', self.day)
        expected = ("/calendar/month/MyCalSlug/?year=2008&month=2&day=6&hour=0"
                    "&minute=0&second=0")
        self.assertEqual(query_string, escape(expected))

    def test_next_url(self):
        query_string = next_url("month_calendar", 'MyCalSlug', self.day)
        expected = ("/calendar/month/MyCalSlug/?year=2008&month=2&day=8&hour=0"
                    "&minute=0&second=0")
        self.assertEqual(query_string, escape(expected))

    def test_create_event_url(self):
        context = {}
        slot = self.period.get_time_slot(datetime.datetime(2010, 1, 4, 7, 0, tzinfo=pytz.utc),
                                         datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc))
        query_string = create_event_url(context, self.cal, slot.start)
        expected = ("/event/create/MyCalSlug/?year=2010&month=1&day=4&hour=7"
                    "&minute=0&second=0")
        self.assertEqual(query_string['create_event_url'], escape(expected))
Ejemplo n.º 54
0
 def setUp(self):
     rule = Rule.objects.create(frequency="WEEKLY")
     cal = Calendar.objects.create(name="MyCal")
     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,
     }
     Event.objects.create(**data)
     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))
Ejemplo n.º 55
0
class TestTemplateTags(TestCase):
    def setUp(self):
        self.day = Day(events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 0, 0, tzinfo=pytz.utc))
        rule = Rule(frequency="WEEKLY")
        rule.save()
        self.cal = Calendar(name="MyCal", slug="MyCalSlug")
        self.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": self.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_querystring_for_datetime(self):
        date = datetime.datetime(2008, 1, 1, 0, 0, 0)
        query_string = querystring_for_date(date, autoescape=True)
        self.assertEqual(escape("?year=2008&month=1&day=1&hour=0&minute=0&second=0"), query_string)

    def test_prev_url(self):
        query_string = prev_url("month_calendar", "MyCalSlug", self.day)
        expected = "/calendar/month/MyCalSlug/?year=2008&month=2&day=6&hour=0" "&minute=0&second=0"
        self.assertEqual(query_string, escape(expected))

    def test_next_url(self):
        query_string = next_url("month_calendar", "MyCalSlug", self.day)
        expected = "/calendar/month/MyCalSlug/?year=2008&month=2&day=8&hour=0" "&minute=0&second=0"
        self.assertEqual(query_string, escape(expected))

    def test_create_event_url(self):
        context = {}
        slot = self.period.get_time_slot(
            datetime.datetime(2010, 1, 4, 7, 0, tzinfo=pytz.utc), datetime.datetime(2008, 1, 4, 7, 12, tzinfo=pytz.utc)
        )
        query_string = create_event_url(context, self.cal, slot.start)
        expected = "/event/create/MyCalSlug/?year=2010&month=1&day=4&hour=7" "&minute=0&second=0"
        self.assertEqual(query_string["create_event_url"], escape(expected))
Ejemplo n.º 56
0
 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())
Ejemplo n.º 57
0
class TestPeriod(TestCase):

    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 test_get_occurences(self):
        occurrence_list = self.period.occurrences
        self.assertEqual(["%s to %s" %(o.start, o.end) for o in occurrence_list],
            ['2008-01-05 08:00:00 to 2008-01-05 09:00:00',
             '2008-01-12 08:00:00 to 2008-01-12 09:00:00',
             '2008-01-19 08:00:00 to 2008-01-19 09:00:00'])

    def test_get_occurrence_partials(self):
        occurrence_dicts = self.period.get_occurrence_partials()
        self.assertEqual(
            [(occ_dict["class"],
            occ_dict["occurrence"].start,
            occ_dict["occurrence"].end)
            for occ_dict in occurrence_dicts],
            [
                (1,
                 datetime.datetime(2008, 1, 5, 8, 0),
                 datetime.datetime(2008, 1, 5, 9, 0)),
                (1,
                 datetime.datetime(2008, 1, 12, 8, 0),
                 datetime.datetime(2008, 1, 12, 9, 0)),
                (1,
                 datetime.datetime(2008, 1, 19, 8, 0),
                 datetime.datetime(2008, 1, 19, 9, 0))
            ])
Ejemplo n.º 58
0
 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),
     )