Skip to content
Snippets Groups Projects
Commit a7a39439 authored by Piotr Gawron's avatar Piotr Gawron
Browse files

timezone used instead of datetime where possible to prevent issue with missing timezones

parent ffd8b269
No related branches found
No related tags found
1 merge request!272Resolve "fix datetime without TZ warnings"
......@@ -6,9 +6,9 @@ from operator import itemgetter
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from web.tests.functions import datetimeify_date
from web.models import Appointment, AppointmentTypeLink, Worker, Availability, Holiday
from web.models.worker_study_role import WORKER_STAFF
from web.tests.functions import datetimeify_date
from web.views import e500_error
from web.views.notifications import get_filter_locations
......@@ -129,7 +129,7 @@ def remove_holidays(availability, worker, date):
return result
def get_availabilities(worker, date):
def get_availabilities(worker: Worker, date: datetime.datetime):
result = []
today = datetimeify_date(date)
......@@ -171,7 +171,7 @@ def get_conflicts(worker, date):
link_when = appointment.datetime_when
link_when = link_when.replace(tzinfo=None)
link_end = link_when + \
datetime.timedelta(minutes=appointment.length)
datetime.timedelta(minutes=appointment.length)
event = {
'title': appointment.title(),
'duration': appointment.length,
......@@ -190,8 +190,8 @@ def get_conflicts(worker, date):
if link_when is not None:
link_when = link_when.replace(tzinfo=None)
link_end = link_when + \
datetime.timedelta(
minutes=link.appointment_type.default_duration)
datetime.timedelta(
minutes=link.appointment_type.default_duration)
event = {
'title': link.appointment_type.description,
'duration': build_duration(link.appointment_type.default_duration),
......@@ -212,15 +212,15 @@ def get_generic_appointment_events(request, date, include_all=False):
if include_all:
appointments = Appointment.objects.filter(
datetime_when__date=date,
location__in=get_filter_locations(request.user),
visit__isnull=True).all()
datetime_when__date=date,
location__in=get_filter_locations(request.user),
visit__isnull=True).all()
else:
appointments = Appointment.objects.filter(
datetime_when__date=date,
location__in=get_filter_locations(request.user),
status=Appointment.APPOINTMENT_STATUS_SCHEDULED,
visit__isnull=True).all()
datetime_when__date=date,
location__in=get_filter_locations(request.user),
status=Appointment.APPOINTMENT_STATUS_SCHEDULED,
visit__isnull=True).all()
for appointment in appointments:
if appointment.location_id not in result:
......@@ -240,7 +240,7 @@ def get_generic_appointment_events(request, date, include_all=False):
if link_when is not None:
link_when = link_when.replace(tzinfo=None)
link_end = link_when + \
datetime.timedelta(minutes=appointment.length)
datetime.timedelta(minutes=appointment.length)
event = {
'title': appointment.title(),
'short_title': appointment.title(),
......@@ -265,28 +265,29 @@ def get_generic_appointment_events(request, date, include_all=False):
def events(request, date, include_all=False):
date = datetimeify_date(date)
#fetch appointments
# fetch appointments
if include_all:
appointments = Appointment.objects.filter(
datetime_when__date=date,
location__in=get_filter_locations(request.user),
visit__isnull=False).all()
else:
else:
appointments = Appointment.objects.filter(
datetime_when__date=date,
location__in=get_filter_locations(request.user),
status=Appointment.APPOINTMENT_STATUS_SCHEDULED,
visit__isnull=False).all()
#store subjects
# store subjects
subjects = {}
#for each appointment
# for each appointment
for i, appointment in enumerate(appointments):
#get its subject
# get its subject
appointment_subject = appointment.visit.subject
#if there is a subject we add it to the subjects dict
# if there is a subject we add it to the subjects dict
if appointment_subject.id not in subjects:
# create subject
flag_set = set([language.image.url for language in appointment_subject.subject.languages.all() if language.image is not None])
flag_set = set([language.image.url for language in appointment_subject.subject.languages.all() if
language.image is not None])
default_language = appointment_subject.subject.default_written_communication_language
if default_language is not None and default_language.image is not None:
flag_set.add(default_language.image.url)
......@@ -305,18 +306,18 @@ def events(request, date, include_all=False):
}
subjects[appointment_subject.id] = subject
#get appointment type link of the appointment
# get appointment type link of the appointment
links = AppointmentTypeLink.objects.filter(
appointment=appointment).all()
#for the AppointmentTypeLink, get all the info and create the event object
# for the AppointmentTypeLink, get all the info and create the event object
for j, link in enumerate(links):
link_when = link.date_when
link_end = None
if link_when is not None:
link_when = link_when.replace(tzinfo=None)
link_end = link_when + \
datetime.timedelta(
minutes=link.appointment_type.default_duration)
datetime.timedelta(
minutes=link.appointment_type.default_duration)
event = {
'title': link.appointment_type.description,
'status': link.appointment.status,
......
......@@ -2,33 +2,30 @@
import datetime
import logging
from web.utils import get_today_midnight_date
from django.contrib.auth.models import Permission
from django.contrib.auth.models import User, AnonymousUser
from django.db import models
from django.db.models import Q
from django.utils import timezone
from web.models.constants import GLOBAL_STUDY_ID, COUNTRY_OTHER_ID, AVAILABILITY_HOLIDAY, AVAILABILITY_EXTRA
from web.models.appointment import Appointment
from web.models.appointment_type_link import AppointmentTypeLink
from web.models.constants import GLOBAL_STUDY_ID, COUNTRY_OTHER_ID, AVAILABILITY_HOLIDAY
from web.models.worker_study_role import STUDY_ROLE_CHOICES, HEALTH_PARTNER_ROLE_CHOICES, \
VOUCHER_PARTNER_ROLE_CHOICES, WORKER_STAFF, WORKER_HEALTH_PARTNER, WORKER_VOUCHER_PARTNER, ROLE_CHOICES
from web.utils import get_weekdays_in_period
from web.officeAvailability import OfficeAvailability
from django.db.models import Q
from web.models.holiday import Holiday
from web.models.availability import Availability
from web.models.appointment import Appointment
from web.models.appointment_type_link import AppointmentTypeLink
from django.contrib.auth.models import Permission
from web.utils import get_today_midnight_date
from web.utils import get_weekdays_in_period
logger = logging.getLogger(__name__)
def roles_by_worker_type(worker_type):
try:
try:
role_choices = role_choices_by_worker_type(worker_type)
except TypeError:
role_choices = []
roles = []
for role_type, role_name in role_choices:
......@@ -158,16 +155,16 @@ class Worker(models.Model):
)
def is_on_leave(self):
if len(self.holiday_set.filter(datetime_end__gt=datetime.datetime.now(),
datetime_start__lt=datetime.datetime.now(),
kind=AVAILABILITY_HOLIDAY)):
if len(self.holiday_set.filter(datetime_end__gt=timezone.now(),
datetime_start__lt=timezone.now(),
kind=AVAILABILITY_HOLIDAY)):
return True
return False
def current_leave_details(self):
holidays = self.holiday_set.filter(datetime_end__gt=datetime.datetime.now(),
datetime_start__lt=datetime.datetime.now(),
kind=AVAILABILITY_HOLIDAY).order_by('-datetime_end')
holidays = self.holiday_set.filter(datetime_end__gt=timezone.now(),
datetime_start__lt=timezone.now(),
kind=AVAILABILITY_HOLIDAY).order_by('-datetime_end')
if len(holidays) > 0:
return holidays[0]
else:
......@@ -205,17 +202,18 @@ class Worker(models.Model):
start_date = start_date.replace(hour=0, minute=0, second=0)
end_date = start_date + datetime.timedelta(days=1)
office_availability = OfficeAvailability('{} {}'.format(self.first_name, self.last_name), start=start_date, end=end_date)
office_availability = OfficeAvailability('{} {}'.format(self.first_name, self.last_name), start=start_date,
end=end_date)
#Subject Appointments
# Subject Appointments
old_events = Q(date_when__gt=start_date) & Q(date_when__gt=end_date)
future_events = Q(date_when__lt=start_date) & Q(date_when__lt=end_date)
non_overlap_events = old_events | future_events
overlap_events = ~non_overlap_events
query = Q(worker=self.id) & overlap_events
subject_appointments = AppointmentTypeLink.objects.filter(query)
#General Appointments
# General Appointments
old_events = Q(datetime_when__gt=start_date) & Q(datetime_when__gt=end_date)
future_events = Q(datetime_when__lt=start_date) & Q(datetime_when__lt=end_date)
non_overlap_events = old_events | future_events
......@@ -223,19 +221,20 @@ class Worker(models.Model):
query = Q(worker_assigned=self.id) & overlap_events
general_appointments = Appointment.objects.filter(query)
#Holidays and extra availabilities.
# Holidays and extra availabilities.
old_events = Q(datetime_start__gt=start_date) & Q(datetime_start__gt=end_date)
future_events = Q(datetime_end__lt=start_date) & Q(datetime_end__lt=end_date)
non_overlap_events = old_events | future_events
overlap_events = ~non_overlap_events
holidays_and_extra_availabilities = self.holiday_set.filter(overlap_events).order_by('-datetime_start')
#Availability
# Availability
weekdays = get_weekdays_in_period(start_date, end_date)
weekdayQ = Q() #create a filter for each weekday in the selected period
weekdayQ = Q() # create a filter for each weekday in the selected period
for weekday in weekdays:
weekdayQ = weekdayQ | Q(day_number=weekday)
availabilities = self.availability_set.filter(person=self.id).filter(weekdayQ).order_by('day_number', 'available_from')
availabilities = self.availability_set.filter(person=self.id).filter(weekdayQ).order_by('day_number',
'available_from')
things = []
things.extend(availabilities)
......@@ -260,7 +259,7 @@ class Worker(models.Model):
roles = self.roles.filter(study=study)
if roles.count() == 0:
return False
if role[0].permissions.filter(codename=codename).all().count() > 0:
return True
else:
......
# coding=utf-8
import datetime
import json
import logging
......@@ -195,8 +194,8 @@ class TestDailyPlanningApi(LoggedInWithWorkerTestCase):
request.user = self.user
appointment = create_appointment()
appointment.datetime_when = datetime.datetime.now().replace(year=2017, month=9, day=5,
hour=12)
appointment.datetime_when = timezone.now().replace(year=2017, month=9, day=5,
hour=12)
appointment.length = 30
appointment.location = self.worker.locations.all()[0]
appointment.visit = None
......
......@@ -590,7 +590,7 @@ class TestSubjectApi(LoggedInWithWorkerTestCase):
subject2 = create_study_subject(2)
contact_attempt = create_contact_attempt(subject=subject)
contact_attempt.datetime_when = datetime.datetime(1900, 1, 1)
contact_attempt.datetime_when = timezone.now().replace(1900, 1, 1)
contact_attempt.save()
create_contact_attempt(subject=subject2)
......
......@@ -415,7 +415,7 @@ def datetimeify_date(date, timezone=datetime.timezone.utc):
if isinstance(date, bytes): # If it's bytes, then convert to string and carry on...
date = date.decode('utf8')
if isinstance(date, str): # If it's string, convert to datetime with timezone support
return datetime.datetime.strptime(date, '%Y-%m-%d')
return make_aware(datetime.datetime.strptime(date, '%Y-%m-%d'))
"""
if len(date) < 8:
actual_length = str(len(date))
......
......@@ -65,8 +65,8 @@ class WorkerModelTests(TestCase):
worker = create_worker()
self.assertEqual(worker.current_leave_details(), None)
h = Holiday(person=worker,
datetime_start=get_today_midnight_date() + datetime.timedelta(days=-2),
datetime_end=get_today_midnight_date() + datetime.timedelta(days=2))
datetime_start=get_today_midnight_date() + datetime.timedelta(days=-2),
datetime_end=get_today_midnight_date() + datetime.timedelta(days=2))
h.save()
self.assertEqual(worker.current_leave_details(), h)
......@@ -102,7 +102,7 @@ class WorkerModelTests(TestCase):
with self.assertRaises(Exception):
worker_type_by_worker(worker)
#worker role tests
# worker role tests
def test_worker_role_by_worker_without_role(self):
self.assertEqual(WORKER_STAFF, Worker().role)
......
......@@ -61,6 +61,7 @@ class VisitViewTests(LoggedInTestCase):
form_data = self.create_visit_detail_form_data(visit)
response = self.client.post(reverse('web.views.visit_details', kwargs={'id': visit.id}), data=form_data)
self.assertEqual(response.status_code, 200)
self.assertNotContains(response, "error")
self.assertTrue(template_name.encode('utf8') in response.content)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment