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))
    def setUp(self):
        weekly = Rule(frequency="WEEKLY")
        weekly.save()
        daily = Rule(frequency="DAILY")
        daily.save()
        cal = Calendar(name="MyCal")
        cal.save()

        self.event1 = Event(**{
            'title': 'Weekly Event',
            'start': datetime.datetime(2009, 4, 1, 8, 0),
            'end': datetime.datetime(2009, 4, 1, 9, 0),
            'end_recurring_period': datetime.datetime(2009, 10, 5, 0, 0),
            'rule': weekly,
            'calendar': cal
        })
        self.event1.save()
        self.event2 = Event(**{
            'title': 'Recent Event',
            'start': datetime.datetime(2008, 1, 5, 9, 0),
            'end': datetime.datetime(2008, 1, 5, 10, 0),
            'end_recurring_period': datetime.datetime(2009, 5, 5, 0, 0),
            'rule': daily,
            'calendar': cal
        })
        self.event2.save()
class TestOccurrencePool(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, 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.recurring_event = Event(**data)
        self.recurring_event.save()

    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)
class TestAwareDay(TestCase):
    def setUp(self):
        self.timezone = pytz.timezone('Europe/Amsterdam')

        start = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 20))
        end = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 21))
        self.event = Event(
            title='One minute long event on january seventh 2008 at 00:20 in Amsterdam.',
            start=start,
            end=end,
        )
        self.event.save()

        self.day = Day(
            events=Event.objects.all(),
            date=self.timezone.localize(datetime.datetime(2008, 2, 7, 9, 0)),
            tzinfo=self.timezone,
        )

    def test_day_range(self):
        start = datetime.datetime(2008, 2, 6, 23, 0, tzinfo=pytz.utc)
        end = datetime.datetime(2008, 2, 7, 23, 0, tzinfo=pytz.utc)

        self.assertEqual(start, self.day.start)
        self.assertEqual(end, self.day.end)

    def test_occurence(self):
        self.assertEqual(self.event in [o.event for o in self.day.occurrences], True)
Beispiel #5
0
 def test_recurring_event_get_occurrences(self):
     recurring_event = Event(**self.recurring_data)
     recurring_event.save()
     occurrences = recurring_event.get_occurrences(start=datetime.datetime(2008, 1, 12, 0, 0),
                                 end=datetime.datetime(2008, 1, 20, 0, 0))
     self.assertEquals(["%s to %s" %(o.start, o.end) for o in occurrences],
         ['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'])
Beispiel #6
0
    def add_new(self, user):
        try:
            client = Client.objects.get(pk=self.cleaned_data["client"])

            if client.phone:
                event_title = "{name} {phone} {id}".format(
                    name=client.get_full_name(), phone=client.phone, id=client.client_id
                )
            else:
                event_title = "{name} {id}".format(name=client.get_full_name(), id=client.client_id)

            event = Event(
                start=parser.parse(self.cleaned_data["start_datetime"]),
                end=parser.parse(self.cleaned_data["end_datetime"]),
                title=event_title,
                creator=user,
            )
            event.save()
            appointment = Appointment(
                client=client,
                venue=Venue.objects.get(pk=self.cleaned_data["venue_id"]),
                event=event,
                creator=user,
                customer=user.userprofile.customer,
            )
            appointment.save()
            return appointment
        except Client.DoesNotExist:
            return False
Beispiel #7
0
 def test_event_get_occurrences_after(self):
     recurring_event=Event(**self.recurring_data)
     recurring_event.save()
     occurrences = recurring_event.get_occurrences(start=datetime.datetime(2008, 1, 5),
         end = datetime.datetime(2008, 1, 6))
     occurrence = occurrences[0]
     occurrence2 = recurring_event.occurrences_after(datetime.datetime(2008,1,5)).next()
     self.assertEqual(occurrence, occurrence2)
Beispiel #8
0
    def test_event_get_occurrences(self):
        event= Event(**self.data)
        event.save()
        occurrences = event.get_occurrences(start=datetime.datetime(2008, 1, 12, 0, 0),
                                    end=datetime.datetime(2008, 1, 20, 0, 0))

        self.assertEquals(["%s to %s" %(o.start, o.end) for o in occurrences],
            [])
Beispiel #9
0
 def test_get_occurrence(self):
     event = Event(**self.recurring_data)
     event.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertEqual(occurrence.start, datetime.datetime(2008,1,5,8))
     occurrence.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertTrue(occurrence.pk is not None)
Beispiel #10
0
class TestEventViews(LoggedInTestCase):

    def setUp(self):
        super(TestEventViews, self).setUp()
        self.cal = Calendar(
            name=random_string(),
            slug=random_string(),
        )
        self.cal.save()
        self.event = Event(
            start=timezone.now(),
            end=timezone.now() + timedelta(weeks=6),
            title=random_string(),
            calendar=self.cal,
        )
        self.event.save()

    def tearDown(self):
        super(TestEventViews, self).tearDown()
        try:
            self.cal.delete()
            self.event.delete()
        except:
            pass

    def test_event_can_be_recurring(self):
        rule = Rule(
            name=random_string(),
            description=random_string(),
            frequency='WEEKLY',
        )
        rule.save()
        try:
            url = reverse(
                'openduty.events.create_or_edit_event',
                kwargs = {
                    'calendar_slug': self.cal.slug,
                    'event_id': str(self.event.id),
                },
            )
            response = self.client.post(
                path = url,
                data = {
                    "start_0": self.event.start.strftime('%Y-%m-%d'),
                    "start_1": "09:00",
                    "end_0": self.event.end.strftime('%Y-%m-%d'),
                    "end_1": "23:00",
                    "description": "desc",
                    "rule": str(rule.id),
                    "oncall": "foo",
                    "fallback": "bar",
                },
            )
            self.assertEqual(302, response.status_code)
            e = Event.objects.get(id=self.event.id)
            self.assertEqual(rule, e.rule)
        finally:
            rule.delete()
 def test_recurring_event_get_occurrences(self):
     recurring_event = Event(**self.recurring_data)
     start = datetime.datetime(2008, 1, 12, 0, 0)
     end = datetime.datetime(2008, 1, 20, 0, 0)
     occurrences = recurring_event.get_occurrences(start=start, end=end)
     expected = [
         '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.assertEquals(["%s to %s" % (o.start, o.end) for o in occurrences], expected)
Beispiel #12
0
 def create_event(self, user):
     start = parser.parse(self.cleaned_data["start_datetime"])
     end = parser.parse(self.cleaned_data["end_datetime"])
     new_event = Event(
         start=start,
         end=end,
         title=self.cleaned_data["title"],
         description=self.cleaned_data["description"],
         creator=user,
     )
     new_event.save()
     return new_event
Beispiel #13
0
 def test_get_escalation_fails_with_no_recurrence_after_event_end(self):
     event = Event(
         start = timezone.now() - timedelta(days=2),
         end = timezone.now() - timedelta(days=1),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
     )
     event.save()
     try:
         events = get_escalation_for_service(self.service)
         self.assertEqual(0, len(events))
     finally:
         event.delete()
Beispiel #14
0
 def test_get_escalation_returns_empty_for_muted_services(self):
     event = Event(
         start = timezone.now() - timedelta(days=1),
         end = timezone.now() + timedelta(days=1),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
     )
     event.save()
     self.service.notifications_disabled = True
     try:
         events = get_escalation_for_service(self.service)
         self.assertEqual(0, len(events))
     finally:
         event.delete()
Beispiel #15
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.month = Month(events=Event.objects.all(),
                        date=datetime.datetime(2008, 2, 7, 9, 0))
    def test_edge_case_events(self):
        cal = Calendar(name="MyCal")
        cal.save()
        data_1 = {
            'title': 'Edge case event test one',
            'start': datetime.datetime(2013, 1, 5, 8, 0, tzinfo=pytz.utc),
            'end': datetime.datetime(2013, 1, 5, 9, 0, tzinfo=pytz.utc),
            'calendar': cal
        }
        data_2 = {
            'title': 'Edge case event test two',
            'start': datetime.datetime(2013, 1, 5, 9, 0, tzinfo=pytz.utc),
            'end': datetime.datetime(2013, 1, 5, 12, 0, tzinfo=pytz.utc),
            'calendar': cal
        }
        event_one = Event(**data_1)
        event_two = Event(**data_2)
        event_one.save()
        event_two.save()
        occurrences_two = event_two.get_occurrences(datetime.datetime(2013, 1, 5, 9, 0, tzinfo=pytz.utc),
                                                    datetime.datetime(2013, 1, 5, 12, 0, tzinfo=pytz.utc))
        self.assertEqual(1, len(occurrences_two))

        occurrences_one = event_one.get_occurrences(datetime.datetime(2013, 1, 5, 9, 0, tzinfo=pytz.utc),
                                                    datetime.datetime(2013, 1, 5, 12, 0, tzinfo=pytz.utc))
        self.assertEqual(0, len(occurrences_one))
Beispiel #17
0
 def make_occurrences(self, rule):
     cal = Calendar.objects.get(name="MyCal")
     recurring_data = {
             'title': 'Recent Event',
             'start': datetime.datetime(2010, 1, 1, 8, 0),
             'end': datetime.datetime(2010, 1, 1, 9, 0),
             'end_recurring_period' : datetime.datetime(2010, 2, 1, 0, 0),
             'rule': rule,
             'calendar': cal
            }
     recurring_event = Event(**recurring_data)
     occurrences = recurring_event.get_occurrences(start=datetime.datetime(2010, 1, 1, 0, 0),
                                 end=datetime.datetime(2010, 2, 1, 0, 0))
     return [o.start.day for o in occurrences]
class TestOccurrence(TestCase):
    def setUp(self):
        rule = Rule(frequency = "WEEKLY")
        rule.save()
        self.recurring_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,
               }
        self.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),
               }
        self.recurring_event = Event(**self.recurring_data)
        self.recurring_event.save()
        self.start = datetime.datetime(2008, 1, 12, 0, 0)
        self.end = datetime.datetime(2008, 1, 27, 0, 0)
    
    def test_presisted_occurrences(self):
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        persisted_occurrence = occurrences[0]
        persisted_occurrence.save()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        self.assertTrue(occurrences[0].pk)
        self.assertFalse(occurrences[1].pk)
    
    def test_moved_occurrences(self):
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        moved_occurrence = occurrences[1]
        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)
    
    def test_cancelled_occurrences(self):
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        cancelled_occurrence = occurrences[2]
        cancelled_occurrence.cancel()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        self.assertTrue(occurrences[2].cancelled)
        cancelled_occurrence.uncancel()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                    end=self.end)
        self.assertFalse(occurrences[2].cancelled)
Beispiel #19
0
 def form_valid(self, form):
     meeting = form.save()
     end = meeting.start + datetime.timedelta(minutes=119)
     event = Event(
         start=meeting.start,
         end=end,
         title='{0} meeting'.format(meeting.entity.name),
         description=meeting.agenda,
         creator=self.request.user,
     )
     event.save()
     er = EventRelation.objects.create_relation(event, meeting)
     cal = Calendar.objects.get(name='civic')
     cal.events.add(event)
     return super(SchedulerSavingMixin, self).form_valid(form)
Beispiel #20
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),
         "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.month = Month(events=Event.objects.all(), date=datetime.datetime(2008, 2, 7, 9, 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.month = Month(events=Event.objects.all(),
                        date=datetime.datetime(2008, 2, 7, 9, 0, tzinfo=pytz.utc))
Beispiel #22
0
    def setUp(self):
        self.timezone = pytz.timezone('Europe/Amsterdam')

        start = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 20))
        end = self.timezone.localize(datetime.datetime(2008, 2, 7, 0, 21))
        self.event = Event(
            title=
            'One minute long event on january seventh 2008 at 00:20 in Amsterdam.',
            start=start,
            end=end,
        )
        self.event.save()

        self.day = Day(
            events=Event.objects.all(),
            date=self.timezone.localize(datetime.datetime(2008, 2, 7, 9, 0)),
            tzinfo=self.timezone,
        )
Beispiel #23
0
 def test_get_escalation_empty_when_recurrance_is_not_now(self):
     rule = Rule(
         name=random_string(),
         description=random_string(),
         frequency='WEEKLY',
     )
     rule.save()
     # Active yesterday, and 1 week from now, but not today
     event = Event(
         start = timezone.now() - timedelta(days=2),
         end = timezone.now() - timedelta(days=1),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
         rule = rule,
     )
     event.save()
     events = get_escalation_for_service(self.service)
     self.assertEqual(0, len(events))
Beispiel #24
0
 def test_get_escalation_works_when_recurrance_is_now(self):
     rule = Rule(
         name=random_string(),
         description=random_string(),
         frequency='WEEKLY',
     )
     rule.save()
     # Active last week at this time, recurring now
     event = Event(
         start = timezone.now() - timedelta(days=7, hours=5),
         end = timezone.now() + timedelta(hours=4) - timedelta(days=7),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
         rule = rule,
     )
     event.save()
     events = get_escalation_for_service(self.service)
     self.assertEqual(2, len(events))
Beispiel #25
0
 def __create_recurring_event(self, title, start, end, end_recurring, rule, cal):
      return Event(**{
             'title': title,
             'start': start,
             'end': end,
             'end_recurring_period' : end_recurring,
             'rule': rule,
             'calendar': cal
            })
Beispiel #26
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),
             '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))
Beispiel #27
0
    def setUp(self):
        weekly = Rule.objects.create(frequency="WEEKLY")
        daily = Rule.objects.create(frequency="DAILY")
        cal = Calendar.objects.create(name="MyCal")
        self.default_tzinfo = timezone.get_default_timezone()

        self.event1 = Event(
            **{
                'title':
                'Weekly Event',
                'start':
                datetime.datetime(2009, 4, 1, 8, 0,
                                  tzinfo=self.default_tzinfo),
                'end':
                datetime.datetime(2009, 4, 1, 9, 0,
                                  tzinfo=self.default_tzinfo),
                'end_recurring_period':
                datetime.datetime(
                    2009, 10, 5, 0, 0, tzinfo=self.default_tzinfo),
                'rule':
                weekly,
                'calendar':
                cal
            })
        self.event1.save()
        self.event2 = Event(
            **{
                'title':
                'Recent Event',
                'start':
                datetime.datetime(2008, 1, 5, 9, 0,
                                  tzinfo=self.default_tzinfo),
                'end':
                datetime.datetime(
                    2008, 1, 5, 10, 0, tzinfo=self.default_tzinfo),
                'end_recurring_period':
                datetime.datetime(2009, 5, 5, 0, 0,
                                  tzinfo=self.default_tzinfo),
                'rule':
                daily,
                'calendar':
                cal
            })
        self.event2.save()
 def __create_recurring_event(self, title, start, end, end_recurring, rule,
                              cal):
     return Event(
         title=title,
         start=start,
         end=end,
         end_recurring_period=end_recurring,
         rule=rule,
         calendar=cal,
     )
Beispiel #29
0
    def setUp(self):
        weekly = Rule.objects.create(frequency="WEEKLY")
        daily = Rule.objects.create(frequency="DAILY")
        cal = Calendar.objects.create(name="MyCal")
        self.default_tzinfo = timezone.get_default_timezone()
        self.start = datetime.datetime.now() - datetime.timedelta(days=10)
        self.end = self.start + datetime.timedelta(days=300)
        self.event1 = Event(
            **{
                'title': 'Weekly Event',
                'start': self.start,
                'end': self.end,
                'end_recurring_period': self.end,
                'rule': weekly,
                'calendar': cal
            })
        self.event1.save()
        self.occ = Occurrence(event=self.event1,
                              start=self.start,
                              end=self.end,
                              original_start=self.start,
                              original_end=self.end)
        self.occ.save()

        self.event2 = Event(
            **{
                'title':
                'Recent Event',
                'start':
                datetime.datetime(2008, 1, 5, 9, 0,
                                  tzinfo=self.default_tzinfo),
                'end':
                datetime.datetime(
                    2008, 1, 5, 10, 0, tzinfo=self.default_tzinfo),
                'end_recurring_period':
                datetime.datetime(2009, 5, 5, 0, 0,
                                  tzinfo=self.default_tzinfo),
                'rule':
                daily,
                'calendar':
                cal
            })
        self.event2.save()
    def test_all_day_event_cook_slots(self):
        cal = Calendar(name='MyCal', slug='MyCalSlug')
        cal.save()
        start = datetime.datetime(
            datetime.datetime.now().year, 1, 5, 0, 0, tzinfo=pytz.utc)
        end = datetime.datetime(
            datetime.datetime.now().year, 1, 6, 0, 0, tzinfo=pytz.utc)
        data = {
            'title': 'All Day Event',
            'start': start,
            'end': end,
            'calendar': self.cal,
        }
        event = Event(**data)
        event.save()
        period = Day([event], start, end)

        slots = _cook_slots(period, 60)
        self.assertEqual(len(slots), 24)
Beispiel #31
0
 def create_event(self, user):
     start = timezone.make_aware(
         parser.parse(
             "{} {}".format(self.cleaned_data["start_date"], self.cleaned_data["start_time"]), dayfirst=True
         ),
         timezone.get_current_timezone(),
     )
     end = timezone.make_aware(
         parser.parse("{} {}".format(self.cleaned_data["end_date"], self.cleaned_data["end_time"]), dayfirst=True),
         timezone.get_current_timezone(),
     )
     new_event = Event(
         start=start,
         end=end,
         title=self.cleaned_data["title"],
         description=self.cleaned_data["description"],
         creator=user,
     )
     new_event.save()
     return new_event
Beispiel #32
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),
     )
Beispiel #33
0
 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))
Beispiel #34
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
     }
     self.recurring_event = Event(**data)
     self.recurring_event.save()
Beispiel #35
0
    def form_valid(self, form):
        meeting = form.save()
        end = meeting.start + datetime.timedelta(minutes=119)
        event = Event(
            start=meeting.start,
            end=end,
            title=u'{0} meeting'.format(meeting.entity.name),
            description=meeting.agenda,
            creator=self.request.user,
        )
        event.save()
        er = EventRelation.objects.create_relation(event, meeting)
        er.save()
        try:
            cal = Calendar.objects.get(name='civic')
        except Calendar.DoesNotExist:
            error_msg = "Calendar object not found."
            raise Calendar.DoesNotExist(error_msg)

        cal.events.add(event)
        return super(MeetingCreateView, self).form_valid(form)
class TestEventListManager(TestCase):
    def setUp(self):
        weekly = Rule(frequency = "WEEKLY")
        weekly.save()
        daily = Rule(frequency = "DAILY")
        daily.save()
        cal = Calendar(name="MyCal")
        cal.save()

        self.event1 = Event(**{
                'title': 'Weekly Event',
                'start': datetime.datetime(2009, 4, 1, 8, 0),
                'end': datetime.datetime(2009, 4, 1, 9, 0),
                'end_recurring_period' : datetime.datetime(2009, 10, 5, 0, 0),
                'rule': weekly,
                'calendar': cal
               })
        self.event1.save()
        self.event2 = Event(**{
                'title': 'Recent Event',
                'start': datetime.datetime(2008, 1, 5, 9, 0),
                'end': datetime.datetime(2008, 1, 5, 10, 0),
                'end_recurring_period' : datetime.datetime(2009, 5, 5, 0, 0),
                'rule': daily,
                'calendar': cal
               })
        self.event2.save()

    def test_occurrences_after(self):
        eml = EventListManager([self.event1, self.event2])
        occurrences = eml.occurrences_after(datetime.datetime(2009,4,1,0,0))
        self.assertEqual(occurrences.next().event, self.event1)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event1)
class TestEventListManager(TestCase):
    def setUp(self):
        weekly = Rule.objects.create(frequency="WEEKLY")
        daily = Rule.objects.create(frequency="DAILY")
        cal = Calendar.objects.create(name="MyCal")
        self.default_tzinfo = timezone.get_default_timezone()

        self.event1 = Event(**{
            'title': 'Weekly Event',
            'start': datetime.datetime(2009, 4, 1, 8, 0, tzinfo=self.default_tzinfo),
            'end': datetime.datetime(2009, 4, 1, 9, 0, tzinfo=self.default_tzinfo),
            'end_recurring_period': datetime.datetime(2009, 10, 5, 0, 0, tzinfo=self.default_tzinfo),
            'rule': weekly,
            'calendar': cal
        })
        self.event1.save()
        self.event2 = Event(**{
            'title': 'Recent Event',
            'start': datetime.datetime(2008, 1, 5, 9, 0, tzinfo=self.default_tzinfo),
            'end': datetime.datetime(2008, 1, 5, 10, 0, tzinfo=self.default_tzinfo),
            'end_recurring_period': datetime.datetime(2009, 5, 5, 0, 0, tzinfo=self.default_tzinfo),
            'rule': daily,
            'calendar': cal
        })
        self.event2.save()

    def test_occurrences_after(self):
        eml = EventListManager([self.event1, self.event2])
        occurrences = eml.occurrences_after(datetime.datetime(2009, 4, 1, 0, 0, tzinfo=self.default_tzinfo))
        self.assertEqual(next(occurrences).event, self.event1)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event1)
        occurrences = eml.occurrences_after()
        self.assertEqual(list(occurrences), [])
Beispiel #38
0
class TestEventListManager(TestCase):
    def setUp(self):
        weekly = Rule(frequency="WEEKLY")
        weekly.save()
        daily = Rule(frequency="DAILY")
        daily.save()
        cal = Calendar(name="MyCal")
        cal.save()

        self.event1 = Event(**{
            'title': 'Weekly Event',
            'start': datetime.datetime(2009, 4, 1, 8, 0),
            'end': datetime.datetime(2009, 4, 1, 9, 0),
            'end_recurring_period': datetime.datetime(2009, 10, 5, 0, 0),
            'rule': weekly,
            'calendar': cal
        })
        self.event1.save()
        self.event2 = Event(**{
            'title': 'Recent Event',
            'start': datetime.datetime(2008, 1, 5, 9, 0),
            'end': datetime.datetime(2008, 1, 5, 10, 0),
            'end_recurring_period': datetime.datetime(2009, 5, 5, 0, 0),
            'rule': daily,
            'calendar': cal
        })
        self.event2.save()

    def test_occurrences_after(self):
        eml = EventListManager([self.event1, self.event2])
        occurrences = eml.occurrences_after(datetime.datetime(2009, 4, 1, 0, 0))
        self.assertEqual(occurrences.next().event, self.event1)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event2)
        self.assertEqual(occurrences.next().event, self.event1)
Beispiel #39
0
 def setUp(self):
     self.MVD = pytz.timezone('America/Montevideo')  # UTC-3
     cal = Calendar(name="MyCal")
     cal.save()
     rule = Rule(frequency="DAILY", name="daily")
     rule.save()
     data = {
         'title':
         'Test event',
         'start':
         self.MVD.localize(datetime.datetime(2017, 1, 13, 15, 0)),
         'end':
         self.MVD.localize(datetime.datetime(2017, 1, 14, 15, 0)),
         'end_recurring_period':
         self.MVD.localize(datetime.datetime(2017, 1, 20)),
         'rule':
         rule,
         'calendar':
         cal
     }
     recurring_event = Event(**data)
     recurring_event.save()
Beispiel #40
0
 def setUp(self):
     self.MVD = pytz.timezone('America/Montevideo')
     cal = Calendar(name="MyCal")
     cal.save()
     rule = Rule(frequency="DAILY", params="byweekday:SA", name="Saturdays")
     rule.save()
     data = {
         'title':
         'Every Saturday Event',
         'start':
         self.MVD.localize(datetime.datetime(2017, 1, 7, 22, 0)),
         'end':
         self.MVD.localize(datetime.datetime(2017, 1, 7, 23, 0)),
         'end_recurring_period':
         self.MVD.localize(datetime.datetime(2017, 2, 1)),
         'rule':
         rule,
         'calendar':
         cal
     }
     recurring_event = Event(**data)
     recurring_event.save()
Beispiel #41
0
 def test_get_occurrence(self):
     event = Event(**self.recurring_data)
     event.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertEqual(occurrence.start, datetime.datetime(2008, 1, 5, 8))
     occurrence.save()
     occurrence = event.get_occurrence(datetime.datetime(2008, 1, 5, 8, 0))
     self.assertTrue(occurrence.pk is not None)
Beispiel #42
0
 def perform_create(self, serializer):
     serializer.is_valid(raise_exception=True)
     appointment = serializer.save()
     date = appointment.date
     time = appointment.time
     contact = Contact.objects.get(pk=appointment.contact_id)
     consultant = User.objects.get(
         pk=appointment.consultant_id)  # FIXME consultant may be null
     _datetime = datetime.combine(date, time)
     period = Hour([], _datetime, tzinfo=pytz.timezone(settings.TIME_ZONE))
     event = Event(start=period.start,
                   end=period.end,
                   title=str(contact),
                   description=str(appointment.id),
                   calendar=Calendar.objects.get(pk=1),
                   creator=consultant)
     event.save()
     appointment_relation = EventRelation.objects.create_relation(
         event, appointment, 'appointment')
     consultant_relation = EventRelation.objects.create_relation(
         event, consultant, 'consultant')
     appointment_relation.save()
     consultant_relation.save()
     AppointmentView.send_notification(appointment, consultant, contact)
Beispiel #43
0
def external_add2(request):
    """
    """
    if request.method == 'POST':
        form = IdForm(request.POST)
        if form.is_valid():
            cd = request.session.get('form1')
            ts = TimeSlot.objects.get(pk=cd['dateTime'])
            u = User.objects.get(username='******')
            e = Event(owner=u,
                      date=ts.date,
                      begin_time=ts.begin_time,
                      description='WEB: ' + form.cleaned_data['name'])
            e.save()
            return HttpResponseRedirect(reverse('appointments.views.external_add3'))
        else:
            print form.errors
    else:
        form = IdForm()

    return render_to_response('mockup2.templ',
    # return render_to_response('get_appointment2.templ',
                              {'id_form': form, },
                               context_instance=RequestContext(request))
Beispiel #44
0
def create_week(request):
    if request.is_ajax():
        to_monday = date.today().weekday()
        start = date.today() - datetime.timedelta(days=to_monday) #Find Monday
        day = start # Day will change, start will not
        end = start + datetime.timedelta(days=4)  # One week, edit later for flexibility
        weekend = set([5, 6])  # Python week starts on Monday as 0
        dupe_list = []
        total = 0
        while day <= end:
                if day.weekday() not in weekend:
                    for period in period_choices:
                        for cart in cart_choice:
                            open = Event(day=day, period=period[0], cart=cart[0])
                            try:
                                open.save()
                                total+=1
                            except IntegrityError:
                                dupe = str(open)
                                dupe_list.append(dupe)
                                pass
                day += datetime.timedelta(days=1)  # Adds one day until the current day is past the end day
        data = {'start': start, 'end': end, 'dupe_list': dupe_list, 'total': total}
        return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))
Beispiel #45
0
 def test_create_get(self):
     p = Parent(first_name=self.parent_first_name,
                 last_name=self.parent_last_name,
                 deleted=False)
     p.save()
     c = Child(first_name=self.first_name,
               last_name=self.last_name,
               deleted=False)
     c.save()
     c.parents.add(p)
     a = Activity(name=self.name)
     a.save()
     color = Color(name=self.color)
     color.save()
     expected = Event(child=c,
                      created=self.created,
                      name=a,
                      color=color,
                      count=self.count,
                      deleted=False)
     expected.save()
     expected.parents.add(p)
     actual = Event.objects.get(id=expected.id)
     self.assertEqual(expected.id, actual.id)
Beispiel #46
0
 def test_event_get_occurrences_after(self):
     recurring_event = Event(**self.recurring_data)
     recurring_event.save()
     occurrences = recurring_event.get_occurrences(
         start=datetime.datetime(2008, 1, 5),
         end=datetime.datetime(2008, 1, 6))
     occurrence = occurrences[0]
     occurrence2 = recurring_event.occurrences_after(
         datetime.datetime(2008, 1, 5)).next()
     self.assertEqual(occurrence, occurrence2)
Beispiel #47
0
    def forms_valid(self, forms):
        forms['poster_form'].save()
        date = forms['date_form'].save()
        info = forms['show_info_form'].save(commit=False)

        if self.request.FILES.get('image'):
            info.poster, created = Image.objects.get_or_create(
                image=self.request.FILES.get('image'),
                title="Poster",
                user=self.request.user)
        elif self.request.POST.get('poster'):
            imageId = self.request.POST.get('poster')
            info.poster = get_object_or_None(Image, id=imageId)

        if not info.location:
            if info.venue_id:
                info.location = info.venue.profile.contact_info.location
            else:
                info.location = self.request.user.profile.contact_info.location
        info.save()
        forms['show_info_form'].save_m2m()
        participants = info.participants()
        thread = create_thread(
            participants=participants,
            sender=self.request.user,
            subject="Event Thread",
            body=str(self.request.user.profile) + " added you in an event",
        )
        show = Show(info=info, date=date, thread=thread, approved=False)
        show.save()

        # create or edit event for each particpent in show
        for user in participants:
            if self.request.user != user:
                event = get_object_or_None(Event,
                                           show=show,
                                           calendar=user.calendar)
                if not event:
                    event = Event(show=show, calendar=user.calendar)
            else:
                event = forms['event_form'].save(commit=False)
                event.show = show
                event.calendar = user.calendar
                event.approved = True
            event.save()
        show.save()
        return self.get_success_url()
 def test_get_escalation_fails_with_no_recurrence_after_event_end(self):
     event = Event(
         start = timezone.now() - timedelta(days=2),
         end = timezone.now() - timedelta(days=1),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
     )
     event.save()
     try:
         events = get_escalation_for_service(self.service)
         self.assertEqual(0, len(events))
     finally:
         event.delete()
Beispiel #49
0
def run():
    to_monday = date.today().weekday()
    start = date.today() - datetime.timedelta(days=to_monday)  #Find Monday
    day = start  # Day will change, start will not
    end = start + datetime.timedelta(
        days=7)  # One week, edit later for flexibility
    weekend = set([5, 6])  # Python week starts on Monday as 0
    total = 0
    while start <= end:
        if start.weekday() not in weekend:
            for period in period_choices:
                for cart in cart_choice:
                    open = Event(day=day, period=period[0], cart=cart[0])
                    print(open)
                    total += 1
            start += datetime.timedelta(
                days=1
            )  # Adds one day until the current day is past the end day
            print(day)
 def test_get_escalation_returns_empty_for_muted_services(self):
     event = Event(
         start = timezone.now() - timedelta(days=1),
         end = timezone.now() + timedelta(days=1),
         title = '{username},{username}'.format(username=self.username),
         calendar = self.cal,
     )
     event.save()
     self.service.notifications_disabled = True
     try:
         events = get_escalation_for_service(self.service)
         self.assertEqual(0, len(events))
     finally:
         event.delete()
Beispiel #51
0
def borrowSubmit(request):
    date = request.POST.getlist('date')
    time = request.POST.getlist('time')
    team = request.POST.get('teamname')
    club = request.POST.get('club')
    # Jul 13, 2018 12:30 PM
    start = datetime.datetime.strptime(date[0] + ' ' + time[0],
                                       '%b %d, %Y %I:%M %p')
    end = datetime.datetime.strptime(date[1] + ' ' + time[1],
                                     '%b %d, %Y %I:%M %p')
    color = random.choice(color_set)
    if end < start:
        return render_to_response(
            'error.html', {
                'error_name': '시간설정 오류!',
                'error_msg': error_msg_dict['time_err'],
                'prev_page': '/borrow'
            })

    url = '/timetable'

    events = []

    for slug in slugs:
        if slug != 'DEFAULT':
            color = others_color
        events.append(
            Event(
                calendar=Calendar.objects.get(slug=slug),
                title=team,
                start=start,
                end=end,
                color_event=color,
                creator=UserModel.objects.get(username=club),
            ))

    for event in events:
        event.save()

    return HttpResponseRedirect(url)
Beispiel #52
0
def change_meeting(request):
    #print("come here")
    meetingid = request.POST.get('id')
    meeting = Meeting.objects.get(id=meetingid)
    # delete original meeting event relationship and events
    #mres = MeetingEventRelationship.objects.filter(meeting=meeting)
    #for mre in mres:
     #   event = mre.event
     #   event.delete()
     #   mre.delete()
    description = "Notice! Meeting information is changed !! Please decide whether  \
                you will attend again!! (original meeting event is deleted automatically)\n"

    _deletemeeting(meeting)
    group_name = request.POST.get('group_name')
    group = Group.objects.get(name=group_name)
    admin = group.admin
    title = request.POST.get('changed_title')
    description += request.POST.get('changed_description')
    start_time = request.POST.get('changed_start_time')
    end_time = request.POST.get('changed_end_time')

    meeting = Meeting(group=group, title=title, description=description,
                      start_time=start_time, end_time=end_time)
    meeting.save()

    event = Event(title=meeting.title,
                  description=meeting.description, start=meeting.start_time, end=meeting.end_time)
    event.creator = admin
    calendar = Calendar.objects.get(slug=admin.username)
    event.calendar = calendar
    event.save()
    mer = MeetingEventRelationship(meeting=meeting, event=event)
    mer.save()

    memberlist = find_all_members(group, True)
    result = 'true'
    for member in memberlist:
        if member == admin:
            continue
        status = sendmeetinginvitation(admin, member, group, meeting)
        if status is False:
            result = 'false'
    data = {'valid': result}
    data = json.dumps(data)
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
Beispiel #53
0
def add_meeting(request):
    group_name = request.POST.get('group_name')
    title = request.POST.get('title')
    description = request.POST.get('description')
    start_time = request.POST.get('start_time')
    end_time = request.POST.get('end_time')
    group = Group.objects.get(name=group_name)
    admin = group.admin
    #find time convertor
    ##save this meeting into meeting table
    meeting = Meeting(group=group, title=title,
                      description=description, start_time=start_time, end_time=end_time)
    meeting.save()
    #bai! save event for the admin
    event = Event(title=title, description=description, start=start_time, end=end_time)
    event.creator = admin
    calendar = Calendar.objects.get(slug=admin.username)
    event.calendar = calendar
    event.save()
    #bai! save meetingeventrelationship for admin
    mer = MeetingEventRelationship(meeting=meeting, event=event)
    mer.save()

    ##send invitation to all member
    ###find all member
    memberlist = find_all_members(group, True)
    result = 'false'
    for member in memberlist:
        if member == admin:
            continue
        status = sendmeetinginvitation(admin, member, group, meeting)
        if status == True:
            result = 'true'
        else:
            result = 'false'
    data = {'valid': result}
    data = json.dumps(data)
    mimetype = 'application/json'
    return HttpResponse(data, mimetype)
Beispiel #54
0
    def handle_noargs(self, **options):
        import datetime
        from schedule.models import Calendar
        from schedule.models import Event
        from schedule.models import Rule

        print "checking for existing data ..."
        try:
            cal = Calendar.objects.get(name="Example Calendar")
            print "It looks like you already have loaded this sample data, quitting."
            import sys
            sys.exit(1)
        except Calendar.DoesNotExist:
            print "Sample data not found in db."
            print "Install it..."

        print "Create Example Calendar ..."
        cal = Calendar(name="Example Calendar", slug="example")
        cal.save()
        print "The Example Calendar is created."
        print "Do we need to install the most common rules?"
        try:
            rule = Rule.objects.get(name="Daily")
        except Rule.DoesNotExist:
            print "Need to install the basic rules"
            rule = Rule(frequency="YEARLY",
                        name="Yearly",
                        description="will recur once every Year")
            rule.save()
            print "YEARLY recurrence created"
            rule = Rule(frequency="MONTHLY",
                        name="Monthly",
                        description="will recur once every Month")
            rule.save()
            print "Monthly recurrence created"
            rule = Rule(frequency="WEEKLY",
                        name="Weekly",
                        description="will recur once every Week")
            rule.save()
            print "Weekly recurrence created"
            rule = Rule(frequency="DAILY",
                        name="Daily",
                        description="will recur once every Day")
            rule.save()
            print "Daily recurrence created"
        print "Rules installed."

        print "Create some events"
        rule = Rule.objects.get(frequency="WEEKLY")
        data = {
            'title': 'Exercise',
            'start': datetime.datetime(2008, 11, 3, 8, 0),
            'end': datetime.datetime(2008, 11, 3, 9, 0),
            'end_recurring_period': datetime.datetime(2009, 6, 1, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        data = {
            'title': 'Exercise',
            'start': datetime.datetime(2008, 11, 5, 15, 0),
            'end': datetime.datetime(2008, 11, 5, 16, 30),
            'end_recurring_period': datetime.datetime(2009, 6, 1, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        data = {
            'title': 'Exercise',
            'start': datetime.datetime(2008, 11, 7, 8, 0),
            'end': datetime.datetime(2008, 11, 7, 9, 30),
            'end_recurring_period': datetime.datetime(2009, 6, 1, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        rule = Rule.objects.get(frequency="MONTHLY")
        data = {
            'title': 'Pay Mortgage',
            'start': datetime.datetime(2008, 11, 1, 14, 0),
            'end': datetime.datetime(2008, 11, 1, 14, 30),
            'end_recurring_period': datetime.datetime(2009, 10, 2, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        rule = Rule.objects.get(frequency="YEARLY")
        data = {
            'title': "Rock's Birthday Party",
            'start': datetime.datetime(2008, 12, 11, 19, 0),
            'end': datetime.datetime(2008, 12, 11, 23, 59),
            'end_recurring_period': datetime.datetime(2009, 12, 22, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        data = {
            'title': 'Christmas Party',
            'start': datetime.datetime(2008, 12, 25, 19, 30),
            'end': datetime.datetime(2008, 12, 25, 23, 59),
            'end_recurring_period': datetime.datetime(2010, 12, 31, 0, 0),
            'rule': rule,
            'calendar': cal
        }
        event = Event(**data)
        event.save()

        data = {
            'title': 'New Pinax site goes live',
            'start': datetime.datetime(2009, 1, 6, 11, 0),
            'end': datetime.datetime(2009, 1, 6, 12, 00),
            'end_recurring_period': datetime.datetime(2009, 1, 7, 0, 0),
            'calendar': cal
        }
        event = Event(**data)
        event.save()
Beispiel #55
0
def create_or_edit_event(request, country, calendar_slug, event_id=None, next=None, template_name='schedule/create_event.html', form_class=EventForm):
    """
    This function, if it receives a GET request or if given an invalid form in a
    POST request it will generate the following response

    Template:
        schedule/create_event.html

    Context Variables:

    form:
        an instance of EventForm

    calendar:
        a Calendar with id=calendar_id

    if this function gets a GET request with ``year``, ``month``, ``day``,
    ``hour``, ``minute``, and ``second`` it will auto fill the form, with
    the date specifed in the GET being the start and 30 minutes from that
    being the end.

    If this form receives an event_id it will edit the event with that id, if it
    recieves a calendar_id and it is creating a new event it will add that event
    to the calendar with the id calendar_id

    If it is given a valid form in a POST request it will redirect with one of
    three options, in this order

    # Try to find a 'next' GET variable
    # If the key word argument redirect is set
    # Lastly redirect to the event detail of the recently create event
    """
    user = request.user
    
    if country=='event':
        print()
    else:
        country = get_object_or_404(CountryPage, name=country)
    
    
    date = coerce_date_dict(request.GET)
    initial_data = None
    if date:
        try:
            start = datetime.datetime(**date)
            initial_data = {
                "start": start,
                "end": start + datetime.timedelta(minutes=30)
            }
        except TypeError:
            raise Http404
        except ValueError:
            raise Http404

    instance = None
    issues = None
    
    is_contryeevent=0
    is_secretariat=0
    is_contryeditor=0
    is_contryeditor_1=0
    can_add_edit=0
      
    if user.groups.filter(name='IPPC Secretariat'):
        is_secretariat=1
    if user.groups.filter(name='Country editor'):
        is_contryeditor=1
    if user.groups.filter(name='Country Contact Points'):
        is_contryeditor=1
    issueform =IssueKeywordsRelateForm(request.POST)
    calendar = get_object_or_404(Calendar, slug=calendar_slug)
    userprofile = get_object_or_404(IppcUserProfile, user_id=user.id)
  
    
    if event_id is not None:
        instance = get_object_or_404(Event, id=event_id)
        
      
        if user.groups.filter(name='Country editor') and (instance.country==userprofile.country):
            is_contryeditor_1=1
            can_add_edit=1  
        if instance.country.id!=-1 :
            is_contryeevent=1
        if (is_secretariat==1 and is_contryeevent==0):
            can_add_edit=1       
        if instance.issuename.count()>0:
            issues = get_object_or_404(IssueKeywordsRelate, pk=instance.issuename.all()[0].id)
            issueform =IssueKeywordsRelateForm(request.POST,instance=issues)
        else:
            issueform =IssueKeywordsRelateForm(request.POST)
 
    else:
        instance = Event()
        if is_contryeditor==1:
            can_add_edit=1
        if (is_secretariat==1):
            can_add_edit=1  
    form = form_class(data=request.POST or None, instance=instance, initial=initial_data)
  
        
    if request.method == "POST":
       f_form = EventFileFormSet(request.POST, request.FILES,instance=instance)
       u_form = EventUrlFormSet(request.POST, instance=instance)
       p_form = EventParticipantsFormSet(request.POST, instance=instance)
       #issueform =IssueKeywordsRelateForm(request.POST,instance=issues)
    else:
       # issueform =IssueKeywordsRelateForm(instance=issues)
       f_form = EventFileFormSet(instance=instance)
       u_form = EventUrlFormSet(instance=instance)
       p_form = EventParticipantsFormSet(instance=instance)
  
    if form.is_valid() and f_form.is_valid() and u_form.is_valid() and  p_form.is_valid():
        event = form.save(commit=False)
        event.start=event.start + datetime.timedelta(hours=12)

        if user.groups.filter(name='Country editor'):
            event.country=user.get_profile().country
        event.creator = request.user
        event.calendar = calendar
        event.save()
        form.save_m2m()
      
      
       
        issue_instance = issueform.save(commit=False)
        issue_instance.content_object = event
        issue_instance.save()
        issueform.save_m2m()
        
        f_form.instance = event
        f_form.save()
        u_form.instance = event
        u_form.save()
        p_form.instance = event
        p_form.save()
        
        if event_id is not None: 
            print('edit')
        else:
           print('new')#sendemail
           send_notificationevent_message(event.id)
     
        next = next or reverse('event', args=[event.id])
        #next = get_next_url(request, next)
        return HttpResponseRedirect(next)

    #next = get_next_url(request, next)
 
    #return render_to_response(template_name, {
    #    "form": form,
    #    "issueform": issueform,
    #    "f_form": f_form,
    #    "u_form": u_form,
    #    "p_form": p_form,
    #    "calendar": calendar,
    #    "is_contryeditor":is_contryeditor,
    #    "is_contryeditor_1":is_contryeditor_1,        
    #    "is_secretariat":is_secretariat,
    #    "can_add_edit":can_add_edit,
    #    "event_id":event_id,
    #    "next": next
    #}, context_instance=RequestContext(request))
    return TemplateResponse(request, template_name, { "userprofile":userprofile, "form": form,
        "issueform": issueform,
        "f_form": f_form,
        "u_form": u_form,
        "p_form": p_form,
        "calendar": calendar,
        "is_contryeditor":is_contryeditor,
        "is_contryeditor_1":is_contryeditor_1,        
        "is_secretariat":is_secretariat,
        "can_add_edit":can_add_edit,
        "event_id":event_id,
        "next": next},)        
Beispiel #56
0
class TestOccurrence(TestCase):
    def setUp(self):
        rule = Rule(frequency="WEEKLY")
        rule.save()
        cal = Calendar(name="MyCal")
        cal.save()
        self.recurring_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
        }
        self.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),
            'calendar': cal
        }
        self.recurring_event = Event(**self.recurring_data)
        self.recurring_event.save()
        self.start = datetime.datetime(2008, 1, 12, 0, 0)
        self.end = datetime.datetime(2008, 1, 27, 0, 0)

    def test_presisted_occurrences(self):
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                                           end=self.end)
        persisted_occurrence = occurrences[0]
        persisted_occurrence.save()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                                           end=self.end)
        self.assertTrue(occurrences[0].pk)
        self.assertFalse(occurrences[1].pk)

    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 test_cancelled_occurrences(self):
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                                           end=self.end)
        cancelled_occurrence = occurrences[2]
        cancelled_occurrence.cancel()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                                           end=self.end)
        self.assertTrue(occurrences[2].cancelled)
        cancelled_occurrence.uncancel()
        occurrences = self.recurring_event.get_occurrences(start=self.start,
                                                           end=self.end)
        self.assertFalse(occurrences[2].cancelled)
    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))
Beispiel #58
0
    def handle_noargs(self, **options):
        import datetime
        from schedule.models import Calendar
        from schedule.models import Event
        from schedule.models import Rule

        print "checking for existing data ..."
        try:
            cal = Calendar.objects.get(name="yml_cal")
            print "It looks like you already have loaded the sample data, quitting."
            import sys
            sys.exit(1)
        except Calendar.DoesNotExist:
            print "Sample data not found in db."
            print "Install it..."

        print "Create 2 calendars : tony_cal, yml_cal"
        yml_cal = Calendar(name="yml_cal", slug="yml")
        yml_cal.save()
        print "First calendar is created"
        tony_cal = Calendar(name="tony_cal", slug="tony")
        tony_cal.save()
        print "Second calendar is created"
        print "Do we need to create the most common rules?"
        try:
            rule = Rule.objects.get(name="Daily")
        except Rule.DoesNotExist:
            rule = Rule(frequency="YEARLY",
                        name="Yearly",
                        description="will recur once every Year")
            rule.save()
            print "YEARLY recurrence created"
            rule = Rule(frequency="MONTHLY",
                        name="Monthly",
                        description="will recur once every Month")
            rule.save()
            print "Monthly recurrence created"
            rule = Rule(frequency="WEEKLY",
                        name="Weekly",
                        description="will recur once every Week")
            rule.save()
            print "Weekly recurrence created"
            rule = Rule(frequency="DAILY",
                        name="Daily",
                        description="will recur once every Day")
            rule.save()
            print "Daily recurrence created"
        print "The common rules are installed."

        print "Create some events"
        rule = Rule.objects.get(frequency="WEEKLY")
        data = {
            'title': 'Ping pong',
            'start': datetime.datetime(2008, 11, 1, 8, 0),
            'end': datetime.datetime(2008, 11, 1, 9, 0),
            'end_recurring_period': datetime.datetime(2010, 5, 5, 0, 0),
            'rule': rule,
            'calendar': tony_cal
        }
        event = Event(**data)
        event.save()
        rule = Rule.objects.get(frequency="DAILY")
        data = {
            'title': 'Home work',
            'start': datetime.datetime(2008, 11, 1, 18, 0),
            'end': datetime.datetime(2008, 11, 1, 19, 0),
            'end_recurring_period': datetime.datetime(2010, 5, 5, 0, 0),
            'rule': rule,
            'calendar': tony_cal
        }
        event = Event(**data)
        event.save()
Beispiel #59
0
class TestEventListManager(TestCase):
    def setUp(self):
        weekly = Rule.objects.create(frequency="WEEKLY")
        daily = Rule.objects.create(frequency="DAILY")
        cal = Calendar.objects.create(name="MyCal")
        self.default_tzinfo = timezone.get_default_timezone()

        self.event1 = Event(
            **{
                'title':
                'Weekly Event',
                'start':
                datetime.datetime(2009, 4, 1, 8, 0,
                                  tzinfo=self.default_tzinfo),
                'end':
                datetime.datetime(2009, 4, 1, 9, 0,
                                  tzinfo=self.default_tzinfo),
                'end_recurring_period':
                datetime.datetime(
                    2009, 10, 5, 0, 0, tzinfo=self.default_tzinfo),
                'rule':
                weekly,
                'calendar':
                cal
            })
        self.event1.save()
        self.event2 = Event(
            **{
                'title':
                'Recent Event',
                'start':
                datetime.datetime(2008, 1, 5, 9, 0,
                                  tzinfo=self.default_tzinfo),
                'end':
                datetime.datetime(
                    2008, 1, 5, 10, 0, tzinfo=self.default_tzinfo),
                'end_recurring_period':
                datetime.datetime(2009, 5, 5, 0, 0,
                                  tzinfo=self.default_tzinfo),
                'rule':
                daily,
                'calendar':
                cal
            })
        self.event2.save()

    def test_occurrences_after(self):
        eml = EventListManager([self.event1, self.event2])
        occurrences = eml.occurrences_after(
            datetime.datetime(2009, 4, 1, 0, 0, tzinfo=self.default_tzinfo))
        self.assertEqual(next(occurrences).event, self.event1)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event2)
        self.assertEqual(next(occurrences).event, self.event1)
        occurrences = eml.occurrences_after()
        self.assertEqual(list(occurrences), [])
Beispiel #60
0
 def save(self, force_insert=False, force_update=False):
     new_task = True
     super(PostEater, self).save(force_insert, force_update)
     end = self.startDateTime + timedelta(minutes=1)
     color = '#A41515'
     description = "http://127.0.0.1:8000/posts/" + str(
         self.submit_time.strftime("%Y/%b/%d"))
     user_short = self.user.profile.housename
     if new_task:
         event = Event(start=self.startDateTime,
                       end=end,
                       title=user_short,
                       description=description,
                       calendar_id=1)
         event.save()
         rel = EventRelation.objects.create_relation(event, self)
         rel.save()
         try:
             cal = Calendar.objects.get(name="hooggeacht")
         except Calendar.DoesNotExist:
             cal = Calendar(name="bla")
             cal.save()
         cal.events.add(event)
     else:
         event = Event.objects.get_for_object(self)[0]
         event.start = self.startDateTime
         event.end = end
         event.title = title
         event.description = self.description
         event.eventColor = self.color
         event.save()