def get(self, request, *args, **kwargs): """ Retrieves prescription entry records from database for display :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving prescription id from request URI') prescription = self.model.objects.get(pk=kwargs.get('id')) prescription_entries = PrescriptionEntry.objects.filter( prescription=prescription, is_deleted=False).order_by('medicine__order') log_end_time() return render( request, self.template_name, { 'prescription': prescription, 'prescription_entries': prescription_entries, 'max_column_width': -12, 'max_cell_width': -6, 'edit_link': reverse_lazy(PRESCRIPTION_EDIT_PAGE_NAME, kwargs={'id': prescription.id}) })
def initialise_form(view, request): """ Function for instantiating GeneralSearchForm :param view: View instance :param request: HttpRequest instance :return: GeneralSearchForm instance """ log_start_time() if request.POST: logger.info('Received a POST request') data = request.POST elif request.GET: logger.info('Received a GET request') data = request.GET else: logger.info('Did not receive a GET or a POST request') return None log_end_time() return GeneralSearchForm(data=data, placeholder='Search ' + view.page_title, form_action=view.search_link, act_search_type_label_var_name='act_search_type_label', search_key_values_var_name='search_type_labels')
def initialise_form(view, request): """ Function for instantiating GeneralSearchForm :param view: View instance :param request: HttpRequest instance :return: GeneralSearchForm instance """ log_start_time() if request.POST: logger.info('Received a POST request') data = request.POST elif request.GET: logger.info('Received a GET request') data = request.GET else: logger.info('Did not receive a GET or a POST request') return None log_end_time() return GeneralSearchForm( data=data, placeholder='Search ' + view.page_title, form_action=view.search_link, act_search_type_label_var_name='act_search_type_label', search_key_values_var_name='search_type_labels')
def __init__(self, diagnosis_category, *args, **kwargs): """ Initialises form helper depending on the level of DiagnosisCategory model instance. :param diagnosis_category: DiagnosisCategory model instance :param args: variable arguments :param kwargs: named arguments """ super(DiagnosisCategoryFormHelper, self).__init__(*args, **kwargs) log_start_time() logger.info('Creating form helper for [%s] with level [%s]' % (diagnosis_category, diagnosis_category.level)) self.form_class = 'form-horizontal' self.label_class = 'inline_form_label col-xs-offset-%s col-xs-%s' % ( diagnosis_category.level, self.MAX_BOOTSTRAP_COLUMN_WIDTH - int(diagnosis_category.level)) self.field_class = 'col-xs-6' self.form_tag = False self.layout = Layout( 'diagnosis_category', 'value', 'remark', ) self.render_required_fields = True log_end_time()
def create_link(page_name, arg_value_pair): """ Function for creating a link using a page name. Query string will be appended if provided :param page_name: valid and registered page name :param arg_value_pair: key-value pair inside a dictionary :return: created link in string """ log_start_time() link = '' try: logger.info('Creating link for [%s]' % page_name) if page_name: link = reverse_lazy(page_name) logger.info('Created link is [%s]' % link) else: logger.info('Received empty value for page_name') if arg_value_pair and isinstance(arg_value_pair, dict): logger.info('Creating query string using arg_value_pair') link += '?%s' % urllib.parse.urlencode(arg_value_pair) else: logger.info('No value for arg_value_pair found') except NoReverseMatch: logger.warn('Cannot create link for [%s]' % page_name) link = '' logger.info('Full link created [%s]' % link) log_end_time() return link
def process_search(self, request): """ Receives either POST or GET request then proceeds to search records depending on search query :param request: HttpRequest instance :return: HttpResponse instance """ log_start_time() form = initialise_form(self, request) if form is not None and form.is_valid(): logger.info('Received a valid form') self.search_type = form.cleaned_data['search_type'] self.search_param = form.cleaned_data['search_param'] logger.info('Creating search link using page name [%s]' % self.list_page_name) self.search_link = create_link(self.list_page_name, {'search_param': self.search_param, 'search_type': self.search_type}) if self.search_param: logger.info('Received a non-empty search parameter') results = search_matches(self, self.search_type, self.search_param) else: logger.info('Did not receive a valid search parameter') results = self.model.objects.all().order_by('-id') paginator = Paginator(results, MAX_LIST_ITEMS_PER_PAGE) logger.info('Calling common functions for listing records') select_search_results(self, request, paginator) modify_page_links(self, paginator) validate_response(self) response = render(request, self.template_name, {'form': form, 'search_link': self.search_link, 'searches': self.searches, 'search_type_labels': self.search_labels, 'act_search_type_label': self.search_labels.get(self.search_type), 'pages': self.pages, 'page_title': self.page_title, 'page_icon': self.page_icon, 'current_page': self.current_page, 'error_message': self.error_message, 'next_link': self.next_link, 'next_link_class': self.next_link_class, 'previous_link': self.previous_link, 'previous_link_class': self.previous_link_class, }) else: response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def modify_page_links(view, paginator): """ Function for setting links and classes for paginator buttons in list view. :param view: View instance :param paginator: Paginator instance :return: None """ log_start_time() search_link = view.search_link + PAGE_PARAMETER_SUFFIX if int(view.current_page) < int(paginator.num_pages): logger.info( 'Paginator number of pages is greater than current page value') view.next_link = search_link + str(view.current_page + 1) view.next_link_class = '' else: logger.info( 'Paginator number of pages is less than current page value') view.next_link = None view.next_link_class = DISABLED_LINK_CLASS if int(paginator.num_pages) < MAX_PAGINATE_NUMBER: logger.info('Limiting links to number of paginator pages') end_page = paginator.num_pages start_page = 1 elif int(view.current_page) > MAX_PAGINATE_NUMBER: logger.info('Changing lower limit for paginator links') end_page = view.current_page start_page = view.current_page - MAX_PAGINATE_NUMBER + 1 else: logger.info( 'Number of paginator pages is greater than default number of search pages' ) end_page = MAX_PAGINATE_NUMBER start_page = 1 if view.current_page <= 1: logger.info('Current page is the lower limit for paginator links') view.previous_link = None view.previous_link_class = DISABLED_LINK_CLASS else: logger.info( 'Changing previous link button class to show previous batch of results' ) view.previous_link = search_link + str(view.current_page - 1) view.previous_link_class = '' view.pages = list(range(start_page, end_page + 1)) log_end_time()
def get(self, request, *args, **kwargs): """ Creates a formset for creating medication entry records for a specified patient. Value for [patient] is taken from request URI. If a medication ID is provided in URI, retrieves medication entries from database for update :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving patient ID from request URI') patient_id = request.GET.get('patient') logger.info('Retrieving medication record ID from request URI') medication_id = kwargs.get('id') if patient_id: logger.info('Retrieved patient ID value [%s]' % patient_id) patient = Patient.objects.get(pk=int(patient_id)) logger.info('Creating formset with 1 extra form') MedicationFormSet = formset_factory(self.form_class) formset = MedicationFormSet() response = render(request, self.template_name, {'formset': formset, 'patient': patient, 'submit_label': 'Record'}) elif medication_id: logger.info('Retrieved medication record ID value [%s]' % medication_id) medication = Medication.objects.get(pk=medication_id) logger.info('Retrieving medication entries using medication record ID [%s]' % medication.id) medication_entries = MedicationEntry.objects.filter(medication=medication) initial = [] logger.info('Pre-filling formset using medication entry records retrieved from database') for entry in medication_entries: initial.append({'description': entry.description, 'dosage': entry.dosage, 'package': entry.package, 'frequency': entry.frequency, 'designated_time': entry.designated_time}) logger.info('Creating formset with no additional forms') MedicationFormSet = formset_factory(self.form_class, extra=0) formset = MedicationFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'patient': medication.patient, 'submit_label': 'Record'}) else: logger.warn('Did not receive value for required medical parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def get(self, request, *args, **kwargs): """ Packages page icons and page labels for links available in the dashboard page :param request: HttpRequest instance :param args: variable arguments :param kwargs: named arguments :return: HttpResponse instance """ log_start_time() icons_labels_zip = zip(PAGE_ICONS, PAGE_LABELS) # will default to searching Patient if request.GET.get('search_category'): search_category = request.GET.get('search_category') else: search_category = DEFAULT_SEARCH_CATEGORY if search_category == DEFAULT_SEARCH_CATEGORY: search_type_labels = PATIENT_SEARCH_TYPE_LABEL else: search_type_labels = GENERAL_SEARCH_TYPE_LABEL log_end_time() return render( request, self.template_name, { 'form': GeneralSearchForm( placeholder='Search ' + PAGE_LABELS[int(search_category) - LIST_OFFSET], form_action=SEARCH_VIEW_LINKS.get(search_category), act_search_type_label_var_name='act_search_type_label', search_key_values_var_name='search_type_labels'), 'act_search_type_label': search_type_labels.get(DEFAULT_SEARCH_TYPE), 'icons_labels_zip': icons_labels_zip, 'view_link': self.view_link, 'search_category': int(search_category), 'search_type_labels': search_type_labels, 'add_link': reverse_lazy(PATIENT_FORM_PAGE_NAME), 'search_category_param': '?search_category=' })
def validate_response(view): """ Function that performs all validation on view instance and sets error messages accordingly :param view: View instance :return: None """ log_start_time() if view.search_count < 1: logger.info('Search returned an emtpy list') view.error_message = EMPTY_SEARCH_RESULT else: logger.info('Records found for received search category and search parameter') log_end_time()
def validate_response(view): """ Function that performs all validation on view instance and sets error messages accordingly :param view: View instance :return: None """ log_start_time() if view.search_count < 1: logger.info('Search returned an emtpy list') view.error_message = EMPTY_SEARCH_RESULT else: logger.info( 'Records found for received search category and search parameter') log_end_time()
def modify_page_links(view, paginator): """ Function for setting links and classes for paginator buttons in list view. :param view: View instance :param paginator: Paginator instance :return: None """ log_start_time() search_link = view.search_link + PAGE_PARAMETER_SUFFIX if int(view.current_page) < int(paginator.num_pages): logger.info('Paginator number of pages is greater than current page value') view.next_link = search_link + str(view.current_page + 1) view.next_link_class = '' else: logger.info('Paginator number of pages is less than current page value') view.next_link = None view.next_link_class = DISABLED_LINK_CLASS if int(paginator.num_pages) < MAX_PAGINATE_NUMBER: logger.info('Limiting links to number of paginator pages') end_page = paginator.num_pages start_page = 1 elif int(view.current_page) > MAX_PAGINATE_NUMBER: logger.info('Changing lower limit for paginator links') end_page = view.current_page start_page = view.current_page - MAX_PAGINATE_NUMBER + 1 else: logger.info('Number of paginator pages is greater than default number of search pages') end_page = MAX_PAGINATE_NUMBER start_page = 1 if view.current_page <= 1: logger.info('Current page is the lower limit for paginator links') view.previous_link = None view.previous_link_class = DISABLED_LINK_CLASS else: logger.info('Changing previous link button class to show previous batch of results') view.previous_link = search_link + str(view.current_page - 1) view.previous_link_class = '' view.pages = list(range(start_page, end_page + 1)) log_end_time()
def extract_form_data(initial_formset): """ Returns an array of initial data from formset argument :param initial_formset: Dict of formset :return: Array of initial formset data """ log_start_time() initial = [] for form in initial_formset: data = {} for field in form.fields: data[field] = form[field].value() initial.append(data) log_end_time() return initial
def __init__(self, *args, **kwargs): super(MedicationFormHelper, self).__init__(*args, **kwargs) log_start_time() self.form_class = 'form-horizontal' self.form_tag = False self.layout = Layout( Div(Div('description', css_class='col-xs-3'), Div('dosage', css_class='col-xs-offset-0-2-5 col-xs-1'), Div('package', css_class='col-xs-offset-0-2-5 col-xs-1'), Div('frequency', css_class='col-xs-offset-0-2-5 col-xs-2'), Div('designated_time', css_class='col-xs-offset-0-2-5 col-xs-2'), Div('DELETE', css_class='col-xs-offset-0-2-5 col-xs-1'), css_class='form-group row'), ) self.render_required_fields = True log_end_time()
def __init__(self, *args, **kwargs): super(MedicationFormHelper, self).__init__(*args, **kwargs) log_start_time() self.form_class = 'form-horizontal' self.form_tag = False self.layout = Layout( Div( Div('description', css_class='col-xs-3'), Div('dosage', css_class='col-xs-offset-0-2-5 col-xs-1'), Div('package', css_class='col-xs-offset-0-2-5 col-xs-1'), Div('frequency', css_class='col-xs-offset-0-2-5 col-xs-2'), Div('designated_time', css_class='col-xs-offset-0-2-5 col-xs-2'), Div('DELETE', css_class='col-xs-offset-0-2-5 col-xs-1'), css_class='form-group row' ), ) self.render_required_fields = True log_end_time()
def select_search_results(view, request, paginator): """ Function for retrieving value of [page] parameter in URI. :param view: View instance :param request: HttpRequest instance :param paginator: Paginator instance :return: None """ log_start_time() if request.POST: logger.info('Defaulting to first page because of POST request') view.current_page = 1 view.searches = paginator.page(1) elif request.GET.get('page'): logger.info('Retrieved value for page parameter') page = request.GET.get('page') try: logger.info('Retrieving results based on retrieved page value') view.searches = paginator.page(page) view.current_page = int(page) except PageNotAnInteger: logger.warn( 'Provided value for page parameter cannot be converted to int') view.error_message = INVALID_SEARCH_PARAMETER_VALUE view.searches = paginator.page(1) except EmptyPage: logger.warn( 'Provided value for page parameter is out of bounds for paginator' ) view.error_message = INVALID_SEARCH_PARAMETER_VALUE view.searches = paginator.page(paginator.num_pages) else: logger.info('Did not receive page parameter') view.current_page = 1 view.searches = paginator.page(1) log_end_time()
def __init__(self, *args, **kwargs): super(PrescriptionEntryFormHelper, self).__init__(*args, **kwargs) log_start_time() self.form_class = 'form-horizontal' self.form_tag = False self.layout = Layout( Div(Div(Div(Div('prescribe', css_class='col-xs-1'), Div('medicine_label', css_class='col-xs-10'), css_class='row'), css_class='container col-xs-3'), Div('dosage', css_class='col-xs-1'), Div('package', css_class='col-xs-offset-1 col-xs-1'), Div('frequency', css_class='col-xs-offset-1 col-xs-2'), Div('designated_time', css_class='col-xs-offset-1 col-xs-2'), css_class='form-group row'), 'medicine', ) self.render_required_fields = True log_end_time()
def get(self, request, *args, **kwargs): """ Retrieves prescription entry records from database for display :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving medication id from request URI') medication = self.model.objects.get(pk=kwargs.get('id')) medication_entries = MedicationEntry.objects.filter(medication=medication) log_end_time() return render(request, self.template_name, {'medication': medication, 'medication_entries': medication_entries, 'max_column_width': -12, 'max_cell_width': -6, 'edit_link': reverse_lazy(MEDICATION_EDIT_PAGE_NAME, kwargs={'id': medication.id})})
def get(self, request, *args, **kwargs): """ Packages page icons and page labels for links available in the dashboard page :param request: HttpRequest instance :param args: variable arguments :param kwargs: named arguments :return: HttpResponse instance """ log_start_time() icons_labels_zip = zip(PAGE_ICONS, PAGE_LABELS) # will default to searching Patient if request.GET.get('search_category'): search_category = request.GET.get('search_category') else: search_category = DEFAULT_SEARCH_CATEGORY if search_category == DEFAULT_SEARCH_CATEGORY: search_type_labels = PATIENT_SEARCH_TYPE_LABEL else: search_type_labels = GENERAL_SEARCH_TYPE_LABEL log_end_time() return render(request, self.template_name, {'form': GeneralSearchForm( placeholder='Search ' + PAGE_LABELS[int(search_category) - LIST_OFFSET], form_action=SEARCH_VIEW_LINKS.get(search_category), act_search_type_label_var_name='act_search_type_label', search_key_values_var_name='search_type_labels'), 'act_search_type_label': search_type_labels.get(DEFAULT_SEARCH_TYPE), 'icons_labels_zip': icons_labels_zip, 'view_link': self.view_link, 'search_category': int(search_category), 'search_type_labels': search_type_labels, 'add_link': reverse_lazy(PATIENT_FORM_PAGE_NAME), 'search_category_param': '?search_category='})
def select_search_results(view, request, paginator): """ Function for retrieving value of [page] parameter in URI. :param view: View instance :param request: HttpRequest instance :param paginator: Paginator instance :return: None """ log_start_time() if request.POST: logger.info('Defaulting to first page because of POST request') view.current_page = 1 view.searches = paginator.page(1) elif request.GET.get('page'): logger.info('Retrieved value for page parameter') page = request.GET.get('page') try: logger.info('Retrieving results based on retrieved page value') view.searches = paginator.page(page) view.current_page = int(page) except PageNotAnInteger: logger.warn('Provided value for page parameter cannot be converted to int') view.error_message = INVALID_SEARCH_PARAMETER_VALUE view.searches = paginator.page(1) except EmptyPage: logger.warn('Provided value for page parameter is out of bounds for paginator') view.error_message = INVALID_SEARCH_PARAMETER_VALUE view.searches = paginator.page(paginator.num_pages) else: logger.info('Did not receive page parameter') view.current_page = 1 view.searches = paginator.page(1) log_end_time()
def get(self, request, *args, **kwargs): """ Retrieves diagnosis category records from database then creates a formset depending on the number of retrieved rows. Pre-fills patient field using relationship between retrieved value of [medical] argument from URI :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() initial = [] logger.info('Retrieving diagnosis categories for form creation') diagnosis_categories = DiagnosisCategory.objects.all() logger.info('Retrieving medical record ID from request URI') medical_record_id = request.GET.get('medical') logger.info('Retrieving diagnosis record ID from request URI') diagnosis_id = kwargs.get('id') if medical_record_id: logger.info('Retrieved medical record ID value [%s]' % medical_record_id) medical_record = MedicalRecord.objects.get(pk=medical_record_id) logger.info( 'Creating initial diagnosis_category and value for each form in formset' ) for category in diagnosis_categories: initial.append({ 'diagnosis_category': category, 'value': '', }) formset = self.DiagnosisFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': medical_record, 'submit_label': 'Record' }) elif diagnosis_id: logger.info('Retrieved diagnosis record ID value [%s]' % diagnosis_id) diagnosis = Diagnosis.objects.get(pk=diagnosis_id) for category in diagnosis_categories: diagnosis_entry = DiagnosisEntry.objects.filter( diagnosis=diagnosis, diagnosis_category=category) if diagnosis_entry.count() > 1: logger.warn( 'Diagnosis entry count is greater than expected for category [%s]' % category) logger.info('Defaulting to first retrieved item') initial.append({ 'diagnosis_category': diagnosis_entry.first().diagnosis_category, 'value': diagnosis_entry.first().value, 'remark': diagnosis_entry.first().remark if diagnosis_entry.first().remark else '' }) elif diagnosis_entry.count() < 1: logger.info( 'No related diagnosis entry for category [%s]' % category) initial.append({ 'diagnosis_category': category, 'value': '', }) else: logger.info( 'Successful diagnosis entry retrieval for category [%s]' % category) initial.append({ 'diagnosis_category': diagnosis_entry.last().diagnosis_category, 'value': diagnosis_entry.last().value, 'remark': diagnosis_entry.last().remark if diagnosis_entry.last().remark else '' }) formset = self.DiagnosisFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': diagnosis.medical_record, 'submit_label': 'Update', 'diagnosis': diagnosis }) else: logger.warn('Did not receive value for required medical parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves diagnosis category records from database. These categories will be used to fetch records for patient's diagnosis record. Categories will be used to group and order diagnosis entry records within a zip list. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() category_list = [] diagnosis_entry_per_category_list = [] logger.info('Retrieving diagnosis id from request URI') diagnosis = self.model.objects.get(pk=kwargs.get('id')) diagnosis_categories = DiagnosisCategory.objects.all().order_by( 'order') for category in diagnosis_categories: logger.info( 'Retrieving diagnosis entry records for category [%s]' % category) category_list.append(category) diagnosis_entry = DiagnosisEntry.objects.filter( diagnosis=diagnosis, diagnosis_category=category) if diagnosis_entry.count() > 1: logger.warn( 'Diagnosis entry count is greater than expected for category [%s]' % category) logger.info('Defaulting to first retrieved item') diagnosis_entry_per_category_list.append( diagnosis_entry.first()) elif diagnosis_entry.count() < 1: logger.info('No related diagnosis entry for category [%s]' % category) diagnosis_entry_per_category_list.append(None) else: logger.info( 'Successful diagnosis entry retrieval for category [%s]' % category) diagnosis_entry_per_category_list.append( diagnosis_entry.last()) category_entry_zip = zip(category_list, diagnosis_entry_per_category_list) log_end_time() return render( request, self.template_name, { 'diagnosis': diagnosis, 'category_entry_zip': category_entry_zip, 'max_column_width': -12, 'max_cell_width': -6, 'edit_link': reverse_lazy(DIAGNOSIS_EDIT_PAGE_NAME, kwargs={'id': diagnosis.id}) })
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new diagnosis record then saves diagnosis entry records with non-empty value. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() if 'cancel' in request.POST: logger.info('User clicked cancel') return HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) else: logger.info('User clicked submit') logger.info('Retrieving POST data') formset = self.DiagnosisFormSet(request.POST) diagnosis_id = request.POST.get('diagnosis') medical_record = MedicalRecord.objects.get( pk=int(request.POST.get('medical_record'))) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') if diagnosis_id: logger.info( 'Retrieved diagnosis record as foreign key for diagnosis entry records' ) diagnosis = Diagnosis.objects.get(pk=diagnosis_id) else: logger.info( 'Created diagnosis record as foreign key for diagnosis entry records' ) diagnosis = Diagnosis(medical_record=medical_record, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for idx, form in enumerate(formset): if diagnosis_id: logger.info( 'Retrieving latest diagnosis entry for diagnosis record [%s] and diagnosis category [%s]' % (diagnosis_id, form.instance.diagnosis_category)) diagnosis_entry = DiagnosisEntry.objects.filter( diagnosis=diagnosis, diagnosis_category=form.instance.diagnosis_category ).order_by('-id').first() else: logger.info( 'Creating latest diagnosis entry for diagnosis record [%s] and diagnosis category [%s]' % (diagnosis_id, form.instance.diagnosis_category)) diagnosis_entry = form.save(commit=False) if diagnosis_entry and diagnosis_entry.value: if diagnosis_id: logger.info('Updating details of diagnosis entry') diagnosis_entry.value = form.instance.value diagnosis_entry.remark = form.instance.remark else: logger.info( 'Saving details of new diagnosis entry') diagnosis.save() diagnosis_entry.diagnosis = diagnosis diagnosis_entry.recorded_by = request.user diagnosis_entry.recorded_date = localtime(now()) diagnosis_entry.save() else: logger.info('Value for [%s] is empty') log_exit_atomic_trans() logger.info('Redirecting to diagnosis profile page') response = redirect(diagnosis) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, { 'formset': formset, 'medical_record': medical_record }) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves laboratory test detail records from database then creates a formset depending on the number of retrieved rows. Pre-fills patient field using relationship between retrieved value of [medical] argument from URI :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() initial = [] logger.info('Retrieving medical record ID from request URI') medical_record_id = request.GET.get('medical') logger.info('Retrieving laboratory record ID from request URI') laboratory_id = kwargs.get('id') laboratory_test_details = LaboratoryTestDetail.objects.all() if medical_record_id: logger.info('Retrieved medical record ID value [%s]' % medical_record_id) medical_record = MedicalRecord.objects.get( pk=int(medical_record_id)) for test_detail in laboratory_test_details: logger.info('Creating display labels for [%s]' % test_detail) display = '%s: %s' % (str( test_detail.laboratory_test), test_detail.description) if test_detail.laboratory_measurement_unit.is_displayable: display += ' (%s)' % test_detail.laboratory_measurement_unit logger.info('Created display is [%s]' % display) initial.append({ 'laboratory_test_detail_display': display, 'laboratory_test_detail': test_detail, 'value': '' }) formset = self.LaboratoryFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': medical_record, 'submit_label': 'Record' }) elif laboratory_id: logger.info('Retrieved laboratory record ID value [%s]' % laboratory_id) laboratory = Laboratory.objects.get(pk=int(laboratory_id)) for test_detail in laboratory_test_details: logger.info( 'Retrieving non-deleted laboratory results for laboratory record [%s] and test detail [%s]' % (laboratory_id, test_detail)) laboratory_result = LaboratoryResult.objects.filter( laboratory=laboratory, laboratory_test_detail=test_detail, is_deleted=False) logger.info('Creating display labels for [%s]' % test_detail) display = '%s: %s' % (str( test_detail.laboratory_test), test_detail.description) if test_detail.laboratory_measurement_unit.is_displayable: display += ' (%s)' % test_detail.laboratory_measurement_unit logger.info('Created display is [%s]' % display) if laboratory_result.count() > 1: logger.warn( 'Laboratory result count is greater than expected for test detail [%s]' % test_detail) logger.info('Defaulting to first retrieved item') initial.append({ 'laboratory_test_detail_display': display, 'laboratory_test_detail': laboratory_result.first().laboratory_test_detail, 'value': laboratory_result.first().value, }) elif laboratory_result.count() < 1: logger.info( 'No related laboratory result record for test detail [%s]' % test_detail) initial.append({ 'laboratory_test_detail_display': display, 'laboratory_test_detail': test_detail, 'value': '', }) else: logger.info( 'Successful laboratory result retrieval for test detail [%s]' % test_detail) initial.append({ 'laboratory_test_detail_display': display, 'laboratory_test_detail': laboratory_result.last().laboratory_test_detail, 'value': laboratory_result.last().value, }) formset = self.LaboratoryFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': laboratory.medical_record, 'submit_label': 'Update', 'laboratory': laboratory }) else: logger.warn('Did not receive value for required patient parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves records from database using value of [medical] argument from URI. Uses a default list page template. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() context = {} logger.info('Retrieving medical record id from request URI') patient_id = request.GET.get('patient') medical_record_id = request.GET.get('medical') if medical_record_id: medical_record = MedicalRecord.objects.get(pk=request.GET.get('medical')) patient = medical_record.patient logger.info('Retrieving records using medical record id value [%s]' % medical_record.id) result_list = self.model.objects.filter(medical_record=medical_record).order_by('-recorded_date') self.search_link = create_link(self.list_page_name, {'medical': medical_record.id}) context.update({'left_link': create_link(self.left_link_page_name, {'medical': medical_record.id}), 'left_link_icon': self.left_link_icon, 'left_link_name': self.left_link_name, 'center_link': medical_record.get_absolute_url(), 'center_link_icon': MEDICAL_RECORD_PAGE_ICON, 'center_link_name': 'Medical Record', 'right_link': create_link(self.right_link_page_name, {'medical': medical_record.id}), 'right_link_icon': self.right_link_icon, 'right_link_name': self.right_link_name, 'add_link': create_link(self.add_page_name, {'medical': medical_record.id}), }) elif patient_id: patient = Patient.objects.get(pk=request.GET.get('patient')) logger.info('Retrieving records using patient id value [%s]' % patient.id) result_list = self.model.objects.filter(patient=patient).order_by('-recorded_date') self.search_link = create_link(self.list_page_name, {'patient': patient.id}) context.update({'add_link': create_link(self.add_page_name, {'patient': patient.id}), }) else: logger.warn('Did not receive value for required medical parameter') return redirect(DASHBOARD_PAGE_NAME, permanent=True) paginator = Paginator(result_list, MAX_LIST_ITEMS_PER_PAGE) self.search_count = result_list.count() logger.info('Calling common functions for listing results') select_search_results(self, request, paginator) modify_page_links(self, paginator) validate_response(self) context.update({'searches': self.searches, 'patient': patient, 'pages': self.pages, 'search_link': self.search_link, 'error_message': self.error_message, 'page_title': self.page_title, 'page_icon': self.page_icon, 'current_page': self.current_page, 'next_link': self.next_link, 'next_link_class': self.next_link_class, 'previous_link': self.previous_link, 'previous_link_class': self.previous_link_class, }) log_end_time() return render(request, self.template_name, context)
def get(self, request, *args, **kwargs): """ Retrieves laboratory test detail records from database then creates a formset depending on the number of retrieved rows. Pre-fills patient field using relationship between retrieved value of [medical] argument from URI :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() initial = [] logger.info('Retrieving medical record ID from request URI') medical_record_id = request.GET.get('medical') logger.info('Retrieving laboratory record ID from request URI') laboratory_id = kwargs.get('id') laboratory_test_details = LaboratoryTestDetail.objects.all() if medical_record_id: logger.info('Retrieved medical record ID value [%s]' % medical_record_id) medical_record = MedicalRecord.objects.get(pk=int(medical_record_id)) for test_detail in laboratory_test_details: logger.info('Creating display labels for [%s]' % test_detail) display = '%s: %s' % (str(test_detail.laboratory_test), test_detail.description) if test_detail.laboratory_measurement_unit.is_displayable: display += ' (%s)' % test_detail.laboratory_measurement_unit logger.info('Created display is [%s]' % display) initial.append({'laboratory_test_detail_display': display, 'laboratory_test_detail': test_detail, 'value': ''}) formset = self.LaboratoryFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'medical_record': medical_record, 'submit_label': 'Record'}) elif laboratory_id: logger.info('Retrieved laboratory record ID value [%s]' % laboratory_id) laboratory = Laboratory.objects.get(pk=int(laboratory_id)) for test_detail in laboratory_test_details: logger.info( 'Retrieving non-deleted laboratory results for laboratory record [%s] and test detail [%s]' % ( laboratory_id, test_detail)) laboratory_result = LaboratoryResult.objects.filter(laboratory=laboratory, laboratory_test_detail=test_detail, is_deleted=False) logger.info('Creating display labels for [%s]' % test_detail) display = '%s: %s' % (str(test_detail.laboratory_test), test_detail.description) if test_detail.laboratory_measurement_unit.is_displayable: display += ' (%s)' % test_detail.laboratory_measurement_unit logger.info('Created display is [%s]' % display) if laboratory_result.count() > 1: logger.warn('Laboratory result count is greater than expected for test detail [%s]' % test_detail) logger.info('Defaulting to first retrieved item') initial.append({'laboratory_test_detail_display': display, 'laboratory_test_detail': laboratory_result.first().laboratory_test_detail, 'value': laboratory_result.first().value, }) elif laboratory_result.count() < 1: logger.info('No related laboratory result record for test detail [%s]' % test_detail) initial.append({'laboratory_test_detail_display': display, 'laboratory_test_detail': test_detail, 'value': '', }) else: logger.info('Successful laboratory result retrieval for test detail [%s]' % test_detail) initial.append({'laboratory_test_detail_display': display, 'laboratory_test_detail': laboratory_result.last().laboratory_test_detail, 'value': laboratory_result.last().value, }) formset = self.LaboratoryFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'medical_record': laboratory.medical_record, 'submit_label': 'Update', 'laboratory': laboratory}) else: logger.warn('Did not receive value for required patient parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new prescription record then saves prescription entry records with prescribe value set to True. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() if 'cancel' in request.POST: logger.info('User clicked cancel') return HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) else: logger.info('User clicked submit') logger.info('Retrieving POST data') formset = self.PrescriptionFormSet(request.POST) prescription_id = request.POST.get('prescription') medical_record = MedicalRecord.objects.get( pk=int(request.POST.get('medical_record'))) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') if prescription_id: logger.info( 'Retrieved prescription record as foreign key for prescription entry records' ) prescription = Prescription.objects.get(pk=prescription_id) else: logger.info( 'Created prescription record as foreign key for prescription entry records' ) prescription = Prescription(medical_record=medical_record, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for idx, form in enumerate(formset): data = form.cleaned_data if prescription_id: logger.info( 'Retrieving latest prescription entry for prescription record [%s] and medicine [%s]' % (prescription_id, form.instance.medicine)) prescription_entry = PrescriptionEntry.objects.filter( prescription=prescription, medicine=form.instance.medicine, is_deleted=False).order_by('-id').first() else: logger.info( 'Creating latest prescription entry for prescription record [%s] and medicine category [%s]' % (prescription_id, form.instance.medicine)) prescription_entry = form.save(commit=False) if prescription_entry: if prescription_id and data['prescribe']: logger.info( 'Updating details of prescription entry') prescription_entry.dosage = form.instance.dosage prescription_entry.package = form.instance.package prescription_entry.frequency = form.instance.frequency prescription_entry.designated_time = form.instance.designated_time elif prescription_id and not data['prescribe']: logger.info( 'Removing details of prescription entry') prescription_entry.is_deleted = True elif data['prescribe']: logger.info( 'Saving details of new prescription entry') prescription.save() prescription_entry.prescription = prescription else: logger.info( 'Skipping prescription entry for [%s]' % form.instance.medicine) continue else: logger.warn( 'No value for prescription_entry variable. Using value from form' ) if data['prescribe']: prescription.save() prescription_entry = form.save(commit=False) prescription_entry.prescription = prescription else: logger.info( 'Skipping prescription entry for [%s]' % form.instance.medicine) continue prescription_entry.updated_by = request.user prescription_entry.updated_date = localtime(now()) prescription_entry.save() log_exit_atomic_trans() logger.info('Redirecting to prescription profile page') response = redirect(prescription) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, { 'formset': formset, 'medical_record': medical_record }) log_end_time() return response
def process_search(self, request): """ Receives either POST or GET request then proceeds to search records depending on search query :param request: HttpRequest instance :return: HttpResponse instance """ log_start_time() form = initialise_form(self, request) if form is not None and form.is_valid(): logger.info('Received a valid form') self.search_type = form.cleaned_data['search_type'] self.search_param = form.cleaned_data['search_param'] logger.info('Creating search link using page name [%s]' % self.list_page_name) self.search_link = create_link(self.list_page_name, { 'search_param': self.search_param, 'search_type': self.search_type }) if self.search_param: logger.info('Received a non-empty search parameter') results = search_matches(self, self.search_type, self.search_param) else: logger.info('Did not receive a valid search parameter') results = self.model.objects.all().order_by('-id') paginator = Paginator(results, MAX_LIST_ITEMS_PER_PAGE) logger.info('Calling common functions for listing records') select_search_results(self, request, paginator) modify_page_links(self, paginator) validate_response(self) response = render( request, self.template_name, { 'form': form, 'search_link': self.search_link, 'searches': self.searches, 'search_type_labels': self.search_labels, 'act_search_type_label': self.search_labels.get(self.search_type), 'pages': self.pages, 'page_title': self.page_title, 'page_icon': self.page_icon, 'current_page': self.current_page, 'error_message': self.error_message, 'next_link': self.next_link, 'next_link_class': self.next_link_class, 'previous_link': self.previous_link, 'previous_link_class': self.previous_link_class, }) else: response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves records from database using value of [medical] argument from URI. Uses a default list page template. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() context = {} logger.info('Retrieving medical record id from request URI') patient_id = request.GET.get('patient') medical_record_id = request.GET.get('medical') if medical_record_id: medical_record = MedicalRecord.objects.get( pk=request.GET.get('medical')) patient = medical_record.patient logger.info( 'Retrieving records using medical record id value [%s]' % medical_record.id) result_list = self.model.objects.filter( medical_record=medical_record).order_by('-recorded_date') self.search_link = create_link(self.list_page_name, {'medical': medical_record.id}) context.update({ 'left_link': create_link(self.left_link_page_name, {'medical': medical_record.id}), 'left_link_icon': self.left_link_icon, 'left_link_name': self.left_link_name, 'center_link': medical_record.get_absolute_url(), 'center_link_icon': MEDICAL_RECORD_PAGE_ICON, 'center_link_name': 'Medical Record', 'right_link': create_link(self.right_link_page_name, {'medical': medical_record.id}), 'right_link_icon': self.right_link_icon, 'right_link_name': self.right_link_name, 'add_link': create_link(self.add_page_name, {'medical': medical_record.id}), }) elif patient_id: patient = Patient.objects.get(pk=request.GET.get('patient')) logger.info('Retrieving records using patient id value [%s]' % patient.id) result_list = self.model.objects.filter( patient=patient).order_by('-recorded_date') self.search_link = create_link(self.list_page_name, {'patient': patient.id}) context.update({ 'add_link': create_link(self.add_page_name, {'patient': patient.id}), }) else: logger.warn('Did not receive value for required medical parameter') return redirect(DASHBOARD_PAGE_NAME, permanent=True) paginator = Paginator(result_list, MAX_LIST_ITEMS_PER_PAGE) self.search_count = result_list.count() logger.info('Calling common functions for listing results') select_search_results(self, request, paginator) modify_page_links(self, paginator) validate_response(self) context.update({ 'searches': self.searches, 'patient': patient, 'pages': self.pages, 'search_link': self.search_link, 'error_message': self.error_message, 'page_title': self.page_title, 'page_icon': self.page_icon, 'current_page': self.current_page, 'next_link': self.next_link, 'next_link_class': self.next_link_class, 'previous_link': self.previous_link, 'previous_link_class': self.previous_link_class, }) log_end_time() return render(request, self.template_name, context)
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new laboratory record then saves laboratory result records with non-empty value. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving laboratory record ID from POST data') laboratory_id = request.POST.get('laboratory') logger.info('Retrieving medical record from database using medical record ID from POST data') medical_record = MedicalRecord.objects.get(pk=int(request.POST.get('medical_record'))) if 'cancel' in request.POST: logger.info('User clicked cancel') if medical_record: logger.info('Redirecting to medical record page') return HttpResponseRedirect( reverse_lazy(MEDICAL_RECORD_PROFILE_PAGE_NAME, kwargs={'id': medical_record.id})) else: logger.info('Redirecting to home page') return HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) else: logger.info('User clicked submit') logger.info('Retrieving POST data') formset = self.LaboratoryFormSet(request.POST) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') if laboratory_id: logger.info('Retrieved laboratory record as foreign key for laboratory result records') laboratory = Laboratory.objects.get(pk=int(laboratory_id)) else: logger.info('Created laboratory record as foreign key for laboratory result records') laboratory = Laboratory(medical_record=medical_record, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for form in formset: if laboratory_id: logger.info( 'Retrieving latest laboratory result for laboratory record [%s] and test detail [%s]' % ( laboratory_id, form.instance.laboratory_test_detail)) laboratory_result = LaboratoryResult.objects.filter(laboratory=laboratory, laboratory_test_detail=form.instance.laboratory_test_detail, is_deleted=False).order_by( '-id').first() else: logger.info( 'Creating latest laboratory result for laboratory record [%s] and test detail [%s]' % ( laboratory_id, form.instance.laboratory_test_detail)) laboratory_result = form.save(commit=False) if laboratory_result: logger.info('Received a non-empty instance for laboratory result') if laboratory_id and form.instance.value: if form.instance.value == laboratory_result.value: logger.info('No change was detected') else: logger.info('Updating details of laboratory laboratory') laboratory_result.value = form.instance.value elif laboratory_id and not form.instance.value: logger.info('Removing details of laboratory result') laboratory_result.is_deleted = True elif laboratory_result.value: logger.info('Saving details of new laboratory result for new laboratory record') laboratory.save() laboratory_result.laboratory = laboratory else: logger.info('Skipping laboratory result for [%s]' % form.instance.laboratory_test_detail) continue else: logger.info('No value for laboratory_result variable. Using value from form') if form.instance.value: logger.info('Saving details of new laboratory result for previous laboratory record') laboratory.save() laboratory_result = form.save(commit=False) laboratory_result.laboratory = laboratory else: logger.info('Skipping laboratory result for [%s]' % form.instance.laboratory_test_detail) continue laboratory_result.updated_by = request.user laboratory_result.updated_date = localtime(now()) laboratory_result.save() log_exit_atomic_trans() logger.info('Redirecting to laboratory profile page') response = redirect(laboratory) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, {'formset': formset, 'medical_record': medical_record}) log_end_time() return response
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new prescription record then saves prescription entry records with prescribe value set to True. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() if 'cancel' in request.POST: logger.info('User clicked cancel') return HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) else: logger.info('User clicked submit') logger.info('Retrieving POST data') formset = self.PrescriptionFormSet(request.POST) prescription_id = request.POST.get('prescription') medical_record = MedicalRecord.objects.get(pk=int(request.POST.get('medical_record'))) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') if prescription_id: logger.info('Retrieved prescription record as foreign key for prescription entry records') prescription = Prescription.objects.get(pk=prescription_id) else: logger.info('Created prescription record as foreign key for prescription entry records') prescription = Prescription(medical_record=medical_record, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for idx, form in enumerate(formset): data = form.cleaned_data if prescription_id: logger.info( 'Retrieving latest prescription entry for prescription record [%s] and medicine [%s]' % ( prescription_id, form.instance.medicine)) prescription_entry = PrescriptionEntry.objects.filter(prescription=prescription, medicine=form.instance.medicine, is_deleted=False).order_by( '-id').first() else: logger.info( 'Creating latest prescription entry for prescription record [%s] and medicine category [%s]' % ( prescription_id, form.instance.medicine)) prescription_entry = form.save(commit=False) if prescription_entry: if prescription_id and data['prescribe']: logger.info('Updating details of prescription entry') prescription_entry.dosage = form.instance.dosage prescription_entry.package = form.instance.package prescription_entry.frequency = form.instance.frequency prescription_entry.designated_time = form.instance.designated_time elif prescription_id and not data['prescribe']: logger.info('Removing details of prescription entry') prescription_entry.is_deleted = True elif data['prescribe']: logger.info('Saving details of new prescription entry') prescription.save() prescription_entry.prescription = prescription else: logger.info('Skipping prescription entry for [%s]' % form.instance.medicine) continue else: logger.warn('No value for prescription_entry variable. Using value from form') if data['prescribe']: prescription.save() prescription_entry = form.save(commit=False) prescription_entry.prescription = prescription else: logger.info('Skipping prescription entry for [%s]' % form.instance.medicine) continue prescription_entry.updated_by = request.user prescription_entry.updated_date = localtime(now()) prescription_entry.save() log_exit_atomic_trans() logger.info('Redirecting to prescription profile page') response = redirect(prescription) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, {'formset': formset, 'medical_record': medical_record}) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves medicine records from database then creates a formset depending on the number of retrieved rows. Pre- fills patient field using relationship between retrieved value of [medical] argument from URI :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() initial = [] logger.info('Retrieving medicine records for form creation') medicines = Medicine.objects.all() logger.info('Retrieving medical record ID from request URI') medical_record_id = request.GET.get('medical') logger.info('Retrieving prescription record ID from request URI') prescription_id = kwargs.get('id') if medical_record_id: logger.info('Retrieved medical record ID value [%s]' % medical_record_id) medical_record = MedicalRecord.objects.get(pk=medical_record_id) logger.info( 'Creating initial medicine and medicine_label for each form in formset' ) for medicine in medicines: initial.append({ 'medicine': medicine, 'medicine_label': medicine }) formset = self.PrescriptionFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': medical_record, 'submit_label': 'Record' }) elif prescription_id: logger.info('Retrieved prescription record ID value [%s]' % prescription_id) prescription = Prescription.objects.get(pk=prescription_id) logger.info('Creating') for medicine in medicines: prescription_entry = PrescriptionEntry.objects.filter( prescription=prescription, medicine=medicine, is_deleted=False) if prescription_entry.count() > 1: logger.warn( 'Prescription entry count is greater than expected for medicine [%s]' % medicine) logger.info('Defaulting to first retrieved item') initial.append({ 'medicine': prescription_entry.first().medicine, 'medicine_label': prescription_entry.first().medicine, 'dosage': prescription_entry.first().dosage, 'package': prescription_entry.first().package, 'frequency': prescription_entry.first().frequency, 'designated_time': prescription_entry.first().designated_time, 'prescribe': True, }) elif prescription_entry.count() < 1: logger.info( 'No related prescription entry for medicine [%s]' % medicine) initial.append({ 'medicine': medicine, 'medicine_label': medicine, }) else: logger.info( 'Successful prescription entry retrieval for medicine [%s]' % medicine) initial.append({ 'medicine': prescription_entry.last().medicine, 'medicine_label': prescription_entry.last().medicine, 'dosage': prescription_entry.last().dosage, 'package': prescription_entry.last().package, 'frequency': prescription_entry.last().frequency, 'designated_time': prescription_entry.last().designated_time, 'prescribe': True, }) formset = self.PrescriptionFormSet(initial=initial) response = render( request, self.template_name, { 'formset': formset, 'medical_record': prescription.medical_record, 'submit_label': 'Update', 'prescription': prescription }) else: logger.warn('Did not receive value for required medical parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def get(self, request, *args, **kwargs): """ Retrieves medicine records from database then creates a formset depending on the number of retrieved rows. Pre- fills patient field using relationship between retrieved value of [medical] argument from URI :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() initial = [] logger.info('Retrieving medicine records for form creation') medicines = Medicine.objects.all() logger.info('Retrieving medical record ID from request URI') medical_record_id = request.GET.get('medical') logger.info('Retrieving prescription record ID from request URI') prescription_id = kwargs.get('id') if medical_record_id: logger.info('Retrieved medical record ID value [%s]' % medical_record_id) medical_record = MedicalRecord.objects.get(pk=medical_record_id) logger.info('Creating initial medicine and medicine_label for each form in formset') for medicine in medicines: initial.append({'medicine': medicine, 'medicine_label': medicine}) formset = self.PrescriptionFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'medical_record': medical_record, 'submit_label': 'Record'}) elif prescription_id: logger.info('Retrieved prescription record ID value [%s]' % prescription_id) prescription = Prescription.objects.get(pk=prescription_id) logger.info('Creating') for medicine in medicines: prescription_entry = PrescriptionEntry.objects.filter(prescription=prescription, medicine=medicine, is_deleted=False) if prescription_entry.count() > 1: logger.warn('Prescription entry count is greater than expected for medicine [%s]' % medicine) logger.info('Defaulting to first retrieved item') initial.append({'medicine': prescription_entry.first().medicine, 'medicine_label': prescription_entry.first().medicine, 'dosage': prescription_entry.first().dosage, 'package': prescription_entry.first().package, 'frequency': prescription_entry.first().frequency, 'designated_time': prescription_entry.first().designated_time, 'prescribe': True, }) elif prescription_entry.count() < 1: logger.info('No related prescription entry for medicine [%s]' % medicine) initial.append({'medicine': medicine, 'medicine_label': medicine, }) else: logger.info('Successful prescription entry retrieval for medicine [%s]' % medicine) initial.append({'medicine': prescription_entry.last().medicine, 'medicine_label': prescription_entry.last().medicine, 'dosage': prescription_entry.last().dosage, 'package': prescription_entry.last().package, 'frequency': prescription_entry.last().frequency, 'designated_time': prescription_entry.last().designated_time, 'prescribe': True, }) formset = self.PrescriptionFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'medical_record': prescription.medical_record, 'submit_label': 'Update', 'prescription': prescription}) else: logger.warn('Did not receive value for required medical parameter') response = redirect(DASHBOARD_PAGE_NAME, permanent=True) log_end_time() return response
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new laboratory record then saves laboratory result records with non-empty value. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() logger.info('Retrieving laboratory record ID from POST data') laboratory_id = request.POST.get('laboratory') logger.info( 'Retrieving medical record from database using medical record ID from POST data' ) medical_record = MedicalRecord.objects.get( pk=int(request.POST.get('medical_record'))) if 'cancel' in request.POST: logger.info('User clicked cancel') if medical_record: logger.info('Redirecting to medical record page') return HttpResponseRedirect( reverse_lazy(MEDICAL_RECORD_PROFILE_PAGE_NAME, kwargs={'id': medical_record.id})) else: logger.info('Redirecting to home page') return HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) else: logger.info('User clicked submit') logger.info('Retrieving POST data') formset = self.LaboratoryFormSet(request.POST) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') if laboratory_id: logger.info( 'Retrieved laboratory record as foreign key for laboratory result records' ) laboratory = Laboratory.objects.get(pk=int(laboratory_id)) else: logger.info( 'Created laboratory record as foreign key for laboratory result records' ) laboratory = Laboratory(medical_record=medical_record, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for form in formset: if laboratory_id: logger.info( 'Retrieving latest laboratory result for laboratory record [%s] and test detail [%s]' % (laboratory_id, form.instance.laboratory_test_detail)) laboratory_result = LaboratoryResult.objects.filter( laboratory=laboratory, laboratory_test_detail=form.instance. laboratory_test_detail, is_deleted=False).order_by('-id').first() else: logger.info( 'Creating latest laboratory result for laboratory record [%s] and test detail [%s]' % (laboratory_id, form.instance.laboratory_test_detail)) laboratory_result = form.save(commit=False) if laboratory_result: logger.info( 'Received a non-empty instance for laboratory result' ) if laboratory_id and form.instance.value: if form.instance.value == laboratory_result.value: logger.info('No change was detected') else: logger.info( 'Updating details of laboratory laboratory' ) laboratory_result.value = form.instance.value elif laboratory_id and not form.instance.value: logger.info( 'Removing details of laboratory result') laboratory_result.is_deleted = True elif laboratory_result.value: logger.info( 'Saving details of new laboratory result for new laboratory record' ) laboratory.save() laboratory_result.laboratory = laboratory else: logger.info('Skipping laboratory result for [%s]' % form.instance.laboratory_test_detail) continue else: logger.info( 'No value for laboratory_result variable. Using value from form' ) if form.instance.value: logger.info( 'Saving details of new laboratory result for previous laboratory record' ) laboratory.save() laboratory_result = form.save(commit=False) laboratory_result.laboratory = laboratory else: logger.info('Skipping laboratory result for [%s]' % form.instance.laboratory_test_detail) continue laboratory_result.updated_by = request.user laboratory_result.updated_date = localtime(now()) laboratory_result.save() log_exit_atomic_trans() logger.info('Redirecting to laboratory profile page') response = redirect(laboratory) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, { 'formset': formset, 'medical_record': medical_record }) log_end_time() return response
def __init__(self, *args, **kwargs): """ Retrieves initial data for diagnosis category choices during form creation. However, data is retrieved from [data] instead of [initial] in kwargs after performing form validation :param args: variable arguments :param kwargs: named arguments """ super(DiagnosisEntryForm, self).__init__(*args, **kwargs) log_start_time() choice_list = None logger.info('Setting default label and widget for value and remark fields') self.fields['value'].label = '' self.fields['remark'].label = '' self.fields['value'].widget = NonInputWidget() self.fields['remark'].widget = NonInputWidget() logger.info('Retrieving diagnosis category') if kwargs.get('data'): logger.info('Performing initial form creation') diagnosis_category = DiagnosisCategory.objects.get( pk=kwargs.get('data')['%s-diagnosis_category' % kwargs.get('prefix')]) elif kwargs.get('initial'): logger.info('Performed form validation') diagnosis_category = kwargs.get('initial')['diagnosis_category'] else: logger.warn('Did not receive value for required diagnosis_category parameter') diagnosis_category = None if diagnosis_category: logger.info('Setting label for value field using [%s]' % diagnosis_category) self.fields['value'].label = diagnosis_category logger.info('Instantiating form helper for [%s]' % diagnosis_category) self.helper = DiagnosisCategoryFormHelper(diagnosis_category) logger.info('Retrieving choices from database for [%s]' % diagnosis_category) choice_list = DiagnosisCategoryChoice.objects.filter( diagnosis_category=diagnosis_category).order_by('order') else: logger.warn('diagnosis_category is none or empty') if choice_list: logger.info( 'Creating dropdown widget for value field using retrieved choices for [%s]' % diagnosis_category) self.fields['value'].widget = Select(choices=list(choice_list.values_list('description', 'description'))) logger.info('Checking if list for [%s] contains a general term' % diagnosis_category) for choice in choice_list: if choice.is_general_term: logger.info('Setting CSS class and widget for [%s]' % choice) self.fields['remark'].widget = Textarea( attrs={'placeholder': 'Additional Information', 'style': 'height: 5em;', }) else: pass else: logger.info('No choice list found for [%s]' % diagnosis_category) log_end_time()
def post(self, request, *args, **kwargs): """ Validates formset data. Creates a new medication record even for updates then saves medication entry records with non-empty description value. :param request: HttpRequest :param args: variable arguments :param kwargs: named arguments :return: HttpResponse """ log_start_time() error_message = None logger.info('Retrieving medication ID from POST data') medication_id = request.POST.get('medication') logger.info('Retrieving patient ID from POST data') patient = Patient.objects.get(pk=int(request.POST.get('patient'))) if medication_id: logger.info('Updating medication record') submit_label = 'Update' else: logger.info('Creating new medication record') submit_label = 'Record' if 'cancel' in request.POST: logger.info('User clicked cancel - Redirecting to [%s]' % DASHBOARD_PAGE_NAME) response = HttpResponseRedirect(reverse_lazy(DASHBOARD_PAGE_NAME)) elif 'add' in request.POST: logger.info('User clicked add - Creating formset with 1 extra form and delete functionality') MedicationFormSet = formset_factory(self.form_class, can_delete=True, extra=1) initial_formset = MedicationFormSet(request.POST) logger.info('Retrieving form data from POST request for formset pre-fill') formset = MedicationFormSet(initial=extract_form_data(initial_formset)) response = render(request, self.template_name, {'formset': formset, 'patient': patient, 'submit_label': submit_label}) elif 'delete' in request.POST: logger.info('User clicked delete - Removing deleted forms from formset') MedicationFormSet = formset_factory(self.form_class, can_delete=True, extra=0) initial_formset = MedicationFormSet(request.POST) if len(initial_formset.deleted_forms) >= len(initial_formset): logger.warn('Number of deleted forms is equal to total number of forms') error_message = CANNOT_DELETE_ALL_FORMS formset = MedicationFormSet(initial=extract_form_data(initial_formset)) else: logger.info('Removing deleted forms from initial formset') initial = [] for form in initial_formset: data = {} for field in form.fields: data[field] = form[field].value() if not data['DELETE']: logger.info('Form is removed from formset') initial.append(data) else: logger.info('Form is included in formset') formset = MedicationFormSet(initial=initial) response = render(request, self.template_name, {'formset': formset, 'patient': patient, 'submit_label': submit_label, 'error_message': error_message}) else: logger.info('User clicked submit - Validating forms') MedicationFormSet = formset_factory(self.form_class, can_delete=True, extra=0) formset = MedicationFormSet(request.POST) logger.info('Validating formset values') if formset.is_valid(): logger.info('Received valid formset data') medication = Medication(patient=patient, recorded_by=request.user, recorded_date=localtime(now())) with atomic(): log_enter_atomic_trans() for idx, form in enumerate(formset): if None in form.cleaned_data: pass else: break medication.save() medication_entry = form.save(commit=False) medication_entry.medication = medication medication_entry.save() log_exit_atomic_trans() if medication.id: logger.info('Redirecting to medication profile page') response = redirect(medication) else: logger.info('Did not receive any valid form') error_message = MINIMUM_REQUIRED_NUMBER_OF_FORMS MedicationFormSet = formset_factory(self.form_class) response = render(request, self.template_name, {'formset': MedicationFormSet(), 'patient': patient, 'submit_label': submit_label, 'error_message': error_message}) else: logger.warn('Received invalid formset data') response = render(request, self.template_name, {'formset': formset, 'patient': patient, 'submit_label': submit_label}) log_end_time() return response