agenda/actes/dossiers: move Occurence fields into Event, add recurring events support

This commit is contained in:
Benjamin Dauvergne 2012-12-17 23:08:31 +01:00
parent 979b59ce42
commit 76974b6f2d
24 changed files with 744 additions and 771 deletions

View File

@ -2,8 +2,7 @@ from django.contrib import admin
import reversion
from models import Act, ActValidationState, EventAct
from models import Act, ActValidationState
admin.site.register(Act, reversion.VersionAdmin)
admin.site.register(ActValidationState, reversion.VersionAdmin)
admin.site.register(EventAct, reversion.VersionAdmin)

View File

@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from datetime import date
from django.db import models
from django.contrib.auth.models import User
@ -40,9 +42,32 @@ class ActValidationState(models.Model):
return VALIDATION_STATES[self.state_name]
class ActManager(models.Manager):
def create_act(self, author=None, **kwargs):
act = self.create(**kwargs)
ActValidationState.objects.create(act=act,state_name='NON_VALIDE',
author=author, previous_state=None)
return act
def next_acts(self, patient_record, today=None):
today = today or date.today()
return self.filter(date__gte=today) \
.filter(patient=patient_record) \
.order_by('date')
def last_acts(self, patient_record, today=None):
today = today or date.today()
return self.filter(date__lte=today) \
.filter(patient=patient_record) \
.order_by('-date')
class Act(models.Model):
objects = ActManager()
patient = models.ForeignKey('dossiers.PatientRecord')
date = models.DateTimeField()
date = models.DateField()
_duration = models.IntegerField(u'Durée en minutes', default=0)
act_type = models.ForeignKey('ressources.ActType',
verbose_name=u'Type d\'acte')
validation_locked = models.BooleanField(default=False,
@ -68,6 +93,32 @@ class Act(models.Model):
verbose_name=u'Intervenants')
pause = models.BooleanField(default=False,
verbose_name=u'Pause facturation')
parent_event = models.ForeignKey('agenda.Event',
verbose_name=u'Rendez-vous lié',
blank=True, null=True)
VALIDATION_CODE_CHOICES = (
('absent', u'Absent'),
('present', u'Présent'),
)
attendance = models.CharField(max_length=16,
choices=VALIDATION_CODE_CHOICES,
default='absent',
verbose_name=u'Présence')
convocation_sent = models.BooleanField(blank=True,
verbose_name=u'Convoqué')
@property
def event(self):
if self.parent_event:
return self.parent_event.today_occurence(self.date)
return None
@property
def start_time(self):
event = self.event
if event:
return event.start_datetime.timetz()
return None
def get_hc_tag(self):
if self.healthcare:
@ -155,7 +206,7 @@ class Act(models.Model):
if not hc:
# On pourrait ici créer une prise en charge de diagnostic
return (False, None)
if self.date.date() < hc.start_date:
if self.date < hc.start_date:
return (False, None)
# Les acts facturés déja couvert par la prise en charge sont pointés
# dans hc.act_set.all()
@ -172,7 +223,7 @@ class Act(models.Model):
for a in acts_billable:
if nb_acts_billed + count >= hc.get_act_number():
return (False, None)
if a.date.date() >= hc.start_date:
if a.date >= hc.start_date:
if a.id == self.id:
return (True, hc)
count = count + 1
@ -225,7 +276,12 @@ class Act(models.Model):
# return (True, hc)
# count = count + 1
# return (False, None)
# END Specific to cmpp healthcare
# END Specific to cmpp healthcare
def duration(self):
'''Return a displayable duration for this field.'''
hours, remainder = divmod(self._duration, 60)
return '%02d:%02d' % (hours, remainder)
def __unicode__(self):
return u'{0} le {1} pour {2} avec {3}'.format(
@ -285,91 +341,6 @@ class EventActManager(EventManager):
end_datetime=end_datetime,
room=room, note=note, **rrule_params)
def modify_patient_appointment(self, creator, title, patient, participants,
act_type, service, start_datetime, end_datetime, description='',
room=None, note=None, **rrule_params):
"""
This method allow you to create a new patient appointment quickly
Args:
creator: author of the modification
title: patient appointment title (str)
patient: Patient object
participants: List of CalebasseUser (therapists)
act_type: ActType object
service: Service object. Use session service by defaut
start_datetime: datetime with the start date and time
end_datetime: datetime with the end date and time
description: description of the event
room: room where the event will take place
freq, count, until, byweekday, rrule_params:
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
Example:
Look at calebasse.agenda.tests.EventTest (test_create_appointments
method)
"""
event_type, created = EventType.objects.get_or_create(
label=u"Rendez-vous patient"
)
act_event = EventAct.objects.create(
title=title,
event_type=event_type,
patient=patient,
act_type=act_type,
date=start_datetime,
)
act_event.doctors = participants
ActValidationState(act=act_event, state_name=NON_VALIDE,
author=creator, previous_state=None).save()
return self._set_event(act_event, participants, description,
services=[service], start_datetime=start_datetime,
end_datetime=end_datetime,
room=room, note=note, **rrule_params)
class EventAct(Event, Act):
objects = EventActManager()
VALIDATION_CODE_CHOICES = (
('absent', u'Absent'),
('present', u'Présent'),
)
attendance = models.CharField(max_length=16,
choices=VALIDATION_CODE_CHOICES,
default='absent',
verbose_name=u'Présence')
convocation_sent = models.BooleanField(blank=True,
verbose_name=u'Convoqué')
def __unicode__(self):
return u'Rdv le {0} de {1} avec {2} pour {3}'.format(
self.occurrence_set.all()[0].start_time, self.patient,
', '.join(map(unicode, self.participants.all())),
self.act_type)
def __repr__(self):
return (u'<%s %r %r>' % (self.__class__.__name__, unicode(self),
self.id)).encode('utf-8')
def start_time(self):
return self.occurrence_set.all()[0].start_time
def duration(self):
o = self.occurrence_set.all()[0]
td = o.end_time - o.start_time
hours, remainder = divmod(td.seconds, 3600)
minutes, remainder = divmod(remainder, 60)
return '%02d:%02d' % (hours, minutes)
class Meta:
verbose_name = 'Rendez-vous patient'
verbose_name_plural = 'Rendez-vous patient'
ordering = ['-date', 'patient']
reversion.register(EventAct, follow=['act_ptr', 'event_ptr'])
class ValidationMessage(ServiceLinkedAbstractModel):
validation_date = models.DateTimeField()

View File

@ -123,7 +123,7 @@
{% endif %}
{% endfor %}
</td>
<td>{{ act.start_time|date:"H:i" }}</td>
<td>{{ act.parent_event.start_time|date:"H:i" }}</td>
<td>{{ act.duration }}</td>
</tr>
{% endfor %}

View File

@ -1,14 +1,13 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil import rrule
from datetime import datetime, date
from django.test import TestCase
from django.contrib.auth.models import User
from validation import automated_validation, are_all_acts_of_the_day_locked, \
get_days_with_acts_not_locked
from calebasse.actes.models import EventAct
from calebasse.dossiers.models import create_patient
from calebasse.agenda.models import EventWithAct
from calebasse.ressources.models import ActType, Service, WorkerType
from calebasse.personnes.models import Worker
@ -28,88 +27,88 @@ class ActTest(TestCase):
patient2 = create_patient('Jimmy', 'Claff', service, creator)
patient3 = create_patient('Bouba', 'Lourson', service, creator)
act_event = EventAct.objects.create_patient_appointment(creator, 'RDV avec M X', patient,
act_event = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M X', patient,
[therapist1, therapist2], act_type, service,
start_datetime=datetime(2020, 10, 2, 7, 15),
end_datetime=datetime(2020, 10, 2, 9, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2040, 10, 2))
act_event2 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient, [therapist3],
periodicity=1, until=date(2020, 10, 2))
act_event2 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 2, 10, 15),
end_datetime=datetime(2020, 10, 2, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
act_event3 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M X', patient2,
periodicity=1, until=date(2020, 10, 2))
act_event3 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M X', patient2,
[therapist1, therapist2], act_type, service,
start_datetime=datetime(2020, 10, 2, 7, 15),
end_datetime=datetime(2020, 10, 2, 9, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2040, 10, 2))
act_event4 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient3, [therapist3],
periodicity=1, until=date(2020, 10, 2))
act_event4 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient3, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 2, 10, 15),
end_datetime=datetime(2020, 10, 2, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
act_event5 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient3, [therapist3],
periodicity=1, until=date(2020, 10, 2))
act_event5 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M Y', patient3, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 3, 10, 15),
end_datetime=datetime(2020, 10, 3, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
act_event6 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M Z', patient, [therapist3],
periodicity=1, until=date(2020, 10, 2))
act_event6 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M Z', patient, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 2, 10, 15),
end_datetime=datetime(2020, 10, 2, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
act_event7 = EventAct.objects.create_patient_appointment(creator, 'RDV avec M Z', patient, [therapist3],
periodicity=1, until=date(2020, 10, 2))
act_event7 = EventWithAct.objects.create_patient_appointment(creator, 'RDV avec M Z', patient, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 4, 10, 15),
end_datetime=datetime(2020, 10, 4, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
periodicity=1, until=date(2020, 10, 4))
act_event3.set_state('ABS_EXC', creator)
act_event6.set_state('VALIDE', creator)
act_event3.act.set_state('ABS_EXC', creator)
act_event6.act.set_state('VALIDE', creator)
result = automated_validation(datetime(2020, 10, 2, 12, 20), service, creator, commit=False)
result = automated_validation(date(2020, 10, 2), service, creator, commit=False)
self.assertEqual(result, (5,2,2,0,1,0,0,0,0,0))
self.assertTrue(act_event.is_state('NON_VALIDE'))
self.assertTrue(act_event2.is_state('NON_VALIDE'))
self.assertTrue(act_event3.is_state('ABS_EXC'))
self.assertTrue(act_event4.is_state('NON_VALIDE'))
self.assertTrue(act_event5.is_state('NON_VALIDE'))
self.assertTrue(act_event6.is_state('VALIDE'))
self.assertTrue(act_event.act.is_state('NON_VALIDE'))
self.assertTrue(act_event2.act.is_state('NON_VALIDE'))
self.assertTrue(act_event3.act.is_state('ABS_EXC'))
self.assertTrue(act_event4.act.is_state('NON_VALIDE'))
self.assertTrue(act_event5.act.is_state('NON_VALIDE'))
self.assertTrue(act_event6.act.is_state('VALIDE'))
result = automated_validation(datetime(2020, 10, 2, 12, 20), service, creator)
result = automated_validation(date(2020, 10, 2), service, creator)
self.assertEqual(result, (5,2,2,0,1,0,0,0,0,0))
self.assertTrue(act_event.is_state('VALIDE'))
self.assertTrue(act_event2.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.is_state('ABS_EXC'))
self.assertTrue(act_event4.is_state('VALIDE'))
self.assertTrue(act_event5.is_state('NON_VALIDE'))
self.assertTrue(act_event6.is_state('ACT_DOUBLE'))
self.assertTrue(act_event.act.is_state('VALIDE'))
self.assertTrue(act_event2.act.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.act.is_state('ABS_EXC'))
self.assertTrue(act_event4.act.is_state('VALIDE'))
self.assertTrue(act_event5.act.is_state('NON_VALIDE'))
self.assertTrue(act_event6.act.is_state('ACT_DOUBLE'))
self.assertTrue(are_all_acts_of_the_day_locked(datetime(2020, 10, 2, 12, 20)))
self.assertFalse(are_all_acts_of_the_day_locked(datetime(2020, 10, 3, 12, 20)))
self.assertFalse(are_all_acts_of_the_day_locked(datetime(2020, 10, 4, 12, 20)))
self.assertEqual(get_days_with_acts_not_locked(datetime(2020, 10, 2), datetime(2020, 10, 4)),
[datetime(2020, 10, 3, 0, 0), datetime(2020, 10, 4, 0, 0)])
[date(2020, 10, 3), date(2020, 10, 4)])
result = automated_validation(datetime(2020, 10, 2, 12, 20), service, creator, commit=False)
self.assertEqual(result, (5,2,2,0,1,0,0,0,0,0))
self.assertTrue(act_event.is_state('VALIDE'))
self.assertTrue(act_event2.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.is_state('ABS_EXC'))
self.assertTrue(act_event4.is_state('VALIDE'))
self.assertTrue(act_event5.is_state('NON_VALIDE'))
self.assertTrue(act_event6.is_state('ACT_DOUBLE'))
self.assertTrue(act_event.act.is_state('VALIDE'))
self.assertTrue(act_event2.act.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.act.is_state('ABS_EXC'))
self.assertTrue(act_event4.act.is_state('VALIDE'))
self.assertTrue(act_event5.act.is_state('NON_VALIDE'))
self.assertTrue(act_event6.act.is_state('ACT_DOUBLE'))
result = automated_validation(datetime(2020, 10, 2, 12, 20), service, creator)
self.assertEqual(result, (5,2,2,0,1,0,0,0,0,0))
self.assertTrue(act_event.is_state('VALIDE'))
self.assertTrue(act_event2.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.is_state('ABS_EXC'))
self.assertTrue(act_event4.is_state('VALIDE'))
self.assertTrue(act_event5.is_state('NON_VALIDE'))
self.assertTrue(act_event6.is_state('ACT_DOUBLE'))
self.assertTrue(act_event.act.is_state('VALIDE'))
self.assertTrue(act_event2.act.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.act.is_state('ABS_EXC'))
self.assertTrue(act_event4.act.is_state('VALIDE'))
self.assertTrue(act_event5.act.is_state('NON_VALIDE'))
self.assertTrue(act_event6.act.is_state('ACT_DOUBLE'))
result = automated_validation(datetime(2020, 10, 2, 12, 20), service, creator, commit=False)
self.assertEqual(result, (5,2,2,0,1,0,0,0,0,0))
self.assertTrue(act_event.is_state('VALIDE'))
self.assertTrue(act_event2.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.is_state('ABS_EXC'))
self.assertTrue(act_event4.is_state('VALIDE'))
self.assertTrue(act_event5.is_state('NON_VALIDE'))
self.assertTrue(act_event6.is_state('ACT_DOUBLE'))
self.assertTrue(act_event.act.is_state('VALIDE'))
self.assertTrue(act_event2.act.is_state('ACT_DOUBLE'))
self.assertTrue(act_event3.act.is_state('ABS_EXC'))
self.assertTrue(act_event4.act.is_state('VALIDE'))
self.assertTrue(act_event5.act.is_state('NON_VALIDE'))
self.assertTrue(act_event6.act.is_state('ACT_DOUBLE'))

View File

@ -14,13 +14,13 @@ def redirect_today(request, service):
service=service)
class ActListingView(ListView):
model=models.EventAct
model=models.Act
template_name='actes/act_listing.html'
def get_queryset(self):
qs = super(ActListingView, self).get_queryset()
self.get_search_form()
qs = qs.filter(services=self.service)
qs = qs.filter(patient__service=self.service)
qs = qs.filter(date=self.date)
if self.request.method == 'POST' and self.search_form.is_valid():
cd = self.search_form.cleaned_data

View File

@ -2,9 +2,8 @@ from django.contrib import admin
import reversion
from models import Event, EventType, Note, Occurrence
from models import Event, EventType, EventWithAct
admin.site.register(Event, reversion.VersionAdmin)
admin.site.register(Occurrence, reversion.VersionAdmin)
admin.site.register(EventType, reversion.VersionAdmin)
admin.site.register(Note, reversion.VersionAdmin)
admin.site.register(EventWithAct, reversion.VersionAdmin)

View File

@ -23,7 +23,7 @@ class Appointment(object):
self.patient_record_paper_id = None
self.event_id = None
self.event_type = None
self.occurrence_id = None
self.event_id = None
self.workers = None
self.workers_initial = None
self.workers_codes = None
@ -41,15 +41,15 @@ class Appointment(object):
else:
self.begin_hour = None
def init_from_occurrence(self, occurrence, service):
def init_from_event(self, event, service):
""" """
delta = occurrence.end_time - occurrence.start_time
self.occurrence_id = occurrence.id
delta = event.end_datetime - event.start_datetime
self.event_id = event.id
self.length = delta.seconds / 60
self.title = occurrence.title
services = occurrence.event.services.all()
self.date = occurrence.start_time.date()
self.__set_time(time(occurrence.start_time.hour, occurrence.start_time.minute))
self.title = event.title
services = event.services.all()
self.date = event.start_datetime.date()
self.__set_time(time(event.start_datetime.hour, event.start_datetime.minute))
for e_service in services:
if e_service != service:
name = e_service.name.lower().replace(' ', '-')
@ -58,13 +58,13 @@ class Appointment(object):
self.type = "busy-here"
else:
self.type = "busy-elsewhere"
self.event_id = occurrence.event.id
if occurrence.event.room:
self.room = occurrence.event.room.name
self.description = occurrence.event.description
if occurrence.event.event_type.id == 1:
event_act = occurrence.event.eventact
workers = event_act.participants.all()
self.event_id = event.id
if event.room:
self.room = event.room.name
self.description = event.description
if event.event_type.id == 1:
event_act = event.act
workers = event_act.doctors.all()
self.convocation_sent = event_act.convocation_sent
self.patient = event_act.patient
self.patient_record_id = event_act.patient.id
@ -93,7 +93,7 @@ class Appointment(object):
validation_states.pop('ACT_DOUBLE')
self.validation = (event_act, state, display_name, validation_states)
else:
self.event_type = occurrence.event.event_type
self.event_type = event.event_type
def init_free_time(self, length, begin_time):
""" """
@ -116,15 +116,15 @@ class Appointment(object):
self.title = title
self.__set_time(time)
def get_daily_appointments(date, worker, service, time_tables, occurrences, holidays):
def get_daily_appointments(date, worker, service, time_tables, events, holidays):
"""
"""
appointments = []
timetables_set = IntervalSet((t.to_interval(date) for t in time_tables))
occurrences_set = IntervalSet((o.to_interval() for o in occurrences))
events_set = IntervalSet((o.to_interval() for o in events))
holidays_set = IntervalSet((h.to_interval(date) for h in holidays))
busy_occurrences_set = IntervalSet((o.to_interval() for o in occurrences if not o.is_event_absence()))
busy_occurrences_set = IntervalSet((o.to_interval() for o in events_set if not o.is_event_absence()))
for free_time in timetables_set - (busy_occurrences_set+holidays_set):
if free_time:
delta = free_time.upper_bound - free_time.lower_bound
@ -133,9 +133,9 @@ def get_daily_appointments(date, worker, service, time_tables, occurrences, holi
appointment.init_free_time(delta_minutes,
time(free_time.lower_bound.hour, free_time.lower_bound.minute))
appointments.append(appointment)
for occurrence in occurrences:
for event in events:
appointment = Appointment()
appointment.init_from_occurrence(occurrence, service)
appointment.init_from_event(event, service)
appointments.append(appointment)
for holiday in holidays:
interval = holiday.to_interval(date)

View File

@ -27,7 +27,7 @@ TIMESLOT_MIN_COLUMNS = 4
# Indicate the default length in time for a new occurrence, specifed by using
# a datetime.timedelta object
DEFAULT_OCCURRENCE_DURATION = datetime.timedelta(hours=+1)
DEFAULT_EVENT_DURATION = datetime.timedelta(hours=+1)
# If not None, passed to the calendar module's setfirstweekday function.
CALENDAR_FIRST_WEEKDAY = 1

View File

@ -4,14 +4,13 @@ from datetime import datetime, timedelta
from django import forms
from calebasse.dossiers.models import PatientRecord
from calebasse.personnes.models import Worker
from calebasse.actes.models import EventAct
from calebasse.agenda.models import Event, EventType
from calebasse.ressources.models import ActType
from calebasse.middleware.request import get_request
from ..dossiers.models import PatientRecord
from ..personnes.models import Worker
from ..ressources.models import ActType
from ..middleware.request import get_request
from ajax_select import make_ajax_field
from models import Event, EventWithAct, EventType
class NewAppointmentForm(forms.ModelForm):
date = forms.DateField(label=u'Date')
@ -19,11 +18,11 @@ class NewAppointmentForm(forms.ModelForm):
duration = forms.CharField(label=u'Durée',
help_text=u'en minutes; vous pouvez utiliser la roulette de votre souris.')
participants = make_ajax_field(EventAct, 'participants', 'worker-or-group', True)
patient = make_ajax_field(EventAct, 'patient', 'patientrecord', False)
participants = make_ajax_field(EventWithAct, 'participants', 'worker-or-group', True)
patient = make_ajax_field(EventWithAct, 'patient', 'patientrecord', False)
class Meta:
model = EventAct
model = EventWithAct
fields = (
'date',
'time',
@ -52,51 +51,27 @@ class NewAppointmentForm(forms.ModelForm):
duration = self.cleaned_data['duration']
try:
return int(duration)
except:
return None
except ValueError:
return 0
def save(self, commit=False):
start_datetime = datetime.combine(self.cleaned_data['date'],
def save(self, commit=True):
appointment = super(NewAppointmentForm, self).save(commit=False)
appointment.start_datetime = datetime.combine(self.cleaned_data['date'],
self.cleaned_data['time'])
end_datetime = start_datetime + timedelta(
appointment.end_datetime = appointment.start_datetime + timedelta(
minutes=self.cleaned_data['duration'])
patient = self.cleaned_data['patient']
creator = get_request().user
self.instance = EventAct.objects.create_patient_appointment(
creator=creator,
title=patient.display_name,
patient=patient,
participants=self.cleaned_data['participants'],
act_type=self.cleaned_data['act_type'],
service=self.service,
start_datetime=start_datetime,
end_datetime=end_datetime,
description='',
room=self.cleaned_data['room'],
note=None,)
return self.instance
appointment.recurrence_end_date = appointment.start_datetime.date()
appointment.creator = get_request().user
appointment.title = appointment.patient.display_name
appointment.service = self.service
appointment.clean()
if commit:
appointment.save()
return appointment
class UpdateAppointmentForm(NewAppointmentForm):
def __init__(self, instance, service=None, occurrence=None, **kwargs):
super(UpdateAppointmentForm, self).__init__(instance=instance,
service=service, **kwargs)
self.occurrence = occurrence
def save(self):
self.occurrence.start_time = datetime.combine(
self.cleaned_data['date'],
self.cleaned_data['time'])
self.occurrence.end_time = self.occurrence.start_time + timedelta(
minutes=self.cleaned_data['duration'])
self.occurrence.save()
patient = self.cleaned_data['patient']
creator = get_request().user
self.instance.title = patient.display_name
self.instance.participants = self.cleaned_data['participants']
self.instance.save()
return self.instance
pass
class NewEventForm(forms.ModelForm):
@ -106,11 +81,11 @@ class NewEventForm(forms.ModelForm):
time = forms.TimeField(label=u'Heure de début')
duration = forms.CharField(label=u'Durée',
help_text=u'en minutes; vous pouvez utiliser la roulette de votre souris.')
participants = make_ajax_field(EventAct, 'participants', 'worker-or-group', True)
participants = make_ajax_field(Event, 'participants', 'worker-or-group', True)
class Meta:
model = Event
widgets = {'services': forms.CheckboxSelectMultiple}
fields = (
'title',
'date',
@ -118,7 +93,6 @@ class NewEventForm(forms.ModelForm):
'duration',
'room',
'participants',
'services',
'event_type'
)
@ -135,22 +109,19 @@ class NewEventForm(forms.ModelForm):
except:
return None
def save(self, commit=False):
start_datetime = datetime.combine(self.cleaned_data['date'],
def save(self, commit=True):
event = super(NewEventForm, self).save(commit=False)
event.start_datetime = datetime.combine(self.cleaned_data['date'],
self.cleaned_data['time'])
end_datetime = start_datetime + timedelta(
event.end_datetime = event.start_datetime + timedelta(
minutes=self.cleaned_data['duration'])
self.instance = Event.objects.create_event(
title=self.cleaned_data['title'],
event_type=self.cleaned_data['event_type'],
participants=self.cleaned_data['participants'],
services=self.cleaned_data['services'],
start_datetime=start_datetime,
end_datetime=end_datetime,
description='',
room=self.cleaned_data['room'],
note=None,)
return self.instance
event.recurrence_end_date = event.start_datetime.date()
event.creator = get_request().user
event.service = self.service
event.clean()
if commit:
event.save()
return event
def clean(self):
cleaned_data = super(NewEventForm, self).clean()
@ -159,23 +130,3 @@ class NewEventForm(forms.ModelForm):
self._errors['title'] = self.error_class([
u"Ce champ est obligatoire pour les événements de type « Autre »."])
return cleaned_data
class UpdateEventForm(NewEventForm):
def __init__(self, instance, occurrence=None, **kwargs):
super(UpdateEventForm, self).__init__(instance=instance, **kwargs)
self.occurrence = occurrence
def save(self):
self.occurrence.start_time = datetime.combine(
self.cleaned_data['date'],
self.cleaned_data['time'])
self.occurrence.end_time = self.occurrence.start_time + timedelta(
minutes=self.cleaned_data['duration'])
self.occurrence.save()
creator = get_request().user
self.instance.participants = self.cleaned_data['participants']
self.instance.services = self.cleaned_data['services']
self.instance.save()
return self.instance

View File

@ -1,135 +1,59 @@
from datetime import datetime, timedelta, date
from datetime import datetime, timedelta, date, time
from interval import IntervalSet
from django.db import models
from model_utils.managers import InheritanceManager
from django.db.models import Q
from model_utils.managers import InheritanceManager, PassThroughManager, InheritanceQuerySet
from calebasse.agenda.conf import default
from calebasse.utils import weeks_since_epoch
from calebasse import agenda
__all__ = (
'EventManager',
'OccurrenceManager',
)
class EventManager(InheritanceManager):
""" This class allows you to manage events, appointment, ...
"""
def _set_event(self, event, participants=[], description='', services=[],
start_datetime=None, end_datetime=None, note=None, room=None, **rrule_params):
""" Private method to configure an Event or an EventAct
"""
event.description = description
event.participants = participants
event.services = services
event.room = room
if note is not None:
event.notes.create(note=note)
start_datetime = start_datetime or datetime.now().replace(
minute=0, second=0, microsecond=0
)
occurence_duration = default.DEFAULT_OCCURRENCE_DURATION
end_datetime = end_datetime or start_datetime + occurence_duration
event.add_occurrences(start_datetime, end_datetime, **rrule_params)
event.save()
return event
def create_event(self, title, event_type, participants=[], description='',
services=[], start_datetime=None, end_datetime=None, room=None, note=None,
**rrule_params):
"""
Convenience function to create an ``Event``, optionally create an
``EventType``, and associated ``Occurrence``s. ``Occurrence`` creation
rules match those for ``Event.add_occurrences``.
Args:
event_type: can be either an ``EventType`` object or the label
is either created or retrieved.
participants: List of CalebasseUser
start_datetime: will default to the current hour if ``None``
end_datetime: will default to ``start_datetime`` plus
default.DEFAULT_OCCURRENCE_DURATION hour if ``None``
freq, count, rrule_params:
follow the ``dateutils`` API (see http://labix.org/python-dateutil)
Returns:
Event object
"""
if isinstance(event_type, str):
event_type, created = agenda.models.EventType.objects.get_or_create(
label=event_type
)
event = self.create(title=title, event_type=event_type)
return self._set_event(event, participants, services = services,
start_datetime = start_datetime, end_datetime = end_datetime,
room=room, **rrule_params)
def create_holiday(self, start_date, end_date, peoples=[], services=[], motive=''):
event_type, created = agenda.models.EventType.objects.get_or_create(
label=u"Vacances"
)
event = self.create(title="Conge", event_type=event_type)
start_datetime = datetime(start_date.year, start_date.month, start_date.day)
end_datetime = datetime(end_date.year, end_date.month, end_date.day, 23, 59)
return self._set_event(event, peoples, motive, services, start_datetime, end_datetime)
class OccurrenceManager(models.Manager):
def daily_occurrences(self, date=None, participants=None, services=None,
event_type=None):
'''
Returns a queryset of for instances that have any overlap with a
particular day.
Args:
date: may be either a datetime.datetime, datetime.date object, or
``None``. If ``None``, default to the current day.
participants: a list of CalebasseUser
services: a list of services
event_type: a single, or a list of, event types
'''
date = date or datetime.now()
start = datetime(date.year, date.month, date.day)
end = start.replace(hour=23, minute=59, second=59)
qs = self.select_related('event').filter(
models.Q(
start_time__gte=start,
start_time__lte=end,
) |
models.Q(
end_time__gte=start,
end_time__lte=end,
) |
models.Q(
start_time__lt=start,
end_time__gt=end,
)
)
if participants:
qs = qs.filter(event__participants__in=participants)
if services:
qs = qs.filter(event__services__in=services)
if event_type:
if type(event_type) is list:
qs = qs.filter(event__event_type__in=event_type)
else:
qs = qs.filter(event__event_type=event_type)
class EventQuerySet(InheritanceQuerySet):
def for_today(self, today=None):
today = today or date.today()
weeks = weeks_since_epoch(today)
filters = [Q(start_datetime__gte=datetime.combine(today, time()),
start_datetime__lte=datetime.combine(today, time(23,59,59))) ]
base_q = Q(start_datetime__lte=datetime.combine(today, time(23,59,59))) & \
(Q(recurrence_end_date__gte=today) |
Q(recurrence_end_date__isnull=True))
for period in range(1, 6):
filters.append(base_q & Q(recurrence_week_offset=weeks % period,
recurrence_week_period=period, recurrence_week_day=today.weekday()))
qs = self.filter(reduce(Q.__or__, filters))
return qs
def daily_disponibility(self, date, occurrences, participants, time_tables, holidays):
def today_occurences(self, today=None):
today = today or date.today()
self = self.for_today(today)
occurences = ( e.today_occurence(today) for e in self )
return sorted(occurences, key=lambda e: e.start_datetime)
def daily_disponibilities(self, date, events, participants, time_tables,
holidays):
'''Slice the day into quarters between 8:00 and 19:00, and returns the
list of particpants with their status amon free, busy and away for each
hour and quarters.
date - the date of day we slice
occurences - a dictionnary of iterable of events indexed by participants
participants - an iterable of participants
time_tables - a dictionnaty of timetable applying for this day indexed by participants
holidays - a dictionnary of holidays applying for this day indexed by participants
'''
result = dict()
quarter = 0
occurrences_set = {}
events_set = {}
timetables_set = {}
holidays_set = {}
for participant in participants:
occurrences_set[participant.id] = IntervalSet((o.to_interval() for o in occurrences[participant.id] if not o.is_event_absence()))
events_set[participant.id] = IntervalSet((o.to_interval() for o in events[participant.id] if not o.is_event_absence()))
timetables_set[participant.id] = IntervalSet((t.to_interval(date) for t in time_tables[participant.id]))
holidays_set[participant.id] = IntervalSet((h.to_interval(date) for h in holidays[participant.id]))
start_datetime = datetime(date.year, date.month, date.day, 8, 0)
@ -137,15 +61,10 @@ class OccurrenceManager(models.Manager):
while (start_datetime.hour <= 19):
for participant in participants:
if not result.has_key(start_datetime.hour):
result[start_datetime.hour] = [0, 1, 2, 3]
result[start_datetime.hour][0] = []
result[start_datetime.hour][1] = []
result[start_datetime.hour][2] = []
result[start_datetime.hour][3] = []
result[start_datetime.hour] = [[], [], [], []]
quarter = 0
interval = IntervalSet.between(start_datetime, end_datetime, False)
if interval.intersection(occurrences_set[participant.id]):
if interval.intersection(events_set[participant.id]):
result[start_datetime.hour][quarter].append({'id': participant.id, 'dispo': 'busy'})
elif interval.intersection(holidays_set[participant.id]):
result[start_datetime.hour][quarter].append({'id': participant.id, 'dispo': 'busy'})
@ -158,31 +77,73 @@ class OccurrenceManager(models.Manager):
end_datetime += timedelta(minutes=15)
return result
def next_appoinment(self, patient_record):
qs = self.next_appoinments(patient_record)
class EventManager(PassThroughManager.for_queryset_class(EventQuerySet),
InheritanceManager):
""" This class allows you to manage events, appointment, ...
"""
def create_event(self, creator, title, event_type, participants=[], description='',
services=[], start_datetime=None, end_datetime=None, room=None, note=None, periodicity=1, until=False, **kwargs):
"""
Convenience function to create an ``Event``, optionally create an
``EventType``.
Args:
event_type: can be either an ``EventType`` object or the label
is either created or retrieved.
participants: List of CalebasseUser
start_datetime: will default to the current hour if ``None``
end_datetime: will default to ``start_datetime`` plus
default.DEFAULT_EVENT_DURATION hour if ``None``
Returns:
Event object
"""
if isinstance(event_type, str):
event_type, created = agenda.models.EventType.objects.get_or_create(
label=event_type
)
if not start_datetime:
now = datetime.now()
start_datetime = datetime.combine(now.date, time(now.hour))
if not end_datetime:
end_datetime = start_datetime + default.DEFAULT_EVENT_DURATION
if until is False:
until = start_datetime.date()
event = self.create(creator=creator,
title=title, start_datetime=start_datetime,
end_datetime=end_datetime, event_type=event_type,
room=room, recurrence_week_period=periodicity,
recurrence_end_date=until,
recurrence_week_day=start_datetime.weekday(), **kwargs)
event.services = services
event.participants = participants
return event
def next_appointment(self, patient_record):
qs = self.next_appointments(patient_record)
if qs:
return qs[0]
else:
return None
def next_appoinments(self, patient_record):
today = date.today()
return self.filter(start_time__gt=datetime(today.year, today.month, today.day)).\
filter(event__event_type__id=1).\
filter(event__eventact__patient=patient_record).\
prefetch_related('event__eventact').\
order_by('start_time')
def next_appointments(self, patient_record, today=None):
from calebasse.actes.models import Act
acts = Act.objects.next_acts(patient_record, today=today) \
.filter(parent_event__isnull=False) \
.select_related()
return [ a.parent_event.today_occurence(a.date) for a in acts ]
def last_appoinment(self, patient_record):
qs = self.last_appoinments(patient_record)
def last_appointment(self, patient_record):
qs = self.last_appointments(patient_record)
if qs:
return qs[0]
else:
return None
def last_appoinments(self, patient_record):
return self.filter(start_time__lt=datetime.now()).\
filter(event__event_type__id=1).\
filter(event__eventact__patient=patient_record).\
prefetch_related('event__eventact').\
order_by('-start_time')
def last_appointments(self, patient_record, today=None):
from calebasse.actes.models import Act
acts = Act.objects.last_acts(patient_record, today=today) \
.filter(parent_event__isnull=False) \
.select_related()
return [ a.parent_event.today_occurence(a.date) for a in acts ]

View File

@ -1,43 +1,23 @@
# -*- coding: utf-8 -*-
from datetime import datetime
from dateutil import rrule
from datetime import datetime, date, timedelta
from copy import copy
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.contrib.auth.models import User
from django.db import models
from ..middleware.request import get_request
from calebasse.agenda import managers
from calebasse.utils import weeks_since_epoch
from interval import Interval
__all__ = (
'Note',
'EventType',
'Event',
'Occurrence',
'EventWithAct',
)
class Note(models.Model):
'''
A generic model for adding simple, arbitrary notes to other models such as
``Event`` or ``Occurrence``.
'''
class Meta:
verbose_name = u'Note'
verbose_name_plural = u'Notes'
def __unicode__(self):
return self.note
note = models.TextField(_('note'))
created = models.DateTimeField(_('created'), auto_now_add=True)
content_type = models.ForeignKey(ContentType)
object_id = models.IntegerField()
class EventType(models.Model):
'''
Simple ``Event`` classifcation.
@ -55,14 +35,15 @@ class EventType(models.Model):
class Event(models.Model):
'''
Container model for general metadata and associated ``Occurrence`` entries.
Container model for general agenda events
'''
objects = managers.EventManager()
title = models.CharField(_('Title'), max_length=32, blank=True)
description = models.TextField(_('Description'), max_length=100)
event_type = models.ForeignKey(EventType, verbose_name=u"Type d'événement")
notes = generic.GenericRelation(Note, verbose_name=_('notes'))
creator = models.ForeignKey(User, verbose_name=_(u'Créateur'), blank=True, null=True)
create_date = models.DateTimeField(_(u'Date de création'), auto_now_add=True)
services = models.ManyToManyField('ressources.Service',
null=True, blank=True, default=None)
@ -71,99 +52,223 @@ class Event(models.Model):
room = models.ForeignKey('ressources.Room', blank=True, null=True,
verbose_name=u'Salle')
start_datetime = models.DateTimeField(_('Début'), blank=True, null=True, db_index=True)
end_datetime = models.DateTimeField(_('Fin'), blank=True, null=True)
PERIODS = (
(1, u'Toutes les semaines'),
(2, u'Une semaine sur deux'),
(3, u'Une semaine sur trois'),
(4, 'Une semaine sur quatre'),
(5, 'Une semaine sur cinq')
)
OFFSET = range(0,4)
recurrence_week_day = models.PositiveIntegerField(default=0)
recurrence_week_offset = models.PositiveIntegerField(
choices=zip(OFFSET, OFFSET),
verbose_name=u"Décalage en semaines par rapport au 1/1/1970 pour le calcul de période",
default=0,
db_index=True)
recurrence_week_period = models.PositiveIntegerField(
choices=PERIODS,
verbose_name=u"Période en semaines",
default=None,
blank=True,
null=True,
db_index=True)
recurrence_end_date = models.DateField(
verbose_name=_(u'Fin de la récurrence'),
blank=True, null=True,
db_index=True)
class Meta:
verbose_name = u'Evénement'
verbose_name_plural = u'Evénements'
ordering = ('title', )
ordering = ('start_datetime', 'end_datetime', 'title')
def __init__(self, *args, **kwargs):
if kwargs.get('start_datetime') and not kwargs.has_key('recurrence_end_date'):
kwargs['recurrence_end_date'] = kwargs.get('start_datetime').date()
super(Event, self).__init__(*args, **kwargs)
def clean(self):
'''Initialize recurrence fields if they are not.'''
if self.start_datetime:
if self.recurrence_week_period:
if self.recurrence_end_date and self.recurrence_end_date < self.start_datetime.date():
self.recurrence_end_date = self.start_datetime.date()
self.recurrence_week_day = self.start_datetime.weekday()
self.recurrence_week_offset = weeks_since_epoch(self.start_datetime) % self.recurrence_week_period
def timedelta(self):
'''Distance between start and end of the event'''
return self.end_datetime - self.start_datetime
def today_occurence(self, today=None):
'''For a recurring event compute the today 'Event'.
The computed event is the fake one that you cannot save to the database.
'''
today = today or date.today()
if not self.is_recurring():
if today == self.start_datetime.date():
return self
else:
return None
if today.weekday() != self.recurrence_week_day:
return None
if weeks_since_epoch(today) % self.recurrence_week_period != self.recurrence_week_offset:
return None
if not (self.start_datetime.date() <= today <= self.recurrence_end_date):
return None
start_datetime = datetime.combine(today, self.start_datetime.timetz())
end_datetime = start_datetime + self.timedelta()
event = copy(self)
event.start_datetime = start_datetime
event.end_datetime = end_datetime
event.recurrence_end_date = None
event.recurrence_week_offset = None
event.recurrence_week_period = None
event.parent = self
def save(*args, **kwarks):
raise RuntimeError()
event.save = save
return event
def next_occurence(self, today=None):
'''Returns the next occurence after today.'''
today = today or date.today()
for occurence in self.all_occurences():
if occurence.start_datetime.date() > today:
return occurence
def is_recurring(self):
'''Is this event multiple ?'''
return self.recurrence_week_period is not None
def all_occurences(self, limit=90):
'''Returns all occurences of this event as a list or pair (start_datetime,
end_datetime).
limit - compute occurrences until limit days in the future
Default is to limit to 90 days.
'''
if self.recurrence_week_period:
day = self.start_datetime.date()
max_end_date = max(date.today(), self.start_datetime.date()) + timedelta(days=limit)
end_date = min(self.recurrence_end_date or max_end_date, max_end_date)
delta = timedelta(days=self.recurrence_week_period*7)
while day <= end_date:
yield self.today_occurence(day)
day += delta
else:
yield self
def to_interval(self):
return Interval(self.start_datetime, self.end_datetime)
def is_event_absence(self):
return False
def __unicode__(self):
return self.title
def add_occurrences(self, start_time, end_time, room=None, **rrule_params):
'''
Add one or more occurences to the event using a comparable API to
``dateutil.rrule``.
If ``rrule_params`` does not contain a ``freq``, one will be defaulted
to ``rrule.DAILY``.
Because ``rrule.rrule`` returns an iterator that can essentially be
unbounded, we need to slightly alter the expected behavior here in order
to enforce a finite number of occurrence creation.
If both ``count`` and ``until`` entries are missing from ``rrule_params``,
only a single ``Occurrence`` instance will be created using the exact
``start_time`` and ``end_time`` values.
'''
rrule_params.setdefault('freq', rrule.DAILY)
if 'count' not in rrule_params and 'until' not in rrule_params:
self.occurrence_set.create(start_time=start_time, end_time=end_time)
else:
delta = end_time - start_time
for ev in rrule.rrule(dtstart=start_time, **rrule_params):
self.occurrence_set.create(start_time=ev, end_time=ev + delta)
def upcoming_occurrences(self):
'''
Return all occurrences that are set to start on or after the current
time.
'''
return self.occurrence_set.filter(start_time__gte=datetime.now())
def next_occurrence(self):
'''
Return the single occurrence set to start on or after the current time
if available, otherwise ``None``.
'''
upcoming = self.upcoming_occurrences()
return upcoming and upcoming[0] or None
def daily_occurrences(self, dt=None):
'''
Convenience method wrapping ``Occurrence.objects.daily_occurrences``.
'''
return Occurrence.objects.daily_occurrences(dt=dt, event=self)
class EventWithActManager(managers.EventManager):
def create_patient_appointment(self, creator, title, patient,
doctors=[], act_type=None, service=None, start_datetime=None, end_datetime=None,
room=None, periodicity=1, until=False):
appointment = self.create_event(creator=creator,
title=title,
event_type=EventType(id=1),
participants=doctors,
services=[service],
start_datetime=start_datetime,
end_datetime=end_datetime,
room=room,
periodicity=periodicity,
until=until,
act_type=act_type,
patient=patient)
return appointment
class Occurrence(models.Model):
'''
Represents the start end time for a specific occurrence of a master ``Event``
object.
'''
start_time = models.DateTimeField()
end_time = models.DateTimeField()
event = models.ForeignKey('Event', verbose_name=_('event'), editable=False)
notes = models.ManyToManyField('Note', verbose_name=_('notes'),
null=True, blank=True, default=None)
objects = managers.OccurrenceManager()
class Meta:
verbose_name = u'Occurrence'
verbose_name_plural = u'Occurrences'
ordering = ('start_time', 'end_time')
def __unicode__(self):
return u'%s: %s' % (self.title, self.start_time.isoformat())
def __cmp__(self, other):
return cmp(self.start_time, other.start_time)
class EventWithAct(Event):
'''An event corresponding to an act.'''
objects = EventWithActManager()
act_type = models.ForeignKey('ressources.ActType',
verbose_name=u'Type d\'acte')
patient = models.ForeignKey('dossiers.PatientRecord')
@property
def title(self):
return self.event.title
def act(self):
return self.get_or_create_act()
@property
def event_type(self):
return self.event.event_type
def get_or_create_act(self, today=None):
from ..actes.models import Act, ActValidationState
today = today or self.start_datetime.date()
act, created = Act.objects.get_or_create(patient=self.patient,
parent_event=getattr(self, 'parent', self),
date=today,
act_type=self.act_type)
self.update_act(act)
if created:
ActValidationState.objects.create(act=act, state_name='NON_VALIDE',
author=self.creator, previous_state=None)
return act
def to_interval(self):
return Interval(self.start_time, self.end_time)
def update_act(self, act):
'''Update an act to match details of the meeting'''
delta = self.timedelta()
duration = delta.seconds // 60
act._duration = duration
act.doctors = self.participants.select_subclasses()
act.act_type = self.act_type
act.patient = self.patient
act.date = self.start_datetime.date()
act.save()
def save(self, *args, **kwargs):
'''Force event_type to be patient meeting.'''
self.clean()
self.event_type = EventType(id=1)
super(EventWithAct, self).save(*args, **kwargs)
# list of occurences may have changed
from ..actes.models import Act
occurences = list(self.all_occurences())
acts = Act.objects.filter(parent_event=self)
occurences_by_date = dict((o.start_datetime.date(), o) for o in occurences)
acts_by_date = dict()
for a in acts:
# sanity check
assert a.date not in acts_by_date
acts_by_date[a.date] = a
for a in acts:
o = occurences_by_date.get(a.date)
if o:
o.update_act(a)
else:
if len(a.actvalidationstate_set.all()) > 1:
a.parent_event = None
a.save()
else:
a.delete()
participants = self.participants.select_subclasses()
for o in occurences:
if o.start_datetime.date() in acts_by_date:
continue
o.get_or_create_act()
def is_event_absence(self):
if self.event.event_type.id != 1:
return False
event_act = self.event.eventact
return event_act.is_absent()
return self.act.is_absent()
def __unicode__(self):
kwargs = {
'patient': self.patient,
'start_datetime': self.start_datetime,
'act_type': self.act_type
}
kwargs['doctors'] = ', '.join(map(unicode, self.participants.all())) if self.id else ''
return u'Rdv le {start_datetime} de {patient} avec {doctors} pour ' \
'{act_type} ({act_type.id})'.format(**kwargs)

View File

@ -23,11 +23,11 @@
{% endif %}
{% if appointment.event_id %}
{% if appointment.patient_record_id %}
<button title="Éditer un rendez-vous" class="edit-appointment icon-edit" data-occurrence-id="{{ appointment.occurrence_id }}"></button>
<button title="Éditer un rendez-vous" class="edit-appointment icon-edit" data-event-id="{{ appointment.event_id }}"></button>
{% else %}
<button title="Éditer un événement" class="edit-event icon-edit" data-occurrence-id="{{ appointment.occurrence_id }}">
<button title="Éditer un événement" class="edit-event icon-edit" data-event-id="{{ appointment.event_id }}">
{% endif %}
<button class="remove-appointment icon-remove-sign" title="Supprimer un rendez-vous" data-occurrence-id="{{ appointment.occurrence_id }}" data-rdv="{{ appointment.title }}"></button>
<button class="remove-appointment icon-remove-sign" title="Supprimer un rendez-vous" data-event-id="{{ appointment.event_id }}" data-rdv="{{ appointment.title }}"></button>
{% endif %}
</span>
</h3>
@ -69,7 +69,7 @@
</p>
<a href="/{{ service }}/dossiers/{{ appointment.patient_record_id }}/view" target="_blank">Dossier patient</a> -
<a href="/{{ service }}/dossiers/{{ appointment.patient_record_id }}/view#tab=5" target="_blank">Prochains rendez-vous</a> -
<a href="#" class="generate-mail-btn" data-dossier-id="{{ appointment.patient_record_id }}" data-occurence-id="{{ appointment.occurrence_id }}" data-next-url="{{ request.get_full_path }}">Courrier</a>
<a href="#" class="generate-mail-btn" data-dossier-id="{{ appointment.patient_record_id }}" data-date="{{date}}" data-occurence-id="{{ appointment.occurrence_id }}" data-next-url="{{ request.get_full_path }}">Courrier</a>
{% endif %}
{% if appointment.validation %}
<div><span>{% if appointment.validation.1 %}<strong>{{ appointment.validation.2 }}</strong>, le {{ appointment.validation.1.created }} par {{ appointment.validation.1.author }}

View File

@ -70,11 +70,11 @@
{% endif %}
{% if appointment.event_id %}
{% if appointment.patient_record_id %}
<button title="Éditer un rendez-vous" class="edit-appointment icon-edit" data-occurrence-id="{{ appointment.occurrence_id }}"></button>
<button title="Éditer un rendez-vous" class="edit-appointment icon-edit" data-event-id="{{ appointment.event_id }}"></button>
{% else %}
<button title="Éditer un événement" class="edit-event icon-edit" data-occurrence-id="{{ appointment.occurrence_id }}">
<button title="Éditer un événement" class="edit-event icon-edit" data-event-id="{{ appointment.event_id }}">
{% endif %}
<button class="remove-appointment icon-remove-sign" title="Supprimer un rendez-vous" data-occurrence-id="{{ appointment.occurrence_id }}" data-rdv="{{ appointment.title }}"></button>
<button class="remove-appointment icon-remove-sign" title="Supprimer un rendez-vous" data-event-id="{{ appointment.event_id }}" data-rdv="{{ appointment.title }}"></button>
{% endif %}
</span>
</h3>
@ -112,7 +112,7 @@
</p>
<a href="/{{ service }}/dossiers/{{ appointment.patient_record_id }}/view" target="_blank">Dossier patient</a> -
<a href="/{{ service }}/dossiers/{{ appointment.patient_record_id }}/view#tab=5" target="_blank">Prochains rendez-vous</a> -
<a href="#" class="generate-mail-btn" data-dossier-id="{{ appointment.patient_record_id }}" data-occurence-id="{{ appointment.occurrence_id }}" data-next-url="{{ request.get_full_path }}">Courrier</a>
<a href="#" class="generate-mail-btn" data-dossier-id="{{ appointment.patient_record_id }}" data-date="{{date}}" data-occurence-id="{{ appointment.occurrence_id }}" data-next-url="{{ request.get_full_path }}">Courrier</a>
{% endif %}
{% if appointment.validation %}
<div><span>{% if appointment.validation.1 %}<strong>{{ appointment.validation.2 }}</strong>, le {{ appointment.validation.1.created }} par {{ appointment.validation.1.author }}

View File

@ -4,70 +4,111 @@ when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from datetime import datetime
from datetime import datetime, date, timedelta
from django.test import TestCase
from django.contrib.auth.models import User
from datetime import datetime, date
from dateutil import rrule
from calebasse.agenda.models import Occurrence, Event
from calebasse.actes.models import EventAct
from calebasse.dossiers.models import PatientRecord
from calebasse.agenda.models import Event, EventType, EventWithAct
from calebasse.dossiers.models import create_patient
from calebasse.ressources.models import ActType, Service, WorkerType
from calebasse.personnes.models import Worker
from calebasse.actes.models import Act
class EventTest(TestCase):
fixtures = ['services', 'filestates']
def setUp(self):
self.creator = User.objects.create(username='John')
def test_create_events(self):
event = Event.objects.create_event("test 1", 'un test', description='42 42',
start_datetime=datetime(2012, 10, 20, 13), end_datetime=datetime(2012, 10, 20, 14),
freq=rrule.WEEKLY, count=3)
self.assertEqual(str(event), 'test 1')
def test_recurring_events(self):
event = Event.objects.create(start_datetime=datetime(2012, 10, 20, 13),
end_datetime=datetime(2012, 10, 20, 13, 30), event_type=EventType(id=1),
recurrence_week_period=3, recurrence_end_date=date(2012, 12, 1))
event.clean()
event.save()
# Test model
self.assertEqual(event.timedelta(), timedelta(minutes=30))
occurences = list(event.all_occurences())
self.assertEqual(occurences[0].start_datetime,
datetime(2012, 10, 20, 13))
self.assertEqual(occurences[0].end_datetime,
datetime(2012, 10, 20, 13, 30))
self.assertEqual(occurences[1].start_datetime,
datetime(2012, 11, 10, 13))
self.assertEqual(occurences[1].end_datetime,
datetime(2012, 11, 10, 13, 30))
self.assertEqual(occurences[2].start_datetime,
datetime(2012, 12, 1, 13))
self.assertEqual(occurences[2].end_datetime,
datetime(2012, 12, 1, 13, 30))
self.assertEqual(len(occurences), 3)
self.assertTrue(event.is_recurring())
self.assertEqual(event.next_occurence(today=date(2012, 10, 21)).start_datetime,
datetime(2012, 11, 10, 13))
self.assertEqual(event.next_occurence(today=date(2012, 11, 30)).start_datetime,
datetime(2012, 12, 1, 13))
self.assertEqual(event.next_occurence(today=date(2012, 12, 2)), None)
# Test manager
i = datetime(2012, 10, 1)
while i < datetime(2013, 2, 1):
d = i.date()
if d in (date(2012, 10, 20), date(2012, 11, 10), date(2012, 12, 1)):
self.assertEqual(list(Event.objects.for_today(d)), [event], d)
else:
self.assertEqual(list(Event.objects.for_today(d)), [], d)
i += timedelta(days=1)
def test_create_appointments(self):
service_camsp = Service.objects.create(name='CAMSP')
service_camsp = Service.objects.get(name='CAMSP')
patient = create_patient('Jean', 'Lepoulpe', service_camsp, self.creator, date_selected=datetime(2020, 10, 5))
patient = create_patient('Jean', 'LEPOULPE', service_camsp, self.creator, date_selected=datetime(2020, 10, 5))
wtype = WorkerType.objects.create(name='ElDoctor', intervene=True)
therapist1 = Worker.objects.create(first_name='Bob', last_name='Leponge', type=wtype)
therapist2 = Worker.objects.create(first_name='Jean', last_name='Valjean', type=wtype)
therapist3 = Worker.objects.create(first_name='Pierre', last_name='PaulJacques', type=wtype)
act_type = ActType.objects.create(name='trepanation')
service = Service.objects.create(name='CMPP')
act_event = EventAct.objects.create_patient_appointment(self.creator, 'RDV avec M X', patient,
appointment1 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV avec M X', patient,
[therapist1, therapist2], act_type, service,
start_datetime=datetime(2020, 10, 2, 7, 15),
end_datetime=datetime(2020, 10, 2, 9, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2040, 10, 2))
act_event2 = EventAct.objects.create_patient_appointment(self.creator, 'RDV avec M Y', patient, [therapist3],
periodicity=None, until=None)
self.assertEqual(unicode(appointment1), u'Rdv le 2020-10-02 07:15:00 de Jean LEPOULPE avec Bob LEPONGE, Jean VALJEAN pour trepanation (1)')
def test_create_recurring_appointment(self):
service_camsp = Service.objects.get(name='CAMSP')
patient = create_patient('Jean', 'LEPOULPE', service_camsp, self.creator, date_selected=datetime(2020, 10, 5))
wtype = WorkerType.objects.create(name='ElDoctor', intervene=True)
therapist3 = Worker.objects.create(first_name='Pierre', last_name='PaulJacques', type=wtype)
act_type = ActType.objects.create(name='trepanation')
service = Service.objects.create(name='CMPP')
appointment2 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV avec M Y', patient, [therapist3],
act_type, service, start_datetime=datetime(2020, 10, 2, 10, 15),
end_datetime=datetime(2020, 10, 2, 12, 20),
freq=rrule.WEEKLY, byweekday=rrule.FR, until=datetime(2021, 10, 2))
self.assertEqual(str(act_event), 'Rdv le 2020-10-02 07:15:00 de Jean Lepoulpe avec Bob Leponge, Jean Valjean pour trepanation (1)')
self.assertEqual(
str(Occurrence.objects.daily_occurrences(datetime(2020, 10, 8), [therapist2])),
'[]'
)
self.assertEqual(
str(Occurrence.objects.daily_occurrences(datetime(2020, 10, 9), [therapist2])),
'[<Occurrence: RDV avec M X: 2020-10-09T07:15:00>]'
)
self.assertEqual(
str(Occurrence.objects.daily_occurrences(datetime(2020, 10, 9), [therapist3])),
'[<Occurrence: RDV avec M Y: 2020-10-09T10:15:00>]'
)
periodicity=2, until=date(2020, 10, 16))
occurences = list(appointment2.all_occurences())
self.assertEqual(len(occurences), 2)
self.assertEqual(Act.objects.filter(parent_event=appointment2).count(),
2)
self.assertEqual(occurences[0].act.date, occurences[0].start_datetime.date())
self.assertEqual(occurences[1].act.date, occurences[1].start_datetime.date())
self.assertEqual(Act.objects.filter(parent_event=appointment2).count(),
2)
appointment2.recurrence_week_period = None
appointment2.save()
self.assertEqual(Act.objects.filter(parent_event=appointment2).count(),
1)
appointment2.recurrence_week_period = 2
appointment2.recurrence_end_date = date(2020, 10, 16)
appointment2.save()
occurences = list(appointment2.all_occurences())
self.assertEqual(len(occurences), 2)
self.assertEqual(Act.objects.filter(parent_event=appointment2).count(), 2)
occurences[1].act.set_state('ANNUL_NOUS', self.creator)
appointment2.recurrence_week_period = None
appointment2.save()
occurences = list(appointment2.all_occurences())
self.assertEqual(len(occurences), 1)
self.assertEqual(Act.objects.filter(parent_event=appointment2).count(), 1)
self.assertEqual(Act.objects.count(), 2)
def test_create_holiday(self):
"""docstring for test_create_event"""
wtype = WorkerType.objects.create(name='ElProfessor', intervene=True)
user = Worker.objects.create(first_name='Jean-Claude', last_name='Van Damme', type=wtype)
event = Event.objects.create_holiday(date(2012, 12, 12), date(2012,12,30),
[user], motive='tournage d\'un film')
self.assertEqual(str(event), 'Conge')
#event = user.event.occurrence_set.all()[0]
#self.assertEqual(event.end_time - event.start_time, timedelta(0, 7200))

View File

@ -16,13 +16,13 @@ agenda_patterns = patterns('',
url(r'^nouveau-rdv/$',
NewAppointmentView.as_view(),
name='nouveau-rdv'),
url(r'^update-rdv/(?P<id>\d+)$',
url(r'^update-rdv/(?P<pk>\d+)$',
UpdateAppointmentView.as_view(),
name='update-rdv'),
url(r'^new-event/$',
NewEventView.as_view(),
name='new-event'),
url(r'^update-event/(?P<id>\d+)$',
url(r'^update-event/(?P<pk>\d+)$',
UpdateEventView.as_view(),
name='update-event'),
url(r'^activite-du-service/$',

View File

@ -7,21 +7,19 @@ from django.shortcuts import redirect
from django.http import HttpResponseRedirect
from calebasse.cbv import TemplateView, CreateView, UpdateView
from calebasse.agenda.models import Occurrence, Event, EventType
from calebasse.agenda.models import Event, EventType, EventWithAct
from calebasse.personnes.models import TimeTable, Holiday
from calebasse.actes.models import EventAct
from calebasse.agenda.appointments import get_daily_appointments, get_daily_usage
from calebasse.personnes.models import Worker
from calebasse.ressources.models import WorkerType, Room
from calebasse.actes.validation import get_acts_of_the_day
from calebasse.actes.validation import (get_acts_of_the_day,
get_days_with_acts_not_locked)
from calebasse.actes.validation_states import VALIDATION_STATES
from calebasse.actes.models import Act, ValidationMessage
from calebasse.actes.validation import (automated_validation,
unlock_all_acts_of_the_day, are_all_acts_of_the_day_locked)
from calebasse.actes.validation import (automated_validation, unlock_all_acts_of_the_day)
from calebasse import cbv
from forms import (NewAppointmentForm, NewEventForm,
UpdateAppointmentForm, UpdateEventForm)
from forms import (NewAppointmentForm, NewEventForm, UpdateAppointmentForm)
def redirect_today(request, service):
'''If not date is given we redirect on the agenda for today'''
@ -70,41 +68,42 @@ class AgendaServiceActivityView(TemplateView):
appointments_times = dict()
appoinment_type = EventType.objects.get(id=1)
meeting_type = EventType.objects.get(id=2)
occurrences = Occurrence.objects.daily_occurrences(context['date'],
services=[self.service],
event_type=[appoinment_type, meeting_type])
for occurrence in occurrences:
start_time = occurrence.start_time.strftime("%H:%M")
if not appointments_times.has_key(start_time):
appointments_times[start_time] = dict()
appointments_times[start_time]['row'] = 0
appointments_times[start_time]['appointments'] = []
plain_events = Event.objects.for_today(self.date) \
.filter(services=self.service,
event_type__in=[appoinment_type, meeting_type])
events = [ e.today_occurence(self.date) for e in plain_events ]
for event in events:
start_datetime = event.start_datetime.strftime("%H:%M")
if not appointments_times.has_key(start_datetime):
appointments_times[start_datetime] = dict()
appointments_times[start_datetime]['row'] = 0
appointments_times[start_datetime]['appointments'] = []
appointment = dict()
length = occurrence.end_time - occurrence.start_time
length = event.end_datetime - event.start_datetime
if length.seconds:
length = length.seconds / 60
appointment['length'] = "%sm" % length
if occurrence.event.event_type == EventType.objects.get(id=1):
if event.event_type == EventType.objects.get(id=1):
appointment['type'] = 1
event_act = occurrence.event.eventact
event_act = event.act
appointment['label'] = event_act.patient.display_name
appointment['act'] = event_act.act_type.name
elif occurrence.event.event_type == EventType.objects.get(id=2):
elif event.event_type == EventType.objects.get(id=2):
appointment['type'] = 2
appointment['label'] = '%s - %s' % (occurrence.event.event_type.label,
occurrence.event.title)
appointment['label'] = '%s - %s' % (event.event_type.label,
event.title)
else:
appointment['type'] = 0
appointment['label'] = '???'
appointment['participants'] = occurrence.event.participants.all()
appointments_times[start_time]['row'] += 1
appointments_times[start_time]['appointments'].append(appointment)
appointment['participants'] = event.participants.all()
appointments_times[start_datetime]['row'] += 1
appointments_times[start_datetime]['appointments'].append(appointment)
context['appointments_times'] = sorted(appointments_times.items())
return context
class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateView):
model = EventAct
model = EventWithAct
form_class = NewAppointmentForm
template_name = 'agenda/nouveau-rdv.html'
success_url = '..'
@ -119,21 +118,16 @@ class NewAppointmentView(cbv.ReturnToObjectMixin, cbv.ServiceFormMixin, CreateVi
class UpdateAppointmentView(UpdateView):
model = EventAct
model = EventWithAct
form_class = UpdateAppointmentForm
template_name = 'agenda/update-rdv.html'
success_url = '..'
def get_object(self, queryset=None):
self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
if self.occurrence.event.eventact:
return self.occurrence.event.eventact
def get_initial(self):
initial = super(UpdateView, self).get_initial()
initial['date'] = self.object.date
initial['time'] = self.occurrence.start_time.strftime("%H:%M")
time = self.occurrence.end_time - self.occurrence.start_time
initial['date'] = self.object.start_datetime.strftime("%Y-%m-%d")
initial['time'] = self.object.start_datetime.strftime("%H:%M")
time = self.object.end_datetime - self.object.start_datetime
if time:
time = time.seconds / 60
else:
@ -144,7 +138,6 @@ class UpdateAppointmentView(UpdateView):
def get_form_kwargs(self):
kwargs = super(UpdateAppointmentView, self).get_form_kwargs()
kwargs['occurrence'] = self.occurrence
kwargs['service'] = self.service
return kwargs
@ -165,21 +158,18 @@ class NewEventView(CreateView):
initial['room'] = self.request.GET.get('room')
return initial
class UpdateEventView(UpdateView):
model = Event
form_class = UpdateEventForm
form_class = NewEventForm
template_name = 'agenda/update-event.html'
success_url = '..'
def get_object(self, queryset=None):
self.occurrence = Occurrence.objects.get(id=self.kwargs['id'])
return self.occurrence.event
def get_initial(self):
initial = super(UpdateEventView, self).get_initial()
initial['date'] = self.occurrence.start_time.date()
initial['time'] = self.occurrence.start_time.strftime("%H:%M")
time = self.occurrence.end_time - self.occurrence.start_time
initial['date'] = self.object.start_datetime.strftime("%Y-%m-%d")
initial['time'] = self.object.start_datetime.strftime("%H:%M")
time = self.object.end_datetime - self.object.start_datetime
if time:
time = time.seconds / 60
else:
@ -188,16 +178,8 @@ class UpdateEventView(UpdateView):
initial['participants'] = self.object.participants.values_list('id', flat=True)
return initial
def get_form_kwargs(self):
kwargs = super(UpdateEventView, self).get_form_kwargs()
kwargs['occurrence'] = self.occurrence
return kwargs
def new_appointment(request):
pass
class AgendaServiceActValidationView(TemplateView):
template_name = 'agenda/act-validation.html'
def acts_of_the_day(self):
@ -299,7 +281,6 @@ class UnlockAllView(CreateView):
class AgendasTherapeutesView(AgendaHomepageView):
template_name = 'agenda/agendas-therapeutes.html'
def get_context_data(self, **kwargs):
@ -312,22 +293,24 @@ class AgendasTherapeutesView(AgendaHomepageView):
holidays = Holiday.objects.select_related('worker'). \
for_period(self.date, self.date). \
order_by('start_date')
occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
plain_events = Event.objects.for_today(self.date) \
.order_by('start_datetime').select_subclasses()
events = [ e.today_occurence(self.date) for e in plain_events ]
occurrences_workers = {}
events_workers = {}
time_tables_workers = {}
holidays_workers = {}
context['workers_agenda'] = []
for worker in context['workers']:
time_tables_worker = [tt for tt in time_tables if tt.worker.id == worker.id]
occurrences_worker = [o for o in occurrences if worker.id in o.event.participants.values_list('id', flat=True)]
events_worker = [o for o in events if worker.id in o.participants.values_list('id', flat=True)]
holidays_worker = [h for h in holidays if h.worker_id in (None, worker.id)]
occurrences_workers[worker.id] = occurrences_worker
events_workers[worker.id] = events_worker
time_tables_workers[worker.id] = time_tables_worker
holidays_workers[worker.id] = holidays_worker
context['workers_agenda'].append({'worker': worker,
'appointments': get_daily_appointments(context['date'], worker, self.service,
time_tables_worker, occurrences_worker, holidays_worker)})
time_tables_worker, events_worker, holidays_worker)})
for worker_agenda in context.get('workers_agenda', []):
patient_appointments = [x for x in worker_agenda['appointments'] if x.patient_record_id]
@ -342,21 +325,16 @@ class AgendasTherapeutesView(AgendaHomepageView):
return context
class JoursNonVerrouillesView(TemplateView):
template_name = 'agenda/days-not-locked.html'
def get_context_data(self, **kwargs):
context = super(JoursNonVerrouillesView, self).get_context_data(**kwargs)
acts = EventAct.objects.filter(is_billed=False,
acts = Act.objects.filter(is_billed=False,
patient__service=self.service).order_by('date')
days_not_locked = []
for act in acts:
current_day = datetime.datetime(act.date.year, act.date.month, act.date.day)
if not current_day in days_not_locked:
locked = are_all_acts_of_the_day_locked(current_day, self.service)
if not locked:
days_not_locked.append(current_day)
context['days_not_locked'] = days_not_locked
days = set(acts.values_list('date', flat=True))
max_day, min_day = max(days), min(days)
days &= set(get_days_with_acts_not_locked(min_day, max_day, self.service))
context['days_not_locked'] = days
return context
class RessourcesView(TemplateView):
@ -366,7 +344,9 @@ class RessourcesView(TemplateView):
def get_context_data(self, **kwargs):
context = super(RessourcesView, self).get_context_data(**kwargs)
occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
plain_events = Event.objects.for_today(self.date) \
.order_by('start_datetime').select_subclasses()
events = [ e.today_occurence(self.date) for e in plain_events ]
context['ressources_types'] = []
context['ressources_agenda'] = []
@ -376,13 +356,13 @@ class RessourcesView(TemplateView):
context['ressources_types'].append(data)
ressources.extend(data['ressources'])
occurrences_ressources = {}
events_ressources = {}
for ressource in ressources:
occurrences_ressource = [o for o in occurrences if ressource == o.event.room]
occurrences_ressources[ressource.id] = occurrences_ressource
events_ressource = [e for e in events if ressource == e.room]
events_ressources[ressource.id] = events_ressource
context['ressources_agenda'].append({'ressource': ressource,
'appointments': get_daily_usage(context['date'], ressource,
self.service, occurrences_ressource)})
self.service, events_ressource)})
return context
@ -401,13 +381,15 @@ class AjaxWorkerTabView(TemplateView):
holidays_worker = Holiday.objects.for_worker_id(worker_id). \
for_period(self.date, self.date). \
order_by('start_date')
occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
occurrences_worker = [o for o in occurrences if worker_id in o.event.participants.values_list('id', flat=True)]
plain_events = Event.objects.for_today(self.date) \
.order_by('start_datetime').select_subclasses()
events = [ e.today_occurence(self.date) for e in plain_events ]
events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
worker = Worker.objects.get(pk=worker_id)
context['worker_agenda'] = {'worker': worker,
'appointments': get_daily_appointments(context['date'], worker, self.service,
time_tables_worker, occurrences_worker, holidays_worker)}
time_tables_worker, events_worker, holidays_worker)}
return context
class AjaxWorkerDisponibilityColumnView(TemplateView):
@ -425,16 +407,16 @@ class AjaxWorkerDisponibilityColumnView(TemplateView):
holidays_worker = Holiday.objects.for_worker_id(worker_id). \
for_period(self.date, self.date). \
order_by('start_date')
occurrences = Occurrence.objects.daily_occurrences(context['date']).order_by('start_time')
occurrences_worker = [o for o in occurrences if worker_id in o.event.participants.values_list('id', flat=True)]
events = Event.objects.today_occurences(self.date)
events_worker = [e for e in events if worker_id in e.participants.values_list('id', flat=True)]
worker = Worker.objects.get(pk=worker_id)
time_tables_workers = {worker.id: time_tables_worker}
occurrences_workers = {worker.id: occurrences_worker}
events_workers = {worker.id: events_worker}
holidays_workers = {worker.id: holidays_worker}
context['initials'] = worker.get_initials()
context['worker_id'] = worker.id
context['disponibility'] = Occurrence.objects.daily_disponibility(context['date'],
occurrences_workers, [worker], time_tables_workers, holidays_workers)
context['disponibility'] = Event.objects.daily_disponibilities(self.date,
events_workers, [worker], time_tables_workers, holidays_workers)
return context

View File

@ -1,7 +1,7 @@
from tastypie.authorization import DjangoAuthorization
from tastypie.resources import ModelResource
from calebasse.agenda.models import Event, Occurrence
from calebasse.agenda.models import Event
from calebasse.dossiers.models import PatientRecord, PatientAddress
@ -11,12 +11,6 @@ class EventResource(ModelResource):
resource_name = 'event'
authorization = DjangoAuthorization()
class OccurrenceResource(ModelResource):
class Meta:
queryset = Occurrence.objects.all()
resource_name = 'occurrence'
authorization = DjangoAuthorization()
class PatientRecordRessource(ModelResource):
class Meta:
queryset = PatientRecord.objects.all()
@ -31,6 +25,5 @@ class PatientAddressRessource(ModelResource):
patientaddress_ressource = PatientAddressRessource()
event_resource = EventResource()
occurrence_resource = OccurrenceResource()
patientrecord_resource = PatientRecordRessource()

View File

@ -578,7 +578,7 @@ class PatientRecord(ServiceLinkedAbstractModel, PatientContact):
cmpp = Service.objects.get(name='CMPP')
for act in acts:
if act.is_state('VALIDE') and act.is_billable() and \
act.date >= self.get_state().date_selected and \
act.date >= self.get_state().date_selected.date() and \
are_all_acts_of_the_day_locked(act.date):
cared, hc = act.is_act_covered_by_diagnostic_healthcare()
if hc:

View File

@ -15,7 +15,8 @@ from django.contrib import messages
from calebasse import cbv
from calebasse.doc_templates import make_doc_from_template
from calebasse.dossiers import forms
from calebasse.agenda.models import Occurrence
from calebasse.agenda.models import Event, EventWithAct
from calebasse.actes.models import Act
from calebasse.agenda.appointments import Appointment
from calebasse.dossiers.models import (PatientRecord, PatientContact,
PatientAddress, Status, FileState, create_patient, CmppHealthCareTreatment,
@ -27,20 +28,20 @@ from calebasse.ressources.models import (Service,
def get_next_rdv(patient_record):
next_rdv = {}
occurrence = Occurrence.objects.next_appoinment(patient_record)
if occurrence:
next_rdv['start_datetime'] = occurrence.start_time
next_rdv['participants'] = occurrence.event.participants.all()
next_rdv['act_type'] = occurrence.event.eventact.act_type
event = Event.objects.next_appointment(patient_record)
if event:
next_rdv['start_datetime'] = event.start_time
next_rdv['participants'] = event.participants.all()
next_rdv['act_type'] = event.eventact.act_type
return next_rdv
def get_last_rdv(patient_record):
last_rdv = {}
occurrence = Occurrence.objects.last_appoinment(patient_record)
if occurrence:
last_rdv['start_datetime'] = occurrence.start_time
last_rdv['participants'] = occurrence.event.participants.all()
last_rdv['act_type'] = occurrence.event.eventact.act_type
event = Event.objects.last_appointment(patient_record)
if event:
last_rdv['start_datetime'] = event.start_time
last_rdv['participants'] = event.participants.all()
last_rdv['act_type'] = event.eventact.act_type
return last_rdv
class NewPatientRecordView(cbv.FormView, cbv.ServiceViewMixin):
@ -254,17 +255,17 @@ class PatientRecordView(cbv.ServiceViewMixin, cbv.MultiUpdateView):
ctx['service_id'] = self.service.id
ctx['states'] = FileState.objects.filter(patient=self.object).filter(status__services=self.service)
ctx['next_rdvs'] = []
for rdv in Occurrence.objects.next_appoinments(ctx['object']):
state = rdv.event.eventact.get_state()
for act in Act.objects.next_acts(ctx['object']).select_related():
state = act.get_state()
if not state.previous_state:
state = None
ctx['next_rdvs'].append((rdv, state))
ctx['next_rdvs'].append((act.parent_event, state))
ctx['last_rdvs'] = []
for rdv in Occurrence.objects.last_appoinments(ctx['object']):
state = rdv.event.eventact.get_state()
for act in Act.objects.last_acts(ctx['object']):
state = act.get_state()
if not state.previous_state:
state = None
ctx['last_rdvs'].append((rdv, state))
ctx['last_rdvs'].append((act.parent_event, state))
ctx['status'] = []
if ctx['object'].service.name == "CMPP":
if ctx['object'].last_state.status.type == "ACCUEIL":
@ -577,9 +578,12 @@ class GenerateRtfFormView(cbv.FormView):
ctx['object'] = PatientRecord.objects.get(id=self.kwargs['patientrecord_id'])
ctx['service_id'] = self.service.id
if self.request.GET.get('event-id'):
date = self.request.GET.get('date')
date = datetime.strptime(date, '%Y-%m-%d').date()
appointment = Appointment()
occurrence = Occurrence.objects.get(id=self.request.GET.get('event-id'))
appointment.init_from_occurrence(occurrence, self.service)
event = Event.objects.get(id=self.request.GET.get('event-id'))
event = event.today_occurence(date)
appointment.init_from_event(event, self.service)
ctx['appointment'] = appointment
return ctx
@ -632,21 +636,16 @@ class PatientRecordsQuotationsView(cbv.ListView):
else:
qs = qs.filter(last_state__status__type__in='')
qs_events = Occurrence.objects.select_related('event')
try:
date_actes_start = datetime.strptime(form.data['date_actes_start'], "%d/%m/%Y")
qs_events = qs_events.filter(models.Q(start_time__gte=date_actes_start))
qs = qs.filter(act_set__date__gte=date_actes_start.date())
except (ValueError, KeyError):
date_actes_start = None
pass
try:
date_actes_end = datetime.strptime(form.data['date_actes_end'], "%d/%m/%Y")
qs_events = qs_events.filter(models.Q(end_time__lte=date_actes_end))
qs = qs.filter(act_set__date__lte=date_actes_end.date())
except (ValueError, KeyError):
date_actes_end = None
if date_actes_start or date_actes_end:
qs = qs.filter(id__in=[x.event.eventact.patient.id for x in qs_events])
pass
qs = qs.filter(service=self.service).order_by('last_name')
return qs

View File

@ -10,7 +10,8 @@ from django.contrib.auth.models import User
from calebasse.actes.validation import automated_validation, \
are_all_acts_of_the_day_locked, \
get_days_with_acts_not_locked
from calebasse.actes.models import EventAct
from calebasse.actes.models import Act
from calebasse.agenda.models import EventWithAct
from calebasse.dossiers.models import create_patient, PatientRecord, \
SessadHealthCareNotification, CmppHealthCareTreatment, CmppHealthCareDiagnostic
from calebasse.dossiers.models import Status
@ -39,50 +40,50 @@ class FacturationTest(TestCase):
service_camsp = Service.objects.get(name='CAMSP')
patient_a = create_patient('a', 'A', service_camsp, self.creator, date_selected=datetime(2020, 10, 5))
act0 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act0 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 6, 10, 15),
end_datetime=datetime(2020, 10, 6, 12, 20))
status_suivi = Status.objects.filter(services__name='CAMSP').filter(type='SUIVI')[0]
patient_a.set_state(status_suivi, self.creator, date_selected=datetime(2020, 10, 7))
act1 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act1 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 10, 15),
end_datetime=datetime(2020, 10, 7, 12, 20))
act2 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act2 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 14, 15),
end_datetime=datetime(2020, 10, 7, 16, 20))
act3 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act3 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 16, 20),
end_datetime=datetime(2020, 10, 7, 17, 20))
status_clos = Status.objects.filter(services__name='CAMSP').filter(type='CLOS')[0]
patient_a.set_state(status_clos, self.creator, date_selected=datetime(2020, 10, 8))
act4 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act4 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 8, 10, 15),
end_datetime=datetime(2020, 10, 8, 12, 20))
patient_b = create_patient('b', 'B', service_camsp, self.creator, date_selected=datetime(2020, 10, 4))
act5 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act5 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 4, 10, 15),
end_datetime=datetime(2020, 10, 4, 12, 20))
act6 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act6 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 5, 10, 15),
end_datetime=datetime(2020, 10, 5, 12, 20))
act6.set_state('ABS_EXC', self.creator)
act7 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act7 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 5, 10, 15),
end_datetime=datetime(2020, 10, 5, 12, 20))
act7.switch_billable = True
act7.save()
patient_b.set_state(status_suivi, self.creator, date_selected=datetime(2020, 10, 6))
act8 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act8 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 10, 15),
end_datetime=datetime(2020, 10, 7, 12, 20))
act9 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act9 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 14, 15),
end_datetime=datetime(2020, 10, 7, 16, 20))
act10 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act10 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 7, 16, 20),
end_datetime=datetime(2020, 10, 7, 17, 20))
act11 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
act11 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_b, [self.therapist3],
self.act_type, service_camsp, start_datetime=datetime(2020, 10, 8, 10, 15),
end_datetime=datetime(2020, 10, 8, 12, 20))
patient_b.set_state(status_clos, self.creator, date_selected=datetime(2020, 10, 9))
@ -149,23 +150,23 @@ class FacturationTest(TestCase):
service_sessad = Service.objects.get(name='SESSAD DYS')
patient_a = create_patient('a', 'A', service_sessad, self.creator, date_selected=datetime(2020, 10, 5))
act0 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act0 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_sessad, start_datetime=datetime(2020, 10, 6, 10, 15),
end_datetime=datetime(2020, 10, 6, 12, 20))
status_traitement = Status.objects.filter(services__name='SESSAD DYS').filter(type='TRAITEMENT')[0]
patient_a.set_state(status_traitement, self.creator, date_selected=datetime(2020, 10, 7))
act1 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act1 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_sessad, start_datetime=datetime(2020, 10, 7, 10, 15),
end_datetime=datetime(2020, 10, 7, 12, 20))
act2 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act2 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_sessad, start_datetime=datetime(2020, 10, 7, 14, 15),
end_datetime=datetime(2020, 10, 7, 16, 20))
act3 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act3 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_sessad, start_datetime=datetime(2020, 10, 7, 16, 20),
end_datetime=datetime(2020, 10, 7, 17, 20))
status_clos = Status.objects.filter(services__name='SESSAD DYS').filter(type='CLOS')[0]
patient_a.set_state(status_clos, self.creator, date_selected=datetime(2020, 10, 8))
act4 = EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
act4 = EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_sessad, start_datetime=datetime(2020, 10, 8, 10, 15),
end_datetime=datetime(2020, 10, 8, 12, 20))
@ -196,7 +197,7 @@ class FacturationTest(TestCase):
service_cmpp = Service.objects.get(name='CMPP')
patient_a = create_patient('a', 'A', service_cmpp, self.creator, date_selected=datetime(2020, 10, 1))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2020, 10, i, 10, 15),
end_datetime=datetime(2020, 10, i, 12, 20)) for i in range (1, 32)]
status_accueil = Status.objects.filter(services__name='CMPP').filter(type='ACCUEIL')[0]
@ -236,7 +237,7 @@ class FacturationTest(TestCase):
patient_a = PatientRecord.objects.get(id=patient_a.id)
self.assertEqual(patient_a.get_state().status, status_traitement)
acts_2 = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
acts_2 = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient_a, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2020, 11, i, 10, 15),
end_datetime=datetime(2020, 11, i, 12, 20)) for i in range (1, 31)]
for i in range(1, 31):
@ -281,10 +282,10 @@ class FacturationTest(TestCase):
patients = []
for j in range(2):
patients.append(create_patient(str(j), str(j), service_cmpp, self.creator, date_selected=datetime(2012, 10, 1)))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patients[j], [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patients[j], [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (1, 32)]
acts_2 = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patients[j], [self.therapist3],
acts_2 = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patients[j], [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 11, i, 10, 15),
end_datetime=datetime(2012, 11, i, 12, 20)) for i in range (1, 31)]
hct = CmppHealthCareTreatment(patient=patients[j], start_date=datetime(2012, 10, 7), author=self.creator)
@ -376,7 +377,7 @@ class FacturationTest(TestCase):
patient = create_patient('A', 'a', service_cmpp, self.creator, date_selected=datetime(2012, 10, 1))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (1, 32)]
hct = CmppHealthCareTreatment(patient=patient, start_date=datetime(2011, 11, 7), author=self.creator)
@ -407,7 +408,7 @@ class FacturationTest(TestCase):
self.assertEqual(len_patient_with_lost_acts, 0)
acts_2 = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts_2 = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 11, i, 10, 15),
end_datetime=datetime(2012, 11, i, 12, 20)) for i in range (1, 31)]
@ -447,7 +448,7 @@ class FacturationTest(TestCase):
self.assertEqual(patient.last_state.status.type, "ACCUEIL")
EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, 1, 10, 15),
end_datetime=datetime(2012, 10, 1, 12, 20))
@ -457,7 +458,7 @@ class FacturationTest(TestCase):
self.assertEqual(patient.last_state.status.type, "DIAGNOSTIC")
self.assertEqual(patient.last_state.date_selected, datetime(2012, 10, 1, 0, 0))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (2, 32)]
@ -472,7 +473,7 @@ class FacturationTest(TestCase):
self.assertEqual(patient.last_state.status.type, "ACCUEIL")
EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, 1, 10, 15),
end_datetime=datetime(2012, 10, 1, 12, 20))
@ -489,7 +490,7 @@ class FacturationTest(TestCase):
self.assertEqual(patient.last_state.status.type, "CLOS")
self.assertEqual(patient.last_state.date_selected, datetime(2012, 12, 9, 0, 0))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (2, 32)]
@ -506,7 +507,7 @@ class FacturationTest(TestCase):
price_o = add_price(120, date(2012, 10, 1))
patient = create_patient('A', 'a', service_cmpp, self.creator, date_selected=datetime(2012, 10, 1))
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (1, 4)]
@ -545,7 +546,7 @@ class FacturationTest(TestCase):
hcd.set_act_number(5)
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 10, i, 10, 15),
end_datetime=datetime(2012, 10, i, 12, 20)) for i in range (4, 32)]
@ -601,7 +602,7 @@ class FacturationTest(TestCase):
hct.set_act_number(28)
acts = [ EventAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
acts = [ EventWithAct.objects.create_patient_appointment(self.creator, 'RDV', patient, [self.therapist3],
self.act_type, service_cmpp, start_datetime=datetime(2012, 11, i, 10, 15),
end_datetime=datetime(2012, 11, i, 12, 20)) for i in range (1, 4)]

View File

@ -2,11 +2,15 @@
{
"fields": {
"act_type": 97,
"date": "2012-10-30T12:00:00",
"date": "2012-10-30",
"patient": 8,
"transport_company": null,
"transport_type": null,
"validation_locked": false
"validation_locked": false,
"doctors": [
5
],
"parent_event": 1
},
"model": "actes.act",
"pk": 1
@ -14,45 +18,19 @@
{
"fields": {
"act_type": 10,
"date": "2012-10-30T00:00:00",
"date": "2012-10-30",
"patient": 9,
"transport_company": null,
"transport_type": null,
"validation_locked": false
"validation_locked": false,
"doctors": [
5
],
"parent_event": 2
},
"model": "actes.act",
"pk": 2
},
{
"fields": {
"attendance": "absent",
"convocation_sent": false,
"event_ptr": 1,
"participants": [
5
],
"services": [
1
]
},
"model": "actes.eventact",
"pk": 1
},
{
"fields": {
"attendance": "absent",
"convocation_sent": false,
"event_ptr": 2,
"participants": [
5
],
"services": [
1
]
},
"model": "actes.eventact",
"pk": 2
},
{
"fields": {
"act": 1,

View File

@ -105,7 +105,10 @@
1,
2
],
"room": 2
"room": 2,
"create_date": "2012-10-20T11:30:00",
"start_datetime": "2012-10-30T11:30:00",
"end_datetime": "2012-10-30T12:00:00"
}
},
{
@ -121,7 +124,10 @@
"services": [
1
],
"room": 1
"room": 1,
"create_date": "2012-10-20T11:30:00",
"start_datetime": "2012-10-30T10:45:00",
"end_datetime": "2012-10-30T11:30:00"
}
},
{
@ -137,37 +143,28 @@
"services": [
1
],
"room": 2
"room": 2,
"create_date": "2012-10-20T11:30:00",
"start_datetime": "2012-10-30T10:00:00",
"end_datetime": "2012-10-30T10:45:00"
}
},
{
"pk": 1,
"model": "agenda.occurrence",
"fields": {
"notes": [],
"start_time": "2012-10-30T10:00:00",
"end_time": "2012-10-30T10:45:00",
"event": 1
}
"fields": {
"act_type": 97,
"patient": 10,
"event_ptr": 1
},
"model": "agenda.eventwithact",
"pk": 1
},
{
"pk": 2,
"model": "agenda.occurrence",
"fields": {
"notes": [],
"start_time": "2012-10-30T10:45:00",
"end_time": "2012-10-30T11:30:00",
"event": 2
}
},
{
"pk": 3,
"model": "agenda.occurrence",
"fields": {
"notes": [],
"start_time": "2012-10-30T11:30:00",
"end_time": "2012-10-30T12:00:00",
"event": 3
}
"fields": {
"act_type": 10,
"patient": 9,
"event_ptr": 2
},
"model": "agenda.eventwithact",
"pk": 2
}
]

View File

@ -26,7 +26,7 @@ function enable_events(base) {
if (r == true)
{
$.ajax({
url: '/api/occurrence/' + $(this).data('occurrence-id') + '/',
url: '/api/event/' + $(this).data('event-id') + '/',
type: 'DELETE',
success: function(data) {
window.location.reload(true);
@ -45,7 +45,7 @@ function enable_events(base) {
event_dialog(new_appointment_url, 'Nouveau rendez-vous', '850px', 'Ajouter');
});
$(base).find('.edit-appointment').click(function() {
event_dialog("update-rdv/" + $(this).data('occurrence-id') , 'Modifier rendez-vous', '850px', 'Modifier');
event_dialog("update-rdv/" + $(this).data('event-id') , 'Modifier rendez-vous', '850px', 'Modifier');
return false;
});
$(base).find('.newevent').click(function() {
@ -56,13 +56,13 @@ function enable_events(base) {
event_dialog($(this).data('url') + "?" + qs, 'Nouvel événement', '850px', 'Ajouter');
});
$(base).find('.edit-event').click(function() {
event_dialog("update-event/" + $(this).data('occurrence-id') , 'Modifier un événement', '850px', 'Modifier');
event_dialog("update-event/" + $(this).data('event-id') , 'Modifier un événement', '850px', 'Modifier');
return false;
});
$(base).find('#print-button').click(function() { window.print(); });
$('.generate-mail-btn', base).click(function() {
var url = '../../dossiers/' + $(this).data('dossier-id') + '/generate?event-id=' + $(this).data('occurence-id');
var url = '../../dossiers/' + $(this).data('dossier-id') + '/generate?event-id=' + $(this).data('occurence-id' + '&date=' + $(this).data('date'));
$('#ajax-dlg').load(url,
function () {
$(this).dialog({title: 'Générer un courrier', width: '500px',

View File

@ -5,7 +5,7 @@ from django.contrib.auth.decorators import login_required
from urls_utils import decorated_includes
from calebasse.api import (event_resource, occurrence_resource,
from calebasse.api import (event_resource,
patientrecord_resource, patientaddress_ressource)
admin.autodiscover()
@ -34,9 +34,6 @@ urlpatterns = patterns('',
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^api/',
decorated_includes(login_required, include(event_resource.urls))),
url(r'^api/',
decorated_includes(login_required, include(occurrence_resource.urls)),
),
url(r'^api/',
decorated_includes(login_required, include(patientrecord_resource.urls)),
),