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()
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))
def save(self, *args, **kwargs): #TODO: fix bug (Issue #34) . the save method prevents the creation of another event with the # same times, even if this is a different CS) SEE issue # if self.cs_event_nk is None and CSEvent.objects.filter(startDateTime=self.startDateTime, endDateTime=self.endDateTime).exists(): # raise ValidationError(_('CS Event at {0}-{1} already exists'.format(self.startDateTime, self.endDateTime))) if not self.cs_event_nk: self.cs_event_nk = create_hash(self) if self.ev_event_id == -1: # not reserved yet cs_cal = Calendar.objects.get(id=self.cs.calendar.id) data = { 'title': 'Charging Slot for ' + self.cs.name, 'start': self.startDateTime, 'end': self.endDateTime, 'calendar': cs_cal } event = Event(**data) event.save() cs_cal.events.add(event) elif self.ev_event_id != -1 and self.status == 'AVAILABLE': # about to be reserved self.status = 'RESERVED' super().save(*args, **kwargs)
def save(self, *args, **kwargs): if not self.nk: self.nk = create_hash(self) if self.cs_event.status != 'r': data = { 'title': 'Charging Time for ' + str(self.ev) + str(self.cs_event.cs.name), 'start': self.cs_event.startDateTime, 'end': self.cs_event.endDateTime, 'calendar': self.ev.calendar } event = Event(**data) event.save() self.cs_event.ev_event_id = event.id self.cs_event.save() self.ev.calendar.events.add(event) else: raise ValidationError(_('EV event already reserved')) super().save(*args, **kwargs)
def add_task(request, flat_id=None): name = request.data.get('name', None) user_ids = request.data.get('users', None) frequency = request.data.get('frequency', None) if name is None or user_ids is None or frequency is None: return Response(data={'message': 'Wrong parameters'}, status=400) if frequency not in ['DAILY', 'WEEKLY', 'MONTHLY']: return Response( data={'message': 'Frequency can be: DAILY, WEEKLY, MONTHLY'}, status=400) try: flat = Flat.objects.get(id=flat_id) except ObjectDoesNotExist: return Response( data={'message': 'The flat {0} does not exist.'.format(flat_id)}, status=400) user_list = [] for user_id in user_ids.split(','): try: user = User.objects.get(id=user_id) if user not in flat.users.all(): return Response(data={ 'message': '{0} is not a member of the flat.'.format(user.username) }, status=400) user_list.append(user) except ObjectDoesNotExist: return Response(data={ 'message': 'The user id {0} does not exist.'.format(user_id) }, status=400) rule = Rule(frequency=frequency, name='{0}_{1}'.format(frequency, name)) rule.save() event = Event(rule=rule, start=datetime.now(), end=datetime.now() + timedelta(days=60), calendar=Calendar.objects.get_calendar_for_object(flat)) event.save() task = Task(flat=flat, name=name, event=event) task.save() for u in user_list: task.users.add(u) task.refresh_from_db() return Response(data={ 'message': 'Your task has been created.', 'task': TaskSerializer(task).data, }, status=200)
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)
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)
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)
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): 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))
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)
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'])
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
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)
def add_to_calendar(pk): event = get_object_or_404(Event, pk=pk) title = '{0} - {1}'.format(event.client_name, event.event_type) description = '<a href="{0}/event/{1}"</a>'.format(base_url, event.pk) start_time = time(19, 0, 0) # current_tz = timezone.get_current_timezone() def get_start_time(): if event.start_time is None: start_time = time(19, 0, 0) else: start_time = event.start_time return start_time start_time = get_start_time() start = dt.combine(event.event_date, start_time) start = timezone.make_aware(start, timezone.get_current_timezone()) end = start + timedelta(hours=4) occurrence = S_Event(start=start, end=end, title=title, description=description) occurrence.save() cal = Calendar.objects.get(pk=1) cal.events.add(occurrence)
def create_twelve(request): if request.is_ajax(): to_monday = date.today().weekday() start = date.today() - datetime.timedelta(days=to_monday) # Find Monday fake_end = start + datetime.timedelta(days=84) if fake_end.weekday() != 4: end = fake_end - datetime.timedelta(days=(fake_end.weekday() - 4)) else: end = fake_end day = start total = 0 dupe_list = [] weekend = set([5, 6]) # Python week starts on Monday as 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) data = {'start': start, 'end': end, 'dupe_list': dupe_list, 'total': total} return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))
def create_month(request): if request.is_ajax(): month = date.today().month year = date.today().year # last = calendar.monthrange(year, month) # Last day start = date.today().replace(day=1) # Get the first day of the month end = date.today().replace(day=(calendar.monthrange(year, month)[1])) weekend = set([5, 6]) # Python week starts on Monday as 0 dupe_list = [] total = 0 day = start 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) data = {'start': start, 'end': end, 'dupe_list': dupe_list, 'total': total} return HttpResponse(json.dumps(data, cls=DjangoJSONEncoder))
def forms_valid(self, forms): date = forms['date_form'].save() self.show.date = date forms['poster_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: info.location = info.venue.profile.contact_info.location info.save() forms['show_info_form'].save_m2m() participants = info.participants() # create or edit event for each particpent in show forms['event_form'].save() for user in participants: event = get_object_or_None(Event, show=self.show, calendar=user.calendar) if self.request.user != user and not event: event = Event(show=self.show, calendar=user.calendar) event.save() self.show.save() return self.get_success_url()
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
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)
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], [])
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)
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)
def allnight_submit(request): datestr = request.POST['date'] club = request.POST['club'] # 철야를 신청한 동아리의 calendar slug 값 owner_slug = admin_slug_dict[club] color = slug_color_dict[owner_slug] start = (datetime.datetime.strptime(datestr, '%b %d, %Y') + datetime.timedelta(days=1)) end = start + datetime.timedelta(hours=6) # DEFAULT slug만 따로 try-except하는 이유: # 이미 철야가 등록된 동아리가 있는지 check하기 위함 try: event = Event.objects.get( calendar=Calendar.objects.get(slug='DEFAULT'), start=start, end=end, creator=UserModel.objects.get(username=club), ) return render_to_response( 'error.html', { 'error_name': '403', 'error_msg': '이미 철야가 등록된 날짜입니다 :( ', 'prev_page': '/allnight' }) except ObjectDoesNotExist: event = Event( calendar=Calendar.objects.get(slug='DEFAULT'), title=club[:-5], start=start, end=end, color_event=color, creator=UserModel.objects.get(username=club), ) event.save() # DEFAULT 제외 for slug in slugs[1:]: if slug == owner_slug: title = '철야' c = '#333333' else: title = club[:-5] c = others_color Event( calendar=Calendar.objects.get(slug=slug), title=title, start=start, end=end, color_event=c, creator=UserModel.objects.get(username=club), ).save() url = '/timetable' return HttpResponseRedirect(url)
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()
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( '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_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], [])
def book(self, start=None, end=None, numero_ospiti=None, servizi_opzionali=[], user=None, session=None): print 'Alloggio book' print 'user:'******'session:', session day_count = end - start notti = day_count.days reservation = Reservation() if user.is_authenticated(): reservation.user = user # if not session.exists(session.session_key): # session.create() # # reservation.session = Session.objects.get(session_key=session.session_key) reservation.alloggio = self reservation.numero_ospiti = numero_ospiti alloggio_quote = self.getAlloggioPrice(notti, numero_ospiti) reservation.price = alloggio_quote['prezzo'] reservation.iva = alloggio_quote['iva'] reservation_event = Event(start=start, end=end, calendar=self.calendar, title='reservation ') reservation_event.save() reservation.event = reservation_event reservation.save() if user.is_authenticated(): reservation.notify_reservation() for service in servizi_opzionali: reservation_service = ReservationService(original_service=service, reservation=reservation) reservation_quote = service.getServicePrice(notti, numero_ospiti) reservation_service.costo = service.costo reservation_service.fattore_tempo = service.fattore_tempo reservation_service.price = reservation_quote['prezzo'] reservation_service.iva = reservation_quote['iva'] reservation_service.save() # reservation.servizi_opzional.add(reservation_service) # reservation.servizi_opzional = servizi_opzionali return reservation
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)
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
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)
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' ])
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
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()
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()
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 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 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)
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 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
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)
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 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))
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))
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))
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_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)
def setUp(self): rule = Rule(frequency="WEEKLY") rule.save() cal = Calendar(name="MyCal") cal.save() data = { "title": "Recent Event", "start": datetime.datetime(2008, 1, 5, 8, 0, tzinfo=pytz.utc), "end": datetime.datetime(2008, 1, 5, 9, 0, tzinfo=pytz.utc), "end_recurring_period": datetime.datetime(2008, 5, 5, 0, 0, tzinfo=pytz.utc), "rule": rule, "calendar": cal, } recurring_event = Event(**data) recurring_event.save() self.period = Period( events=Event.objects.all(), start=datetime.datetime(2008, 1, 4, 7, 0, tzinfo=pytz.utc), end=datetime.datetime(2008, 1, 21, 7, 0, tzinfo=pytz.utc), )
def 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
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.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), [])
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)
def save(self, force_insert=False, force_update=False): new_meeting = False if not self.id: new_meeting = True unique_slugify(self, "-".join([self.circle.short_name, self.name, self.date_and_time.strftime('%Y-%m-%d')]) ) super(Meeting, self).save(force_insert, force_update) end = self.date_and_time + timedelta(minutes=self.duration) title = " ".join([self.circle.short_name, self.get_name_display()]) if new_meeting: event = Event( start=self.date_and_time, end=end, title=title, household_location=self.household_location, alternate_location=self.alternate_location, description=self.description) event.save() rel = EventRelation.objects.create_relation(event, self) rel.save() try: cal = Calendar.objects.get(pk=1) except Calendar.DoesNotExist: cal = Calendar(name="Community Calendar") cal.save() cal.events.add(event) else: event = Event.objects.get_for_object(self)[0] event.start = self.date_and_time event.end = end event.title = title event.household_location = self.household_location event.alternate_location = self.alternate_location event.description = self.description event.save()
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), )
def handle_noargs(self, **options): import datetime from schedule.models import Room from schedule.models import Event from schedule.models import Rule print "checking for existing data ..." try: cal = Room.objects.get(name="yml_cal") print "It looks like you already have loaded the sample data, quitting." import sys sys.exit(1) except Room.DoesNotExist: print "Sample data not found in db." print "Install it..." print "Create 2 rooms : tony_cal, yml_cal" yml_cal = Room(name="yml_cal", slug="yml") yml_cal.save() print "First room is created" tony_cal = Room(name="tony_cal", slug="tony") tony_cal.save() print "Second room 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, "room": 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, "room": tony_cal, } event = Event(**data) event.save()