Skip to content

Commit

Permalink
Merge pull request #3 from bioinformatics-ua/dev
Browse files Browse the repository at this point in the history
0.1.1
  • Loading branch information
joaorafaelalmeida authored Oct 16, 2018
2 parents 4576a3d + 0781b6e commit bbf5675
Show file tree
Hide file tree
Showing 37 changed files with 419 additions and 113 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ env/*
*.pyc

#Put this files in somewhere private
docker-compose.yml
!docker-compose.yml

#Ignore migrations
Backend/accounts/migrations/*
Expand All @@ -23,4 +23,4 @@ Backend/utils/migrations/*
!Backend/protocol_element/migrations/__init__.py
!Backend/utils/migrations/__init__.py

UI/package-lock.json
UI/package-lock.json
15 changes: 10 additions & 5 deletions Backend/genericcdss/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,12 @@
'FOOTER_EXTRA': """<a href='http://www.ua.pt/'>
<img style='margin-left:20px' src='https://emif-catalogue.eu/taska/static/images/logo-ua2.png'>
</a>""",
'APP_SYMBOL':"""
<img style='margin-left:20px' src='static/NOTFOUND'>
'APP_SYMBOL_SMALL':"""<img style='margin-left:20px; max-width: 70px;' src='images/logo_small.png'>
""",
'LANGUAGE':"pt - to do"
'APP_SYMBOL':"""<center><img style='max-width: 150px; max-height: 150px;' src='images/logo.png'></center>
""",
'LANGUAGE':"pt - to do",
'SHOW_DEFAULT_HOME': True
}

CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
Expand All @@ -214,13 +216,16 @@
'copyright': (GLOBALS['COPYRIGHT'], 'Text to show as copyright'),
'copyrightsplash': ('<a target="_blank" href="http://bioinformatics.ua.pt/">Bioinformatics, UA.</a>', 'Text to show as copyright on splash screen'),
'footer_extra': (GLOBALS['FOOTER_EXTRA'], 'Extra HTML to be shown besides the footer'),
'app_symbol_small': (GLOBALS['APP_SYMBOL_SMALL'], 'Image used to represent the system (Logo) - small'),
'app_symbol': (GLOBALS['APP_SYMBOL'], 'Image used to represent the system (Logo)'),
'site_name': (GLOBALS['SITE_NAME'], 'Website title'),
'language':(GLOBALS['LANGUAGE'], 'The languge used in the GUI')
'language':(GLOBALS['LANGUAGE'], 'The languge used in the GUI'),
'show_default_home':(GLOBALS['SHOW_DEFAULT_HOME'], 'If true, it show the default home. If false, it show the home flat page')
}

CONSTANCE_CONFIG_FIELDSETS = {
'General Options': ('site_name', 'footer_extra', 'app_symbol', 'copyrightsplash', 'copyright','language'),
'General Options': ('site_name', 'footer_extra', 'copyrightsplash', 'copyright', 'language'),
'Home Options': ('show_default_home', 'app_symbol_small', 'app_symbol')
}

JET_DEFAULT_THEME = 'light-blue'
16 changes: 11 additions & 5 deletions Backend/patients/api/serializers/AdmissionSerializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,24 @@
from patients.api.serializers import PatientSerializer

class AdmissionSerializer(serializers.ModelSerializer):
physician = serializers.SerializerMethodField(required=False)
next_measure = serializers.SerializerMethodField(required=False)
last_measure = serializers.SerializerMethodField(required=False)
admission_physician = serializers.SerializerMethodField(required=False)
last_measure_physician = serializers.SerializerMethodField(required=False)
next_measure = serializers.SerializerMethodField(required=False)
last_measure = serializers.SerializerMethodField(required=False)
#protocol_id = serializers.SerializerMethodField(required=False)
patient = PatientSerializer()
patient = PatientSerializer()

class Meta:
permission_classes = [permissions.IsAuthenticated]
model = Admission
fields = '__all__'

def get_physician(self, obj):
def get_admission_physician(self, obj):
return obj.physician.getFullName()

def get_last_measure_physician(self, obj):
if(obj.getLastProtocolAssignedMeasurePhysician() != ""):
return obj.getLastProtocolAssignedMeasurePhysician().getFullName()
return obj.physician.getFullName()

def get_next_measure(self, obj):
Expand Down
2 changes: 1 addition & 1 deletion Backend/patients/api/views/AdmissionViewSet.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def new(self, request, *args, **kwargs):
selectedProtocols = request.data.get('seletedProtocols') #For now it is only one
for selectedProtocol in selectedProtocols:
protocol = Protocol.objects.get(id=selectedProtocol.get("id"))
ExecutedProtocol.new(protocol=protocol, patient=patient)
ExecutedProtocol.new(protocol=protocol, patient=patient, physician=physician)

self.queryset = Admission.all(active=True)
return super(AdmissionViewSet, self).list(request, *args, **kwargs)
Expand Down
41 changes: 40 additions & 1 deletion Backend/patients/management/commands/populate_db_patients.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# coding=utf-8
from django.core.management.base import BaseCommand
from patients.models import CVGroup, ClinicalVariable, Patient, CVPatient, Admission
from accounts.models import Profile
from django.contrib.auth.models import User
from protocol.models import Protocol, ExecutedProtocol
import random
import time

Expand Down Expand Up @@ -42,6 +45,8 @@ def handle(self, *args, **options):
self.manageBodyMeasurements(options['force'])
self.managePerfomedExams(options['force'])

self.assignPatients()

def deleteAll(self):
self.stdout.write("\tDeleting data in the CVPatients\n")
CVPatient.objects.all().delete()
Expand Down Expand Up @@ -263,4 +268,38 @@ def managePerfomedExams(self, force):
group = cvg,
variable = "Physician",
value = random.choice(drs),
measure_date=measure_date)
measure_date=measure_date)

def assignPatients(self):
try:
physician_user = User.objects.create_user('João Almeida', '[email protected]', '12345')
physician = Profile(user=physician_user, role=Profile.PHYSICIAN)
physician.save()
max = len(Patient.objects.all())/4
count = 0
for patient in Patient.objects.all():
# Create admission
Admission.new(patient=patient,
physician=physician,
room="c." + str(patient.id))

# Assign protocols
protocol = Protocol.objects.get(title="Hypoglycemia")
ExecutedProtocol.new(protocol=protocol, patient=patient, physician=physician)

if count%2 == 0: #Execute one mesurement in some patients
inquiryData = {"Blood Glucose": "12", "Diet": "zero"}
CVPatient.addCVSet(inquiryData, patient)
assignment = ExecutedProtocol.getNextExecution(patient)
result = assignment.run(inquiryData)
# Next assigment
protocol = assignment.protocol
last_execution = assignment.schedule_time
ExecutedProtocol.new(protocol=protocol, patient=patient, physician=physician, last_execution=last_execution)

count += 1
if count == max:
break
except Exception as ex:
self.stdout.write("\tError: Probably no protocol or doctors in the database!\n")
self.stdout.write(ex)
10 changes: 10 additions & 0 deletions Backend/patients/models/Admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def getLastProtocolAssignedMeasure(self):
return lastProtocolExecution.execution_time.strftime("%Y-%m-%d %H:%M")
return ""

def getLastProtocolAssignedMeasurePhysician(self):
'''
Retrieves who made the last protocol measurement
:return: datetime in string format
'''
lastProtocolExecution = ExecutedProtocol.getLastExecution(patient=self.patient, admissionDate=self.start_date)
if(lastProtocolExecution):
return lastProtocolExecution.physician
return ""

def getNextProtocolAssignedMeasure(self):
'''
It returns when the patient information should be measured
Expand Down
2 changes: 1 addition & 1 deletion Backend/protocol/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ProtocolAdmin(admin.ModelAdmin):

@admin.register(ExecutedProtocol)
class ExecutedProtocolAdmin(admin.ModelAdmin):
list_display = ("protocol", "patient", "execution_time")
list_display = ("protocol", "patient", "execution_time", "physician")

@admin.register(Schedule)
class ScheduleAdmin(admin.ModelAdmin):
Expand Down
18 changes: 15 additions & 3 deletions Backend/protocol/api/serializers/ExecutedProtocolSerializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@

from protocol.models import ExecutedProtocol

from patients.models import Admission


class ExecutedProtocolSerializer(serializers.ModelSerializer):
title = serializers.SerializerMethodField(required=False)
description = serializers.SerializerMethodField(required=False)
execution_time = serializers.SerializerMethodField(required=False)
title = serializers.SerializerMethodField(required=False)
description = serializers.SerializerMethodField(required=False)
execution_time = serializers.SerializerMethodField(required=False)
admission_physician = serializers.SerializerMethodField(required=False)
last_measure_physician = serializers.SerializerMethodField(required=False)

class Meta:
permission_classes = [permissions.IsAuthenticated]
Expand All @@ -26,4 +30,12 @@ def get_description(self, obj):
def get_execution_time(self, obj):
if(obj.execution_time):
return obj.execution_time.strftime("%Y-%m-%d %H:%M")
return ""

def get_admission_physician(self, obj):
return Admission.getLatestAdmission(obj.patient).physician.getFullName()

def get_last_measure_physician(self, obj):
if(obj.physician):
return obj.physician.getFullName()
return ""
8 changes: 6 additions & 2 deletions Backend/protocol/api/views/ProtocolViewSet.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from protocol_element.api.serializers import ProtocolElementSerializer, PEInquirySerializer
from protocol_element.models import ProtocolElement, PEInquiry

from accounts.models import Profile

from history.models import History

class ProtocolViewSet(viewsets.ModelViewSet):
Expand Down Expand Up @@ -104,15 +106,17 @@ def run(self, request):
'error': "Invalid parameters"
})

physician = Profile.objects.get(user=request.user)
patient = Patient.objects.get(id=patientId)
CVPatient.addCVSet(inquiryData, patient)

assignment = ExecutedProtocol.getNextExecution(patient)
result = assignment.run(inquiryData)
result = assignment.run(inquiryData=inquiryData, physician=physician)

#Next assigment
protocol = assignment.protocol
ExecutedProtocol.new(protocol=protocol, patient=patient)
last_execution = assignment.schedule_time
ExecutedProtocol.new(protocol=protocol, patient=patient, physician=physician, last_execution=last_execution)

return Response({"results": result})

Expand Down
11 changes: 8 additions & 3 deletions Backend/protocol/models/ExecutedProtocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

from protocol_element.models import ProtocolElement, PEDecision, PEAction

from accounts.models import Profile

class ExecutedProtocol(models.Model):
ASSIGNED = 1
EXECUTED = 2
Expand All @@ -25,17 +27,19 @@ class ExecutedProtocol(models.Model):
protocol = models.ForeignKey(Protocol)
patient = models.ForeignKey(Patient)
schedule = models.ForeignKey(Schedule)
physician = models.ForeignKey(Profile)
schedule_time = models.DateTimeField()
execution_time = models.DateTimeField(null=True)
elementsExecuted = models.ManyToManyField(ProtocolElement)
state = models.PositiveSmallIntegerField(choices=STATUS, default=ASSIGNED)

def run(self, inquiryData):
def run(self, inquiryData, physician):
elementsExecutedInProtocol, actionsResult = self.protocol.run(inquiryData)
for element in elementsExecutedInProtocol:
self.elementsExecuted.add(element)
self.state = ExecutedProtocol.EXECUTED
self.execution_time = datetime.now()
self.physician = physician
self.save()
return self.getResult()

Expand All @@ -50,12 +54,13 @@ def getResult(self):
return actionsResult

@staticmethod
def new(protocol, patient):
schedule_time, scheduleTitle = protocol.getNextScheduleTime()
def new(protocol, patient, physician, last_execution=None):
schedule_time, scheduleTitle = protocol.getNextScheduleTime(last_execution)
scheduleObj = Schedule.objects.get(title=scheduleTitle)
protocol = ExecutedProtocol.objects.create(protocol=protocol,
patient=patient,
schedule=scheduleObj,
physician=physician,
schedule_time=schedule_time,
state=ExecutedProtocol.ASSIGNED)
protocol.save()
Expand Down
42 changes: 31 additions & 11 deletions Backend/protocol/models/Protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from django.db import models
from django.utils import timezone
from datetime import datetime
from datetime import datetime, timedelta

from protocol.models import Schedule

Expand Down Expand Up @@ -63,13 +63,22 @@ def edit(id, title, description, schedules):#, type, public):
@staticmethod
def all():
'''
Returns all executed protocol instances
Returns all protocol instances
'''
tmpAll = Protocol.objects.all().filter(removed=False)

return tmpAll.order_by('title')

def getNextScheduleTime(self):
@staticmethod
def get(title):
'''
Returns a active protocol instance
'''
tmpAll = Protocol.all()

return tmpAll.get(title=title)

def getNextScheduleTime(self, last_execution=None):
'''
Returns next schedule time
:return: tuple (datetime, schedule title)
Expand All @@ -81,22 +90,33 @@ def getNextScheduleTime(self):
nextScheduleTime = None
nextScheduleTitle = None
allPossibleTimes = sorted(allPossibleTimes)

for timeObj, scheduleTitle in allPossibleTimes:
if(datetime.now().time() < timeObj.time): #the time is after now
if(nextScheduleTime):
if (timeObj.time < nextScheduleTime.time):
compareTimes = False
if(last_execution):
if (last_execution.date() == datetime.now().date()):
if(timeObj.time.hour != last_execution.hour or timeObj.time.minute != last_execution.minute):
if(datetime.now().time() < timeObj.time and last_execution.time() < timeObj.time): #the time is after now
compareTimes = True
else:
compareTimes = True
else:
compareTimes = True

if(compareTimes):
if (datetime.now().time() < timeObj.time): # the time is after now
if (nextScheduleTime):
if (timeObj.time < nextScheduleTime.time):
nextScheduleTime = timeObj
nextScheduleTitle = scheduleTitle
else:
nextScheduleTime = timeObj
nextScheduleTitle = scheduleTitle
else:
nextScheduleTime = timeObj
nextScheduleTitle = scheduleTitle

if(nextScheduleTime == None):
nextScheduleTime, nextScheduleTitle = allPossibleTimes[0]

if(nextScheduleTime.time < datetime.now().time()): #Tomorrow
nextSchedule = datetime.now() + datetime.timedelta(days=1)
nextSchedule = datetime.now() + timedelta(days=1)
return (nextSchedule.replace(hour=nextScheduleTime.time.hour, minute=nextScheduleTime.time.minute), nextScheduleTitle)
else: #Today
nextSchedule = datetime.now()
Expand Down
14 changes: 14 additions & 0 deletions Backend/utils/api/views/ConstanceView.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,32 @@ def __getAppSymbol(self):
except:
return "Error"

def __getAppSymbolSmall(self):
try:
return config.app_symbol_small
except:
return "Error"

def __getTitle(self):
try:
return config.site_name
except:
return "Error"

def __getShowDefaultHome(self):
try:
return config.show_default_home
except:
return "Error"

@detail_route(methods=['get'])
def getSettings(self, request, *args, **kwargs):
response = {}

response["title"] = self.__getTitle()
response["footer"] = self.__getFooter()
response["appSymbol"] = self.__getAppSymbol()
response["appSymbolSmall"] = self.__getAppSymbolSmall()
response["showDefaultHome"] = self.__getShowDefaultHome()

return Response(response)
Loading

0 comments on commit bbf5675

Please sign in to comment.