from datetime import datetime, date, timedelta

import barcode as barcode
from django.core.exceptions import ObjectDoesNotExist
import random
from random import randint
import json
from django.utils import timezone
import operator
import calendar
import django.utils
from decimal import Decimal
import sendgrid
from django.conf import settings
from string import Template
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
import models
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q
import os
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
import pdfkit




def search_for_username(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         if request.is_ajax():
                query = str(request.GET.get('term', ''))
                if query:
                    try:
                         Username=models.AuthUser.objects.filter(username__startswith=query)[:5]
                    except ObjectDoesNotExist:
                         Username=''


                    if Username:
                        results ='This username is already in use by other user.'
                    else:
                        results ='This username is available.'
                    results.append(results)
                    data = json.dumps(results)
                    mimetype = 'application/json'
                    return HttpResponse(data, mimetype)
                #else:
                     #data = 'Any request was Made!!'
                     #mimetype = 'application/json'
                     #return HttpResponse(data, mimetype)


def search_for_client(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         if request.is_ajax():
                query = str(request.GET.get('term', ''))
                if query:
                    try:
                         Clients=models.Client.objects.filter(client_code__startswith=query)[:10]

                    except ObjectDoesNotExist:
                         Clients=models.Client.objects.filter(business_legal_name__startswith=query)[:10]

                    results = []
                    for Client in Clients:
                        drug_json={}
                        drug_json['id'] = Client.client_id
                        drug_json['label'] = Client.client_code
                        drug_json['value']= Client.business_legal_name
                        results.append(drug_json)
                    data = json.dumps(results)
                    mimetype = 'application/json'
                    return HttpResponse(data, mimetype)
                else:
                     data = 'Any request was Made!!'
                     mimetype = 'application/json'
                     return HttpResponse(data, mimetype)

def blank(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         if request.is_ajax():
                q = request.GET.get('term', '')
                if q:
                    Patients=models.Patient.objects.filter(first_name__startswith=str(q))[:20]
                    results = []
                    for Patient in Patients:
                        drug_json = {}
                        drug_json['id'] = Patient.patient_id
                        drug_json['label'] = Patient.full_name()
                        drug_json['value']= Patient.first_name
                        results.append(drug_json)
                    data = json.dumps(results)
                    mimetype = 'application/json'
                    return HttpResponse(data, mimetype)
                else:
                     data = 'Fail'
                     mimetype = 'application/json'
                     return HttpResponse(data, mimetype)

         return render_to_response('dashboard_screen/blank.html', {
             'title': 'DashBoard',
         },c)

     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def blank2(request):
     c = RequestContext(request)
     if request.user.is_authenticated():

         if request.is_ajax() or request.method == 'POST':
            if 'fistname' in request.POST:
                    fistname = request.POST.get('fistname', '')

            if fistname:
               return render_to_response('dashboard_screen/blank.html', {'test':fistname}, context_instance=RequestContext(request))
            else:
                return render_to_response('dashboard_screen/blank.html', {'test':'nonono'}, context_instance=RequestContext(request))
         else:

             return render_to_response('dashboard_screen/blank.html', {
                   'title': 'DashBoard',
             },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def search(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         error=''
         if request.is_ajax() or 'search' in request.POST:

             Patients=models.Patient.objects.all()

             if 'patient_external_id' in request.POST:
                 patient_external_id = str(request.POST.get('patient_external_id', ''))
                 Patients.filter(ext_id=patient_external_id)

             if 'patient_last_name' in request.POST:
                 patient_last_name = str(request.POST.get('patient_last_name', ''))
                 Patients.filter(last_name=patient_last_name)

             if 'patient_first_name' in request.POST:
                 patient_first_name = str(request.POST.get('patient_first_name', ''))
                 Patients.filter(first_name=patient_first_name)

             if not patient_first_name or not patient_external_id or not patient_last_name:
                 error='No Data to search, Please Provide one of the field.'

             #error=patient_external_id

             return render_to_response('dashboard_screen/new_entry.html', {
                 'title': 'New Entry',
                 'error':error,
                 'patients':Patients,
             },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def wizard(request, step_id=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         states = models.state.objects.all()
         no_gyn_specimen_sources=models.Non_GYN_Specimen_Sources.objects.all()
         error=''
         CaseTypes=models.CaseType.objects.all()

         Exams=models.Exam.objects.all()
         start_date= date.today()
         end_date = start_date
         date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
         start_date = date_with_time.replace(hour=00, minute=00)
         date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
         end_date = date_with_time2.replace(hour=23, minute=59)
         Patient=''
         CaseTypes_in=[]
         CaseTypes_names_in=[]
         Clients=models.Client.objects.filter(is_aproved=1)
         Clients_able_to_work=[]
         for Client in Clients:
             if Client.has_price():
                 Clients_able_to_work.append(Client)



         if step_id:
             Step=step_id
         else:
             Step=0

         if request.method == "POST":
         ###############################################################################################################
             if 'new_case' in request.POST:
                 if 'patient_id' in request.POST:
                     patient_id = int(request.POST.get('patient_id', ''))
                     try:
                          Patient = models.Patient.objects.get(patient_id=patient_id)
                     except ObjectDoesNotExist:
                          Patient=''
                 else:
                     Patient=''

                 if 'patient_first_name' in request.POST:
                     patient_first_name = str(request.POST.get('patient_first_name', ''))
                 else:
                     patient_first_name=''

                 if 'patient_last_name' in request.POST:
                     patient_last_name = str(request.POST.get('patient_last_name', ''))
                 else:
                     patient_last_name=''

                 if Patient:
                     Entries=models.Entry.objects.filter(patient=Patient,initial_info=0,created_date__range=(start_date,end_date))

                     for Entry in Entries:
                         old_exams=Entry.test_in_entry.all()
                         for test_in in old_exams:
                             Exam=models.Exam.objects.get(exam_id=test_in.exam_id)
                             Exam.entry.remove(Entry)

                         old_accessions=Entry.accession_number.all()
                         for accession in old_accessions:
                             try:
                                 Acc=models.Accession.objects.get(id=accession.id)
                             except ObjectDoesNotExist:
                                 Acc=''
                             if Acc:
                                 Entry.accession_number.remove(Acc)

                             path1='/'+str(Acc.barcode_img)

                             if os.path.exists(path1):
                                os.remove(path1)
                             Acc.delete()
                             Entry.delete()

                 return render_to_response('dashboard_screen/wizard.html', {
                     'title': 'New Entry',
                     'message':error,
                     'Patient':Patient,
                     'Step':Step,
                     'Lab':Lab,
                     'states':states,
                     'CaseTypes':CaseTypes,
                     'CaseTypes_in':CaseTypes_in,
                     'Exams':Exams,
                     'no_gyn_specimen_sources':no_gyn_specimen_sources,
                     'Clients':Clients_able_to_work,
                     'patient_first_name':patient_first_name,
                     'patient_last_name':patient_last_name

                 },c)
         ###############################################################################################################
             if 'save_step1' in request.POST:

                 if 'patient_id' in request.POST:
                     patient_id =request.POST.get('patient_id', '')
                     if patient_id:
                         try:
                              Patient = models.Patient.objects.get(patient_id=int(patient_id))
                         except ObjectDoesNotExist:
                              Patient=''
                 else:
                     Patient=''

                 if Patient:
                     try:
                        Entry = models.Entry.objects.get(patient=Patient,initial_info=0,created_date__range=(start_date,end_date))
                     except ObjectDoesNotExist:
                        Entry=''

                     error=''
                     if 'client_id' in request.POST:
                         client_id=int(request.POST.get('client_id', ''))
                         if client_id:
                             try:
                                Client = models.Client.objects.get(client_id=client_id)
                             except ObjectDoesNotExist:
                                Client=''
                             if not Client:
                                 error='We dont recognize this Client'
                         Patient.patient_client=Client

                     else:
                         error='Please Client ID is a Mandatory Field'


                     if 'patient_dob' in request.POST:
                         patient_dob = str(request.POST.get('patient_dob', ''))
                         if patient_dob != '':
                            start_d = patient_dob.split('/')
                            y_start= int(start_d[2])
                            m_start= int(start_d[0])
                            d_start= int(start_d[1])
                            patient_dob= date(y_start, m_start, d_start)
                            Patient.dob=patient_dob
                     else:
                         error='Please DOB is a Mandatory Field'

                     if 'patient_external_id' in request.POST:
                         patient_external_id = str(request.POST.get('patient_external_id', ''))
                         Patient.ext_id=patient_external_id
                     else:
                         error='Please External ID is a Mandatory Field'

                     if 'patient_last_name' in request.POST:
                         patient_last_name = str(request.POST.get('patient_last_name', ''))
                         Patient.last_name=patient_last_name

                     if 'patient_phone' in request.POST:
                         patient_phone = str(request.POST.get('patient_phone', ''))

                     else:
                         error='Please fill Mandatory Fields'

                     if 'patient_first_name' in request.POST:
                         patient_first_name = str(request.POST.get('patient_first_name', ''))
                         Patient.first_name=patient_first_name
                     else:
                         error='Please fill Mandatory Fields'

                     if 'patient_ethnicity' in request.POST:
                         patient_ethnicity = str(request.POST.get('patient_ethnicity', ''))
                         Patient.ethnicity=patient_ethnicity

                     if 'patient_gender' in request.POST:
                         patient_gender = str(request.POST.get('patient_gender', ''))
                         Patient.gender=patient_gender

                     if 'patient_state' in request.POST:
                         patient_state = str(request.POST.get('patient_state', ''))
                         Patient.state =patient_state

                     if 'patient_zipcode' in request.POST:
                         patient_zipcode = str(request.POST.get('patient_zipcode', ''))
                         Patient.zipcode=patient_zipcode

                     if 'patient_address' in request.POST:
                         patient_address = str(request.POST.get('patient_address', ''))
                         Patient.address =patient_address

                     if 'patient_address2' in request.POST:
                         patient_address2 = str(request.POST.get('patient_address2', ''))
                         Patient.address2 =patient_address2

                     if 'patient_city' in request.POST:
                         patient_city = str(request.POST.get('patient_city', ''))
                         Patient.city =patient_city


                     if 'patient_phone' in request.POST:
                         patient_phone = str(request.POST.get('patient_phone', ''))
                         Patient.phone=patient_phone


                     if 'patient_ssn' in request.POST:
                         patient_ssn = str(request.POST.get('patient_ssn', ''))
                         Patient.SSN_number=patient_ssn
                     else:
                         error='Please fill Mandatory Fields'

                     if 'billing_option' in request.POST:
                         billing_option = request.POST.get('billing_option', '')
                         Patient.insurance_type=billing_option

                     if 'insurance_name' in request.POST:
                         insurance_name = request.POST.get('insurance_name', '')
                         Patient.insurance_name=insurance_name

                     if 'insurance_suscriber_number' in request.POST:
                         insurance_suscriber_number = request.POST.get('insurance_suscriber_number', '')
                         Patient.insurance_suscriber_number=insurance_suscriber_number

                     if 'insurance_group' in request.POST:
                         insurance_group = request.POST.get('insurance_group', '')
                         Patient.insurance_group=insurance_group

                     if 'insurance_dob' in request.POST:
                         insurance_dob = request.POST.get('insurance_dob', '')
                         if insurance_dob != '':
                            start_d = insurance_dob.split('/')
                            y_start= int(start_d[2])
                            m_start= int(start_d[0])
                            d_start= int(start_d[1])
                            insurance_dob= date(y_start, m_start, d_start)
                            Patient.insurance_dob=insurance_dob

                     if 'insurance_icd10' in request.POST:
                         insurance_icd10 = request.POST.get('insurance_icd10', '')
                         Patient.insurance_ICD10=insurance_icd10

                     if 'insurance_upin' in request.POST:
                         insurance_upin = request.POST.get('insurance_upin', '')
                         Patient.insurance_UPIN=insurance_upin

                     if 'responsible_party' in request.POST:
                         responsible_party = request.POST.get('responsible_party', '')
                         Patient.insurance_responsible_party=responsible_party

                     if 'insurance_relationship' in request.POST:
                         insurance_relationship = request.POST.get('insurance_relationship', '')
                         Patient.insurance_relationship=insurance_relationship


                     if 'GYN_speciment_type' in request.POST:
                         GYN_speciment_type = request.POST.get('GYN_speciment_type', '')
                         Patient.GYN_speciment_type=GYN_speciment_type

                     if 'GYN_clinically_suspicious' in request.POST:
                         GYN_clinically_suspicious = request.POST.get('GYN_clinically_suspicious', '')
                         Patient.GYN_clinically_suspicious=GYN_clinically_suspicious

                     if error: # if hubo error al hacer el update
                         Step=0  #lo tengo q poner a cero para mantenerlo en este paso1 sin guardar la info
                         if Entry:
                            Entry.step=0
                            Entry.save()
                            Exam_in=Entry.test_in_entry.all()
                            if Exam_in:
                                 for exam in Exam_in:
                                     cat_in=exam.exam_casetype.case_type_name
                                     if not cat_in in CaseTypes_names_in:
                                        CaseTypes_names_in.append(cat_in)
                                        CaseTypes_in.append(exam.exam_casetype)

                         return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 1
                             'title': 'Step1',
                             'message':error,
                             'Patient':Patient,
                             'Step':Step,
                             'Lab':Lab,
                             'states':states,
                             'CaseTypes':CaseTypes,
                             'CaseTypes_in':CaseTypes_in,
                             'Exams':Exams,
                             'Entry':Entry,
                             'no_gyn_specimen_sources':no_gyn_specimen_sources,
                             'clients':Clients,
                         },c)
                     else:
                         ###############################################################################################
                         Patient.save()
                         ###############################################################################################
                         Step=1 # cambiar por 1
                         error='The Patient info was Update '
                         if Entry:
                            Entry.step=1  # cambiar por 1
                            Entry.save()
                            Exam_in=Entry.test_in_entry.all()
                            if Exam_in:
                                 for exam in Exam_in:
                                     cat_in=exam.exam_casetype.case_type_name
                                     if not cat_in in CaseTypes_names_in:
                                        CaseTypes_names_in.append(cat_in)
                                        CaseTypes_in.append(exam.exam_casetype)
                         return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 2
                             'title': 'Step2',
                             'message':error,
                             'Patient':Patient,
                             'Step':Step,
                             'Lab':Lab,
                             'states':states,
                             'CaseTypes':CaseTypes,
                             'CaseTypes_in':CaseTypes_in,
                             'Exams':Exams,
                             'Entry':Entry,
                             'no_gyn_specimen_sources':no_gyn_specimen_sources,
                             'clients':Clients,
                         },c)
                 else:
                     error='No tengo patient lo tengo q crear'
                     if 'client_id' in request.POST:
                         client_id=int(request.POST.get('client_id', ''))
                         if client_id:
                             try:
                                Client = models.Client.objects.get(client_id=client_id)
                             except ObjectDoesNotExist:
                                Client=''
                             if not Client:
                                 error='We dont recognize this Client'


                     else:
                         error='Please Client ID is a Mandatory Field'
                     if 'patient_dob' in request.POST:
                         patient_dob = str(request.POST.get('patient_dob', ''))
                         if patient_dob != '':
                            start_d = patient_dob.split('/')
                            y_start= int(start_d[2])
                            m_start= int(start_d[0])
                            d_start= int(start_d[1])
                            patient_dob= date(y_start, m_start, d_start)
                     else:
                         error='Please DOB is a Mandatory Field'
                     if 'patient_ssn' in request.POST:
                         patient_ssn = str(request.POST.get('patient_ssn', ''))
                     else:
                         error='Please fill Mandatory Fields'

                     if 'patient_first_name' in request.POST:
                         patient_first_name = str(request.POST.get('patient_first_name', ''))
                     else:
                         error='Please fill Mandatory Fields'
                     if 'patient_last_name' in request.POST:
                         patient_last_name = str(request.POST.get('patient_last_name', ''))

                     Patient = models.Patient.objects.create(
                         dob=patient_dob,
                         SSN_number=patient_ssn,
                         first_name=patient_first_name,
                         last_name=patient_last_name,
                     )
                     Patient.patient_client=Client
                     if 'patient_external_id' in request.POST:
                         patient_external_id = str(request.POST.get('patient_external_id', ''))
                         Patient.ext_id=patient_external_id

                     if 'patient_ethnicity' in request.POST:
                         patient_ethnicity = str(request.POST.get('patient_ethnicity', ''))
                         Patient.ethnicity=patient_ethnicity

                     if 'patient_gender' in request.POST:
                         patient_gender = str(request.POST.get('patient_gender', ''))
                         Patient.gender=patient_gender

                     if 'patient_state' in request.POST:
                         patient_state = str(request.POST.get('patient_state', ''))
                         Patient.state =patient_state

                     if 'patient_zipcode' in request.POST:
                         patient_zipcode = str(request.POST.get('patient_zipcode', ''))
                         Patient.zipcode=patient_zipcode

                     if 'patient_address' in request.POST:
                         patient_address = str(request.POST.get('patient_address', ''))
                         Patient.address =patient_address

                     if 'patient_address2' in request.POST:
                         patient_address2 = str(request.POST.get('patient_address2', ''))
                         Patient.address2 =patient_address2

                     if 'patient_city' in request.POST:
                         patient_city = str(request.POST.get('patient_city', ''))
                         Patient.city =patient_city


                     if 'patient_phone' in request.POST:
                         patient_phone = str(request.POST.get('patient_phone', ''))
                         Patient.phone=patient_phone

                     if 'billing_option' in request.POST:
                         billing_option = request.POST.get('billing_option', '')
                         Patient.insurance_type=billing_option

                     if 'insurance_name' in request.POST:
                         insurance_name = request.POST.get('insurance_name', '')
                         Patient.insurance_name=insurance_name

                     if 'insurance_suscriber_number' in request.POST:
                         insurance_suscriber_number = request.POST.get('insurance_suscriber_number', '')
                         Patient.insurance_suscriber_number=insurance_suscriber_number

                     if 'insurance_dob' in request.POST:
                         insurance_dob = request.POST.get('insurance_dob', '')
                         if insurance_dob != '':
                            start_d = insurance_dob.split('/')
                            y_start= int(start_d[2])
                            m_start= int(start_d[0])
                            d_start= int(start_d[1])
                            insurance_dob= date(y_start, m_start, d_start)
                            Patient.insurance_dob=insurance_dob

                     if 'insurance_icd10' in request.POST:
                         insurance_icd10 = request.POST.get('insurance_icd10', '')
                         Patient.insurance_ICD10=insurance_icd10

                     if 'insurance_upin' in request.POST:
                         insurance_upin = request.POST.get('insurance_upin', '')
                         Patient.insurance_UPIN=insurance_upin

                     if 'responsible_party' in request.POST:
                         responsible_party = request.POST.get('responsible_party', '')
                         Patient.insurance_responsible_party=responsible_party

                     if 'insurance_relationship' in request.POST:
                         insurance_relationship = request.POST.get('insurance_relationship', '')
                         Patient.insurance_relationship=insurance_relationship


                     if 'GYN_speciment_type' in request.POST:
                         GYN_speciment_type = request.POST.get('GYN_speciment_type', '')
                         Patient.GYN_speciment_type=GYN_speciment_type

                     if 'GYN_clinically_suspicious' in request.POST:
                         GYN_clinically_suspicious = request.POST.get('GYN_clinically_suspicious', '')
                         Patient.GYN_clinically_suspicious=GYN_clinically_suspicious

                     if 'insurance_group' in request.POST:
                         insurance_group = request.POST.get('insurance_group', '')
                         Patient.insurance_group=insurance_group

                     Patient.save()
                     if error:
                         error='Please review the information'
                         Step=1 #lo tengo q poner a cero
                         return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 1
                             'title': 'Step1',
                             'message':error,
                             'Patient':Patient,
                             'Step':Step,
                             'Lab':Lab,
                             'states':states,
                             'CaseTypes':CaseTypes,
                             'CaseTypes_in':CaseTypes_in,
                             'Exams':Exams,
                             'no_gyn_specimen_sources':no_gyn_specimen_sources,
                             'Clients':Clients_able_to_work,

                         },c)
                     else:
                         Step=1
                         return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 2
                             'title': 'Step2',
                             'message':error,
                             'Patient':Patient,
                             'Step':Step,
                             'Lab':Lab,
                             'states':states,
                             'CaseTypes':CaseTypes,
                             'CaseTypes_in':CaseTypes_in,
                             'Exams':Exams,
                             'no_gyn_specimen_sources':no_gyn_specimen_sources,
                             'Clients':Clients_able_to_work,
                         },c)
         ###############################################################################################################
             if 'save_step2' in request.POST:
                 multi_casetype=''
                 Entry=''

                 if request.POST.getlist('my_multi_select2[]'):
                     multi_casetype = request.POST.getlist('my_multi_select2[]')
                 else:
                     error='You must select a Test.'

                 if 'patient_id' in request.POST:
                     patient_id = int(request.POST.get('patient_id', ''))
                     try:
                          Patient = models.Patient.objects.get(patient_id=patient_id)
                     except ObjectDoesNotExist:
                          Patient=''
                 else:
                     Patient=''

                 if 'collection_date' in request.POST:
                     collection_date = str(request.POST.get('collection_date', ''))
                     if collection_date != '':
                        start_d = collection_date.split('/')
                        y_start= int(start_d[2])
                        m_start= int(start_d[0])
                        d_start= int(start_d[1])
                        collection_date= date(y_start, m_start, d_start)
                 else:
                     collection_date=''

                 if 'physician_name' in request.POST:
                     physician_name = str(request.POST.get('physician_name', ''))


                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''
                 else:
                     Entry=''

                 if Entry:
                     import barcode
                     from barcode.writer import ImageWriter
                     Entry.collection_date=collection_date
                     Entry.physician_name=physician_name
                     Ldate= datetime.now()
                     Entry.lab_id=str(Ldate.year)+str(Ldate.month)+str(Ldate.day)+'-'+str(Entry.entry_id)

                     old_exams=Entry.test_in_entry.all()
                     for test_in in old_exams:
                         Exam=models.Exam.objects.get(exam_id=test_in.exam_id)
                         Exam.entry.remove(Entry)

                     old_accessions=Entry.accession_number.all()
                     for accession in old_accessions:
                         Acc=models.Accession.objects.get(id=accession.id)
                         if Acc:
                             Entry.accession_number.remove(Acc)

                         path1='/'+str(Acc.barcode_img)
                         if os.path.exists(path1):
                            os.remove(path1)
                         Acc.delete()

                     for requested_test in multi_casetype:
                         Exam=models.Exam.objects.get(exam_id=requested_test)
                         Exam.entry.add(Entry)


                     Entry.save()
                     Exam_in=Entry.test_in_entry.all()
                     if Exam_in:
                         for Exam in Exam_in:
                             sdate= datetime.now()
                             val=str(sdate.year)
                             val=val[-2:]
                             year=str(sdate.year)
                             y=year
                             m=str(sdate.month)
                             d=str(sdate.day)
                             h=str(sdate.hour)
                             mi=str(sdate.minute)
                             val1=y+m+d+h+mi
                             val2=randint(10000,99999)
                             val2=str(val2)
                             val3= str(val1)+val2
                             val3= str(val1)+val2

                             if Exam.exam_casetype.case_type_id == 1:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 GYN_accession_number = 'C' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean

                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(GYN_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=GYN_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 2:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 Non_GYN_accession_number = 'NG' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(Non_GYN_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=Non_GYN_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 3:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 MP_accession_number = 'M' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(MP_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=MP_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 4:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True

                                 Accession.save()
                                 SP_accession_number = 'S' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(SP_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=SP_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)
                     Entry.step=2



                     Exam_in=Entry.test_in_entry.all()
                     sdate= date.today()
                     if Exam_in:
                         for exam in Exam_in:
                             cat_in=exam.exam_casetype.case_type_name
                             if not cat_in in CaseTypes_names_in:
                                 CaseTypes_names_in.append(cat_in)
                                 CaseTypes_in.append(exam.exam_casetype)
                     Entry.save()
                     Step=2

                 else:
                     import barcode
                     from barcode.writer import ImageWriter

                     Entry=models.Entry.objects.create(
                         patient=Patient,
                         physician_name=physician_name,
                         collection_date=collection_date,
                     )
                     Entry.save()
                     Ldate= datetime.now()
                     Entry.lab_id=str(Ldate.year)+str(Ldate.month)+str(Ldate.day)+'-'+str(Entry.entry_id)
                     for requested_test in multi_casetype:
                         Exam=models.Exam.objects.get(exam_id=requested_test)
                         Exam.entry.add(Entry)
                         Exam.save()

                     Exam_in=Entry.test_in_entry.all()
                     if Exam_in:
                         for Exam in Exam_in:
                             sdate= datetime.now()
                             val=str(sdate.year)
                             val=val[-2:]
                             year=str(sdate.year)
                             y=year
                             m=str(sdate.month)
                             d=str(sdate.day)
                             h=str(sdate.hour)
                             mi=str(sdate.minute)
                             val1=y+m+d+h+mi
                             val2=randint(10000,99999)
                             val2=str(val2)
                             val3= str(val1)+val2
                             val3= str(val1)+val2

                             if Exam.exam_casetype.case_type_id == 1:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 Accession.access.add(Entry)
                                 EAN = barcode.get_barcode_class('ean13')
                                 GYN_accession_number = 'C' + val + '-'+str(Accession.id)
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(GYN_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=GYN_accession_number
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 2:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 Non_GYN_accession_number = 'NG' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(Non_GYN_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=Non_GYN_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 3:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )
                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 MP_accession_number = 'M' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+ str(MP_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=MP_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)

                             if Exam.exam_casetype.case_type_id == 4:
                                 Accession=models.Accession.objects.create(
                                     exam_in=Exam,
                                 )

                                 T_entries=Lab.total_entries_today()
                                 x=T_entries%10
                                 if x == 0:
                                     Accession.quality_control=True
                                 Accession.save()
                                 SP_accession_number = 'S' + val + '-'+str(Accession.id)
                                 EAN = barcode.get_barcode_class('ean13')
                                 ean = EAN(val3, writer=ImageWriter())
                                 barcode2=ean
                                 directory='media/exams/'+ str(Exam.exam_id)
                                 if not os.path.exists(directory):
                                    os.makedirs(directory)
                                 path2=directory+'/'+str(SP_accession_number)
                                 filename=ean.save(path2)

                                 Accession.barcode=barcode2
                                 Accession.barcode_img=filename
                                 Accession.accession_number=SP_accession_number
                                 Accession.access.add(Entry)
                                 Accession.save()
                                 imageFile=str(Accession.barcode_img)
                                 im1=Image.open(imageFile)
                                 draw = ImageDraw.Draw(im1)
                                 draw.text((70, 190),"Patient:"+Entry.patient.full_name()+ ' -'+'DOB:'+str(Entry.patient.dob.strftime("%Y/%m/%d"))+' -'+'Age:'+str(Entry.patient.how_old()),(0,0,0))
                                 draw.text((70, 203),"Accession Number:"+str(Accession.accession_number)+ ' -'+'Gender:'+str(Entry.patient.show_gender_name()) ,(0,0,0))
                                 draw.text((70, 216),"Created:"+str(Entry.created_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw.text((70, 229),"Collection Date:"+str(Entry.collection_date.strftime("%Y/%m/%d")),(0,0,0))
                                 draw = ImageDraw.Draw(im1)
                                 draw = ImageDraw.Draw(im1)
                                 im1.save(imageFile)
                     Entry.step=2
                     Step=2
                     Exam_in=Entry.test_in_entry.all()
                     if Exam_in:
                         for exam in Exam_in:
                             cat_in=exam.exam_casetype.case_type_name
                             if not cat_in in CaseTypes_names_in:
                                 CaseTypes_names_in.append(cat_in)
                                 CaseTypes_in.append(exam.exam_casetype)
                     Entry.save()

                 return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 1
                     'title': 'Step2',
                     'message':error,
                     'Patient':Patient,
                     'Step':Step,
                     'Lab':Lab,
                     'states':states,
                     'CaseTypes':CaseTypes,
                     'CaseTypes_in':CaseTypes_in,
                     'Exams':Exams,
                     'Entry':Entry,
                     'no_gyn_specimen_sources':no_gyn_specimen_sources,
                 },c)
         ###############################################################################################################
             if 'save_step3' in request.POST:
                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''
                 else:
                     Entry=''

                 Exam_in=Entry.test_in_entry.all()
                 if Exam_in:
                     for exam in Exam_in:
                         cat_in=exam.exam_casetype.case_type_name
                         if not cat_in in CaseTypes_names_in:
                             CaseTypes_names_in.append(cat_in)
                             CaseTypes_in.append(exam.exam_casetype)


                #####################################################
                 if Entry:
                     if 'GYN_Cervix' in request.POST:
                         Entry.GYN_Cervix = request.POST.get('GYN_Cervix', '')

                     if 'GYN_Vaginal' in request.POST:
                         Entry.GYN_Vaginal= request.POST.get('GYN_Vaginal', '')

                     if 'GYN_Endocervix' in request.POST:
                         Entry.GYN_Endocervix=request.POST.get('GYN_Endocervix', '')

                     if 'GYN_None' in request.POST:
                         Entry.GYN_None=request.POST.get('GYN_None', '')

                     if 'GYN_mestrual' in request.POST:
                         Entry.GYN_mestrual=request.POST.get('GYN_mestrual', '')

                     if 'GYN_last_menstrual_period' in request.POST:
                         Entry.GYN_last_menstrual_period =request.POST.get('GYN_last_menstrual_period', '')

                     if 'GYN_previous_biopsy' in request.POST:
                         Entry.GYN_previous_biopsy=request.POST.get('GYN_previous_biopsy', '')

                     if 'GYN_pap_smear' in request.POST:
                         Entry.GYN_pap_smear=request.POST.get('GYN_pap_smear', '')

                     if 'GYN_abnormal_report' in request.POST:
                         Entry.GYN_abnormal_report=request.POST.get('GYN_abnormal_report', '')

                     if 'GYN_routine' in request.POST:
                         Entry.GYN_routine=request.POST.get('GYN_routine', '')

                     if 'GYN_menopausal_syndrome' in request.POST:
                         Entry.GYN_menopausal_syndrome=request.POST.get('GYN_menopausal_syndrome', '')

                     if 'GYN_cervicitis' in request.POST:
                         Entry.GYN_cervicitis=request.POST.get('GYN_cervicitis', '')

                     if 'GYN_condyloma' in request.POST:
                         Entry.GYN_condyloma=request.POST.get('GYN_condyloma', '')

                     if 'GYN_herpes' in request.POST:
                         Entry.GYN_herpes=request.POST.get('GYN_herpes', '')

                     if 'GYN_iud' in request.POST:
                         Entry.GYN_iud=request.POST.get('GYN_iud', '')

                     if 'GYN_abnormal_bleeding' in request.POST:
                         Entry.GYN_abnormal_bleeding=request.POST.get('GYN_abnormal_bleeding', '')

                     if 'GYN_cervical_lesion' in request.POST:
                         Entry.GYN_cervical_lesion=request.POST.get('GYN_cervical_lesion', '')

                     if 'GYN_vaginitis' in request.POST:
                         Entry.GYN_vaginitis=request.POST.get('GYN_vaginitis', '')

                     if 'GYN_bleeds_on_contact' in request.POST:
                         Entry.GYN_bleeds_on_contact=request.POST.get('GYN_bleeds_on_contact', '')

                     if 'GYN_infection' in request.POST:
                         Entry.GYN_infection=request.POST.get('GYN_infection', '')

                     if 'GYN_discharge' in request.POST:
                         Entry.GYN_discharge=request.POST.get('GYN_discharge', '')

                     if 'GYN_discharge_info' in request.POST:
                         Entry.GYN_discharge_info=request.POST.get('GYN_discharge_info', '')

                     if 'GYN_hysterectomy' in request.POST:
                         Entry.GYN_hysterectomy=request.POST.get('GYN_hysterectomy', '')

                     if 'GYN_hysterectomy_description' in request.POST:
                         Entry.GYN_hysterectomy_description=request.POST.get('GYN_hysterectomy_description', '')

                     if 'Non_GYN_specimen_source' in request.POST:
                         Entry.Non_GYN_specimen_source=int(request.POST.get('Non_GYN_specimen_source', ''))

                     if 'Non_GYN_clinical_info' in request.POST:
                         Entry.Non_GYN_clinical_info=request.POST.get('Non_GYN_clinical_info', '')

                     if 'Non_GYN_gross_description' in request.POST:
                         Entry.Non_GYN_gross_description=request.POST.get('Non_GYN_gross_description', '')

                     if 'MP_speciment_source' in request.POST:
                         Entry.MP_speciment_source=request.POST.get('MP_speciment_source', '')

                     if 'SP_clinical_info' in request.POST:
                         Entry.SP_clinical_info=request.POST.get('SP_clinical_info', '')

                     if 'SP_specimen_source_1' in request.POST:
                         Entry.SP_specimen_source_1=request.POST.get('SP_specimen_source_1', '')

                     if 'SP_gross_description_1' in request.POST:
                         Entry.SP_gross_description_1=request.POST.get('SP_gross_description_1', '')

                     if 'SP_specimen_source_2' in request.POST:
                         Entry.SP_specimen_source_2=request.POST.get('SP_specimen_source_2', '')

                     if 'SP_gross_description_2' in request.POST:
                         Entry.SP_gross_description_2=request.POST.get('SP_gross_description_2', '')

                     if 'SP_specimen_source_3' in request.POST:
                         Entry.SP_specimen_source_3=request.POST.get('SP_specimen_source_3', '')

                     if 'SP_gross_description_3' in request.POST:
                         Entry.SP_gross_description_3=request.POST.get('SP_gross_description_3', '')

                     if 'SP_specimen_source_4' in request.POST:
                         Entry.SP_specimen_source_4=request.POST.get('SP_specimen_source_4', '')

                     if 'SP_gross_description_4' in request.POST:
                         Entry.SP_gross_description_4=request.POST.get('SP_gross_description_4', '')

                     if 'SP_specimen_source_5' in request.POST:
                         Entry.SP_specimen_source_5=request.POST.get('SP_specimen_source_5', '')

                     if 'SP_gross_description_5' in request.POST:
                         Entry.SP_gross_description_5=request.POST.get('SP_gross_description_5', '')

                     if 'SP_specimen_source_6' in request.POST:
                         Entry.SP_specimen_source_6=request.POST.get('SP_specimen_source_6', '')

                     if 'SP_gross_description_6' in request.POST:
                         Entry.SP_gross_description_6=request.POST.get('SP_gross_description_6', '')

                     if 'SP_specimen_source_7' in request.POST:
                         Entry.SP_specimen_source_7=request.POST.get('SP_specimen_source_7', '')

                     if 'SP_gross_description_7' in request.POST:
                         Entry.SP_gross_description_7=request.POST.get('SP_gross_description_7', '')

                     if 'SP_specimen_source_8' in request.POST:
                         Entry.SP_specimen_source_8=request.POST.get('SP_specimen_source_8', '')

                     if 'SP_gross_description_8' in request.POST:
                         Entry.SP_gross_description_8=request.POST.get('SP_gross_description_8', '')

                     if 'SP_specimen_source_9' in request.POST:
                         Entry.SP_specimen_source_9=request.POST.get('SP_specimen_source_9', '')

                     if 'SP_gross_description_9' in request.POST:
                         Entry.SP_gross_description_9=request.POST.get('SP_gross_description_9', '')

                     if 'SP_specimen_source_10' in request.POST:
                         Entry.SP_specimen_source_10=request.POST.get('SP_specimen_source_10', '')

                     if 'SP_gross_description_10' in request.POST:
                         Entry.SP_gross_description_10=request.POST.get('SP_gross_description_10', '')

                     if 'SP_specimen_source_11' in request.POST:
                         Entry.SP_specimen_source_11=request.POST.get('SP_specimen_source_11', '')

                     if 'SP_gross_description_11' in request.POST:
                         Entry.SP_gross_description_11=request.POST.get('SP_gross_description_11', '')

                     if 'SP_specimen_source_12' in request.POST:
                         Entry.SP_specimen_source_12=request.POST.get('SP_specimen_source_12', '')

                     if 'SP_gross_description_12' in request.POST:
                         Entry.SP_gross_description_12=request.POST.get('SP_gross_description_12', '')

                 Entry.step=3
                 Entry.save()
                 Step=3
                ########################################################################################################

                 return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 1
                     'title': 'Step3',
                     'message':error,
                     'Patient':Patient,
                     'Step':Step,
                     'Lab':Lab,
                     'states':states,
                     'CaseTypes':CaseTypes,
                     'CaseTypes_in':CaseTypes_in,
                     'Exams':Exams,
                     'Entry':Entry,
                     'no_gyn_specimen_sources':no_gyn_specimen_sources,
                 },c)
         ###############################################################################################################
             if 'save_step4' in request.POST:
                 sdate= date.today()

                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''
                 else:
                     Entry=''

                 Exam_in=Entry.test_in_entry.all()
                 if Exam_in:
                     for exam in Exam_in:
                         cat_in=exam.exam_casetype.case_type_name
                         if not cat_in in CaseTypes_names_in:
                             CaseTypes_names_in.append(cat_in)
                             CaseTypes_in.append(exam.exam_casetype)
                 Step=3
                 Entry.initial_info=1
                 Patient=Entry.patient


                 if 'print_labels' in request.POST:
                     if Entry:
                         all_acc=Entry.accession_number.all()
                         if all_acc:
                             for acc in all_acc:
                                 printer = os.popen('lpr', 'w')
                                 path='/'+str(acc.barcode_img)
                                 printer.write(path)
                                 printer.close()

                 exams=Entry.test_in_entry.all()

                 Entry.save()

                 return render_to_response('dashboard_screen/wizard.html', {  # este enviara al paso 4
                     'title': 'Step4',
                     'message':error,
                     'Patient':Patient,
                     'Step':Step,
                     'Lab':Lab,
                     'states':states,
                     'CaseTypes':CaseTypes,
                     'CaseTypes_in':CaseTypes_in,
                     'Exams':Exams,
                     'Entry':Entry,
                     'no_gyn_specimen_sources':no_gyn_specimen_sources,


                 },c)


         ###############################################################################################################

         else:
             return render_to_response('dashboard_screen/wizard.html', {
                 'title': 'New Entry',
                 'message':error,
                 'Patient':Patient,
                 'Step':Step,
                 'Lab':Lab,
                 'states':states,
                 'CaseTypes':CaseTypes,
                 'CaseTypes_in':CaseTypes_in,
                 'Exams':Exams,
                 'no_gyn_specimen_sources':no_gyn_specimen_sources,

             },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)



def new_entry(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         error=''
         Patients=''
         Clients=models.Client.objects.filter(is_aproved=1)
         Clients_able_to_work=[]
         for Client in Clients:
             if Client.has_price():
                 Clients_able_to_work.append(Client)

         if request.is_ajax() or 'search' in request.POST:
                 if 'patient_external_id' in request.POST:
                     patient_external_id = str(request.POST.get('patient_external_id', ''))

                 if 'patient_first_name' in request.POST:
                     patient_first_name = str(request.POST.get('patient_first_name', ''))
                 else:
                     patient_first_name=''

                 if 'patient_last_name' in request.POST:
                     patient_last_name = str(request.POST.get('patient_last_name', ''))
                 else:
                     patient_last_name=''

                 #if request.POST.getlist('my_multi_select2[]'):
                    # multi_casetype = request.POST.getlist('my_multi_select2[]')
                 #else:
                    # error='You must select a case type to start a new case.'
                 if not patient_first_name and not patient_external_id and not patient_last_name:
                     error='No Data to search, Please Provide one of the field.'
                     Patients=''

                 if patient_external_id:
                    Patients=models.Patient.objects.filter(ext_id__startswith=patient_external_id)

                 if patient_first_name:
                    Patients=models.Patient.objects.filter(first_name__startswith=patient_first_name)

                 if patient_last_name:
                    Patients=models.Patient.objects.filter(last_name__startswith=patient_last_name)

                 if Patients.count() > 0:
                     error='We found'+ str(Patients.count()) +'matches'
                 else:
                     error='We could not find matches for your search'

                 return render_to_response('dashboard_screen/new_entry.html', {
                     'title': 'New Entry',
                     'message':error,
                     'Patients':Patients,
                     'patient_first_name':patient_first_name,
                     'patient_last_name':patient_last_name,
                     'Lab':Lab,
                     'Clients':Clients_able_to_work,

                 },c)
         return render_to_response('dashboard_screen/new_entry.html', {
             'title': 'New Entry',
             'message':error,
             'Patients':Patients,
             'Lab':Lab,
             'Clients':Clients_able_to_work,

         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def queve(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         #start_date= date.today()
         #end_date = start_date
         #date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
         #start_date = date_with_time.replace(hour=00, minute=00)
         #date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
         #end_date = date_with_time2.replace(hour=23, minute=59)

         #'startdate':start_date,
         #'enddate':end_date,
         try:
             Entries=models.Entry.objects.filter(initial_info=1)  #, created_date__range=(start_date,end_date)
         except ObjectDoesNotExist:
             Entries=''

         return render_to_response('dashboard_screen/queve.html', {
             'title': 'Pending Queve',
             'Entries':Entries,
             'Lab':Lab,

         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
             'title': 'Login',
             'message': message,
             'pagetype':11,

         },c)
def pathology_queve(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         Ent2=[]
         Entries=models.Entry.objects.filter(initial_info=1)  #, created_date__range=(start_date,end_date)

         if Entries:
            for Ent in Entries:
                if Ent.accession_number.all():
                    for acc in Ent.accession_number.all():
                        if acc.pathology_queve and not acc.pathology_aproved:
                            Ent2.append(Ent)


         return render_to_response('dashboard_screen/pathology_queve.html', {
             'title': 'Pending Queve',
             'Entries':Ent2,
             'Lab':Lab,

         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
             'title': 'Login',
             'message': message,
             'pagetype':11,

         },c)
def quality_queve(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         start_date= date.today()
         end_date = start_date
         date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
         start_date = date_with_time.replace(hour=00, minute=00)
         date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
         end_date = date_with_time2.replace(hour=23, minute=59)
         Ent2=[]
         Entries=models.Entry.objects.filter(initial_info=1)  #, created_date__range=(start_date,end_date)

         if Entries:
            for Ent in Entries:
                if Ent.accession_number.all():
                    for acc in Ent.accession_number.all():
                        if acc.quality_control and not acc.quality_control_aproved:
                            Ent2.append(Ent)

         return render_to_response('dashboard_screen/quality_queve.html', {
             'title': 'Pending Queve',
             'Entries':Ent2,
             'startdate':start_date,
             'enddate':end_date,
             'Lab':Lab,

         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
             'title': 'Login',
             'message': message,
             'pagetype':11,

         },c)
def all_requisitions(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         start_date= date.today()
         end_date = start_date
         date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
         start_date = date_with_time.replace(hour=00, minute=00)
         date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
         end_date = date_with_time2.replace(hour=23, minute=59)

         if request.is_ajax() or 'export' in request.POST:

             if 'entry_id' in request.POST:
                 entry_id =request.POST.get('entry_id', '')
                 if entry_id:
                     try:
                          Entry = models.Entry.objects.get(entry_id=int(entry_id))
                     except ObjectDoesNotExist:
                          Entry=''

             if 'accesion_id' in request.POST:
                 accesion_id =request.POST.get('accesion_id', '')

             url='http://127.0.0.1:8000/dashboard/toPDF/'+str(Entry.entry_id)+'/'+str(accesion_id)+'/'

             config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
             options = {
                'page-size': 'Letter',
                'margin-top': '0.75in',
                'margin-right': '0.75in',
                'margin-bottom': '0.75in',
                'margin-left': '0.75in',
                'encoding': "UTF-8",
                'no-outline': None
            }
             directory='media/entries/'+str(Entry.entry_id)
             if not os.path.exists(directory):
                os.makedirs(directory)
             filename=directory+'/'+str(Entry.lab_id)+'.pdf'
             css='static/dashboard/css/style.css'
             path=filename
             Entry.entry_report=''

             from django.core.files.base import File as DjangoFile
             if not os.path.exists(path):
                 pdfkit.from_url(url, path, configuration=config,options=options)
                 Entry.entry_report.name=path
             else:
                 os.remove(path)
                 pdfkit.from_url(url, path, configuration=config, options=options)
                 Entry.entry_report.name=path

             Entry.save()


             with open(str(Entry.entry_report), 'rb') as pdf:
                 response = HttpResponse(pdf.read(),content_type='application/pdf')
                 response["Cache-Control"] = "max-age=0"
                 response["Accept-Ranges"] = "none"
                 response['Content-Disposition'] = 'attachment; filename='+str(Entry.lab_id)+'.pdf'


             return response

         Entries=models.Entry.objects.filter(initial_info=1)  #, created_date__range=(start_date,end_date)


         return render_to_response('dashboard_screen/all_requisitions.html', {
             'title': 'Pending Queve',
             'Entries':Entries,
             'startdate':start_date,
             'enddate':end_date,
             'Lab':Lab,

         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
             'title': 'Login',
             'message': message,
             'pagetype':11,

         },c)
def view_user(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

         return render_to_response('dashboard_screen/view_user.html', {
             'title': 'DashBoard',
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def users(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

         return render_to_response('dashboard_screen/users.html', {
             'title': 'DashBoard',
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def all_users(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         users=models.AuthUser.objects.all()

         return render_to_response('dashboard_screen/all_users.html', {
             'title': 'All Users',
             'Lab':Lab,
             'users':users,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)


def add_user(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         states = models.state.objects.all()
         groups=models.AuthGroup.objects.all()
         error=''
         if request.is_ajax() or 'save_user' in request.POST:

             if 'user_email' in request.POST:
                  user_email = request.POST.get('user_email', '')
                  try:
                      user1=models.AuthUser.objects.get(email=user_email)
                  except ObjectDoesNotExist:
                      user1=''

                  if user1:
                      error='This Email is already in used by other User.'
             else:
                 error='Please fill Mandatory Fields'

             if 'user_username' in request.POST:
                  user_username = request.POST.get('user_username', '')
                  try:
                      user2=models.AuthUser.objects.get(username=user_username)
                  except ObjectDoesNotExist:
                      user2=''

                  if user2:
                      error='This Username is already in used by other User.'
             else:
                 error='Please fill Mandatory Fields'


             if 'user_password' in request.POST:
                 user_password = request.POST.get('user_password', '')
             else:
                 error='Please fill Mandatory Fields'

             if 'user_first_name' in request.POST:
                  user_first_name = request.POST.get('user_first_name', '')
             else:
                 error='Please fill Mandatory Fields'


             if 'user_last_name' in request.POST:
                  user_last_name = request.POST.get('user_last_name', '')
             else:
                 error='Please fill Mandatory Fields'

             if 'user_phone' in request.POST:
                  user_phone = request.POST.get('user_phone', '')
             else:
                 error='Please fill Mandatory Fields'

             if not error:
                 New_User = models.User.objects.create(
                      username=user_username,
                      email=user_email,
                      first_name=user_first_name,
                      last_name=user_last_name,
                 )

                 New_User.set_password(user_password)
                 New_User.save()
                 if New_User:
                     New_UserProfile=models.UserProfile.objects.create(
                         user=New_User,
                         phone=user_phone,
                     )
                     New_UserProfile.save()


                 if 'user_group' in request.POST:
                     user_group=int(request.POST.get('user_group', ''))
                     group=models.AuthGroup.objects.get(id=user_group)

                 if group.id == 4:
                     New_User.is_superuser=1

                 New_User.is_active=1
                 New_User.save()

                 group_member=models.AuthUserGroups.objects.create(
                     user_id = New_User.id,
                     group_id = group.id,
                 )
                 group_member.save()

                 if 'user_address' in request.POST:
                     user_address = request.POST.get('user_address', '')
                     New_UserProfile.address=user_address


                 if 'user_address2' in request.POST:
                     user_address2 = request.POST.get('user_address2', '')
                     New_UserProfile.address2=user_address2

                 if 'user_city' in request.POST:
                     user_city = request.POST.get('user_city', '')
                     New_UserProfile.city=user_city

                 if 'user_zipcode' in request.POST:
                     user_zipcode = request.POST.get('user_zipcode', '')
                     New_UserProfile.zipcode=user_zipcode

                 if 'user_state' in request.POST:
                     user_state = request.POST.get('user_state', '')
                     New_UserProfile.state=user_state

                 New_UserProfile.save()

                 error='We save the New User Sucesfully'

                 return render_to_response('dashboard_screen/add_user.html', {
                     'message':error,
                     'states':states,
                     'Lab':Lab,
                 }, context_instance=RequestContext(request))


         return render_to_response('dashboard_screen/add_user.html', {
             'title': 'Add User',
             'states':states,
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def pending_client(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Clients = models.Client.objects.filter(is_aproved=0)
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

        # if request.user.

         return render_to_response('dashboard_screen/pending_client.html', {
             'title': 'Pending Client',
             'clients':Clients,
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def update_client_price(request,client_id):
     c = RequestContext(request)
     Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
     if request.user.is_authenticated():
         client_id=int(client_id)
         error=''
         try:
            Client = models.Client.objects.get(client_id=client_id)
         except ObjectDoesNotExist:
             Client=''

         if request.is_ajax() or 'edit_client_price' in request.POST:
             if 'client_id' in request.POST:
                  client_id = int(request.POST.get('client_id', ''))
                  try:
                      Client=models.Client.objects.get(client_id=client_id)
                  except ObjectDoesNotExist:
                      Client=''
             Exams=models.Exam.objects.all()

             for Exam in Exams:
                 if str(Exam.exam_id) in request.POST:
                     price = request.POST.get(str(Exam.exam_id), '')
                 if price:

                     try:
                        defined_price=models.ClienExamPrice.objects.get(client_exam_id=Exam,created_for_client=Client)
                        defined_price.price=price
                     except ObjectDoesNotExist:

                         defined_price = models.ClienExamPrice.objects.create(
                              client_exam_id= Exam,
                              created_for_client=Client,
                              price= price
                         )
                     defined_price.save()
                     Client.is_aproved=True
                     Client.save()

             if defined_price:

                         error='We Updated all Exam prices for this Client'
                         Exams=models.Exam.objects.all()
                         return render_to_response('dashboard_screen/update_client_price.html', {
                             'title': 'Update Price Client',
                             'message':error,
                             'client':Client,
                             'exams':Exams,
                             'Lab':Lab,
                         },c)

             else:
                 return render_to_response('dashboard_screen/update_client_price.html', {
                     'message':error,
                     'client':Client,
                     'exams':Exams,
                     'Lab':Lab,
                 }, context_instance=RequestContext(request))




         else:
             if Client:
                 Exams=models.Exam.objects.all()
                 return render_to_response('dashboard_screen/update_client_price.html', {
                     'title': 'All Client',
                     'client':Client,
                     'exams':Exams,
                     'Lab':Lab,
                 },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def edit_client(request,client_id):
     c = RequestContext(request)
     Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
     if request.user.is_authenticated():
         states = models.state.objects.all()
         error=''
         client_id=int(client_id)
         try:
            Client = models.Client.objects.get(client_id=client_id)
         except ObjectDoesNotExist:
             Client=''


         if request.is_ajax() or 'edit_client' in request.POST:

             if 'client_id' in request.POST:
                  client_id = int(request.POST.get('client_id', ''))
                  try:
                      Client=models.Client.objects.get(client_id=client_id)
                  except ObjectDoesNotExist:
                      Client=''

             if 'client_code' in request.POST:
                  client_code = str(request.POST.get('client_code', ''))
                  try:
                      Client2=models.Client.objects.filter(~Q(client_id=Client.client_id)).filter(client_code=client_code)
                  except ObjectDoesNotExist:
                      Client2=''

                  if Client2:
                      error='This client code is already in used, by other Client.'
             else:
                  error='Please fill Mandatory Fields'

             if 'client_attending_physician_name' in request.POST:
                  client_attending_physician_name = str(request.POST.get('client_attending_physician_name', ''))
             else:
                 error='Please fill Mandatory Fields'


             if 'business_UPIN_number' in request.POST:
                  client_UPIN_number = str(request.POST.get('business_UPIN_number', ''))
                  try:
                      Client3=models.Client.objects.filter(~Q(client_id=Client.client_id)).filter(business_UPIN_number=client_UPIN_number)
                  except ObjectDoesNotExist:
                      Client3=''

                  if Client3:
                      error='This UPIN Number is already in use by another Client'
             else:
                 error='Please fill Mandatory Fields'

             if 'client_first_name' in request.POST:
                  client_first_name = str(request.POST.get('client_first_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'client_last_name' in request.POST:
                 client_last_name = str(request.POST.get('client_last_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'client_legal_name' in request.POST:
                 client_legal_name = str(request.POST.get('client_legal_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if not error:
                         Client.first_name=client_first_name
                         Client.last_name=client_last_name
                         Client.business_UPIN_number=client_UPIN_number
                         Client.business_legal_name=client_legal_name
                         Client.attending_physician_name=client_attending_physician_name


                         if 'client_phone' in request.POST:
                             client_phone = str(request.POST.get('client_phone', ''))
                             Client.business_phone=client_phone

                         if 'client_contact_phone' in request.POST:
                             client_contact_phone =str(request.POST.get('client_contact_phone', ''))
                             Client.contact_phone=client_contact_phone

                         if 'client_fax' in request.POST:
                             client_fax = str(request.POST.get('client_fax', ''))
                             Client.business_fax=client_fax

                         if 'client_city' in request.POST:
                             client_city = str(request.POST.get('client_city', ''))
                             Client.business_city =client_city

                         if 'client_zipcode' in request.POST:
                             client_zipcode = str(request.POST.get('client_zipcode', ''))
                             Client.business_zipcode=client_zipcode

                         if 'client_state' in request.POST:
                             client_state = str(request.POST.get('client_state', ''))
                             Client.business_state =client_state

                         if 'client_address' in request.POST:
                             client_address = str(request.POST.get('client_address', ''))
                             Client.business_address =client_address

                         if 'client_address2' in request.POST:
                             client_address2 = str(request.POST.get('client_address2', ''))
                             Client.business_address2 =client_address2

                         if 'e_fax' in request.POST:
                              e_fax = request.POST.get('e_fax', '')
                              e_fax=1
                         else:
                             e_fax=0

                         Client.e_fax=e_fax

                         if 'website' in request.POST:
                              website = str(request.POST.get('website', ''))
                              website=1
                         else:
                             website=0
                         Client.website=website

                         if 'printed' in request.POST:
                              printed = str(request.POST.get('printed', ''))
                              printed=1
                         else:
                             printed=0

                         Client.printed=printed


                         if 'interface' in request.POST:
                              interface = str(request.POST.get('interface', ''))
                              interface=1
                         else:
                             interface=0
                         Client.interface=interface

                         if 'notification' in request.POST:
                             notification = int(request.POST.get('notification', ''))
                             Client.notification= notification

                         Client.save()
                         error='We Update the Client Info Sucesfully'

                         return render_to_response('dashboard_screen/edit_client.html', {
                             'message':error,
                             'Lab':Lab,
                             'states':states,
                             'client':Client,
                         }, context_instance=RequestContext(request))
             else:
                 error='we got a problem'
                 return render_to_response('dashboard_screen/edit_client.html', {
                     'message':error,
                     'client':Client,
                     'Lab':Lab,
                     'states':states,
                 }, context_instance=RequestContext(request))

         else:

             if Client:


                 return render_to_response('dashboard_screen/edit_client.html', {
                     'title': 'Pending Client',
                     'client':Client,
                     'Lab':Lab,
                     'states':states,
                 }, c)
             else:
                 Clients = models.Client.objects.all()
                 Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
                 return render_to_response('dashboard_screen/all_client.html', {
                    'title': 'All Client',
                    'clients':Clients,
                    'Lab':Lab,
             },c)

     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def all_patient(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Patients=models.Patient.objects.all()
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

        # if request.user.

         return render_to_response('dashboard_screen/all_patient.html', {
             'title': 'All Client',
             'Patients':Patients,
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def all_client(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Clients = models.Client.objects.filter(is_aproved=1)
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

        # if request.user.

         return render_to_response('dashboard_screen/all_client.html', {
             'title': 'All Client',
             'clients':Clients,
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def add_client(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         states = models.state.objects.all()
         error=''
         if request.is_ajax() or 'save_client' in request.POST:

             if 'client_code' in request.POST:
                  client_code = str(request.POST.get('client_code', ''))
                  try:
                      Client2=models.Client.objects.get(client_code=client_code)
                  except ObjectDoesNotExist:
                      Client2=''

                  if Client2:
                      error='This client code was previously used, by other Client, Please contact your IT administrator'
             else:
                  error='Please fill Mandatory Fields'



             if 'client_email' in request.POST:
                  client_email = request.POST.get('client_email', '')
                  try:
                      user1=models.AuthUser.objects.get(email=client_email)
                  except ObjectDoesNotExist:
                      user1=''

                  if user1:
                      error='This Email is already in used by other Client.'
             else:
                 error='Please fill Mandatory Fields'

             #if 'client_password' in request.POST:
                 # client_password = str(request.POST.get('client_password', ''))

             if 'client_attending_physician_name' in request.POST:
                  client_attending_physician_name = str(request.POST.get('client_attending_physician_name', ''))
             else:
                 error='Please fill Mandatory Fields'



             if 'client_UPIN_number' in request.POST:
                  client_UPIN_number = str(request.POST.get('client_UPIN_number', ''))
                  try:
                      Client3=models.Client.objects.get(business_UPIN_number=client_UPIN_number)
                  except ObjectDoesNotExist:
                      Client3=''

                  if Client3:
                      error='This UPIN NUmber is already in use by another Client'

             else:
                 error='Please fill Mandatory Fields'

             if 'client_first_name' in request.POST:
                  client_first_name = str(request.POST.get('client_first_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'client_last_name' in request.POST:
                  client_last_name = str(request.POST.get('client_last_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'client_legal_name' in request.POST:
                  client_legal_name = str(request.POST.get('client_legal_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if not error:

                     #Client_User = models.User.objects.create(
                     #     username=client_username,
                     #     email=client_email,
                     #     first_name=client_first_name,
                     #     last_name=client_last_name,
                     #)

                    # Client_User.set_password(client_password)
                     #Client_User.save()


                     Client=models.Client.objects.create(
                             client_code= client_code,
                             business_UPIN_number= client_UPIN_number,
                             business_legal_name =client_legal_name,
                             business_email = client_email,
                     )
                     Client.save()

                     if Client:
                         Client.attending_physician_name=client_attending_physician_name
                         Client.first_name=client_first_name
                         Client.last_name=client_last_name
                         Client.email=client_email
                         if 'client_phone' in request.POST:
                             client_phone = str(request.POST.get('client_phone', ''))
                             Client.business_phone= client_phone

                         if 'client_contact_phone' in request.POST:
                             client_contact_phone = str(request.POST.get('client_contact_phone', ''))
                             Client.contact_phone=client_contact_phone

                         if 'client_fax' in request.POST:
                             client_fax = str(request.POST.get('client_fax', ''))
                             Client.business_fax= client_fax

                         if 'client_city' in request.POST:
                             client_city = str(request.POST.get('client_city', ''))
                             Client.business_city = client_city

                         if 'client_zipcode' in request.POST:
                             client_zipcode = str(request.POST.get('client_zipcode', ''))
                             Client.business_zipcode= client_zipcode

                         if 'client_state' in request.POST:
                             client_state = str(request.POST.get('client_state', ''))
                             Client.business_state = client_state

                         if 'client_address' in request.POST:
                             client_address = str(request.POST.get('client_address', ''))
                             Client.business_address = client_address

                         if 'client_address2' in request.POST:
                             client_address2 = str(request.POST.get('client_address2', ''))
                             Client.business_address2 = client_address2

                         if 'e_fax' in request.POST:
                              e_fax = request.POST.get('e_fax', '')
                              e_fax=1
                         else:
                             e_fax=0

                         Client.e_fax=e_fax

                         if 'website' in request.POST:
                              website = str(request.POST.get('website', ''))
                              website=1
                         else:
                             website=0
                         Client.website=website

                         if 'printed' in request.POST:
                              printed = str(request.POST.get('printed', ''))
                              printed=1
                         else:
                             printed=0

                         Client.printed=printed


                         if 'interface' in request.POST:
                              interface = str(request.POST.get('interface', ''))
                              interface=1
                         else:
                             interface=0
                         Client.interface=interface

                         if 'notification' in request.POST:
                             notification = int(request.POST.get('notification', ''))
                             Client.notification= notification

                         Client.save()
                         error='We save the Client Info Sucesfully'

                         return render_to_response('dashboard_screen/add_client.html', {
                             'message':error,
                             'states':states,
                         }, context_instance=RequestContext(request))
             else:
                 return render_to_response('dashboard_screen/add_client.html', {
                     'message':error,
                     'states':states,
                 }, context_instance=RequestContext(request))

         return render_to_response('dashboard_screen/add_client.html', {
             'title': 'Add Client',
             'states':states,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def edit_patient(request, patient_id=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         states = models.state.objects.all()
         error=''
         if patient_id:
             patient_id=int(patient_id)
         try:
             Patient = models.Patient.objects.get(patient_id=patient_id)
         except ObjectDoesNotExist:
             Patient=''

         Clients=models.Client.objects.filter(is_aproved=1)

         Clients_able_to_work=[]
         for Client in Clients:
             if Client.has_price():
                 Clients_able_to_work.append(Client)

         if request.is_ajax() or 'edit_patient' in request.POST:

             if 'patient_id' in request.POST:
                  patient_id = int(request.POST.get('patient_id', ''))
                  try:
                     Patient = models.Patient.objects.get(patient_id=patient_id)
                  except ObjectDoesNotExist:
                     Patient=''
             if 'patient_client' in request.POST:
                  patient_client = int(request.POST.get('patient_client', ''))
                  try:
                     Client = models.Client.objects.get(client_id=patient_client)
                  except ObjectDoesNotExist:
                     Client=''

             if 'patient_dob' in request.POST:
                 patient_dob = str(request.POST.get('patient_dob', ''))
                 if patient_dob != '':
                    start_d = patient_dob.split('/')
                    y_start= int(start_d[2])
                    m_start= int(start_d[0])
                    d_start= int(start_d[1])
                    patient_dob= date(y_start, m_start, d_start)
             else:
                 error='Please DOB is a Mandatory Field'

             if 'patient_external_id' in request.POST:
                 patient_external_id = str(request.POST.get('patient_external_id', ''))
             else:
                 error='Please External ID is a Mandatory Field'

             if 'patient_last_name' in request.POST:
                 patient_last_name = str(request.POST.get('patient_last_name', ''))

             if 'patient_phone' in request.POST:
                 patient_phone = str(request.POST.get('patient_phone', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'patient_first_name' in request.POST:
                 patient_first_name = str(request.POST.get('patient_first_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'patient_ethnicity' in request.POST:
                 patient_ethnicity = str(request.POST.get('patient_ethnicity', ''))

             if 'patient_gender' in request.POST:
                 patient_gender = str(request.POST.get('patient_gender', ''))

             if 'patient_state' in request.POST:
                 patient_state = str(request.POST.get('patient_state', ''))

             if 'patient_zipcode' in request.POST:
                 patient_zipcode = str(request.POST.get('patient_zipcode', ''))

             if 'patient_address' in request.POST:
                 patient_address = str(request.POST.get('patient_address', ''))

             if 'patient_address2' in request.POST:
                 patient_address2 = str(request.POST.get('patient_address2', ''))

             if 'patient_city' in request.POST:
                 patient_city = str(request.POST.get('patient_city', ''))


             if 'patient_phone' in request.POST:
                 patient_phone = str(request.POST.get('patient_phone', ''))


             if 'patient_ssn' in request.POST:
                 patient_ssn = str(request.POST.get('patient_ssn', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'notification' in request.POST:
                 notification = int(request.POST.get('notification', ''))

             if not error:
                 Patient.patient_client=Client
                 Patient.dob=patient_dob
                 Patient.SSN_number=patient_ssn
                 Patient.first_name=patient_first_name
                 Patient.last_name=patient_last_name
                 Patient.ext_id=patient_external_id
                 Patient.address =patient_address
                 Patient.address2 =patient_address2
                 Patient.city =patient_city
                 Patient.state =patient_state
                 Patient.zipcode=patient_zipcode
                 Patient.phone=patient_phone
                 Patient.gender=patient_gender
                 Patient.ethnicity=patient_ethnicity
                 Patient.notification=notification
                 Patient.save()
                 error="The Patient was Updated sucesfully"
                 return render_to_response('dashboard_screen/edit_patient.html', {
                     'title': 'Add Patient',
                     'message':error,
                     'Patient':Patient,
                     'states':states,
                     'Clients':Clients_able_to_work,
                 },c)
             else:
                 error='Something wrong happended'
                 return render_to_response('dashboard_screen/edit_patient.html', {
                     'title': 'Add Patient',
                     'message':error,
                     'Patient':Patient,
                     'states':states,
                     'Clients':Clients_able_to_work,
                 },c)
         return render_to_response('dashboard_screen/edit_patient.html', {
             'title': 'Edit Patient',
             'message':error,
             'Patient':Patient,
             'states':states,
             'Clients':Clients_able_to_work,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def add_patient(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         states = models.state.objects.all()
         error=''
         Clients=models.Client.objects.filter(is_aproved=1)

         Clients_able_to_work=[]
         for Client in Clients:
             if Client.has_price():
                 Clients_able_to_work.append(Client)

         if request.is_ajax() or 'save_patient' in request.POST:

             if 'patient_dob' in request.POST:
                 patient_dob = str(request.POST.get('patient_dob', ''))
                 if patient_dob != '':
                    start_d = patient_dob.split('/')
                    y_start= int(start_d[2])
                    m_start= int(start_d[0])
                    d_start= int(start_d[1])
                    patient_dob= date(y_start, m_start, d_start)
             else:
                 error='Please DOB is a Mandatory Field'

             if 'patient_client' in request.POST:
                  patient_client = int(request.POST.get('patient_client', ''))
                  try:
                     Client = models.Client.objects.get(client_id=patient_client)
                  except ObjectDoesNotExist:
                     Client=''
                     Clients=models.Client.objects.filter(is_aproved=1)


             if 'patient_external_id' in request.POST:
                 patient_external_id = str(request.POST.get('patient_external_id', ''))
             else:
                 error='Please External ID is a Mandatory Field'

             if 'patient_last_name' in request.POST:
                 patient_last_name = str(request.POST.get('patient_last_name', ''))

             if 'patient_phone' in request.POST:
                 patient_phone = str(request.POST.get('patient_phone', ''))

             else:
                 error='Please fill Mandatory Fields'

             if 'patient_first_name' in request.POST:
                 patient_first_name = str(request.POST.get('patient_first_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'patient_ethnicity' in request.POST:
                 patient_ethnicity = str(request.POST.get('patient_ethnicity', ''))

             if 'patient_gender' in request.POST:
                     patient_gender = str(request.POST.get('patient_gender', ''))

             if 'patient_state' in request.POST:
                 patient_state = str(request.POST.get('patient_state', ''))

             if 'patient_zipcode' in request.POST:
                 patient_zipcode = str(request.POST.get('patient_zipcode', ''))

             if 'patient_address' in request.POST:
                 patient_address = str(request.POST.get('patient_address', ''))

             if 'patient_address2' in request.POST:
                 patient_address2 = str(request.POST.get('patient_address2', ''))

             if 'patient_city' in request.POST:
                 patient_city = str(request.POST.get('patient_city', ''))


             if 'patient_phone' in request.POST:
                 patient_phone = str(request.POST.get('patient_phone', ''))


             if 'patient_ssn' in request.POST:
                 patient_ssn = str(request.POST.get('patient_ssn', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'notification' in request.POST:
                 notification = int(request.POST.get('notification', ''))

             if not error:

                     Patient = models.Patient.objects.create(
                            dob =patient_dob,
                            SSN_number=patient_ssn,
                            first_name=patient_first_name,
                            last_name=patient_last_name,
                     )
                     Patient.patient_client=Client
                     Patient.ext_id=patient_external_id
                     Patient.address =patient_address
                     Patient.address2 =patient_address2
                     Patient.city =patient_city
                     Patient.state =patient_state
                     Patient.zipcode=patient_zipcode
                     Patient.phone=patient_phone
                     Patient.gender=patient_gender
                     Patient.ethnicity=patient_ethnicity
                     Patient.notification=notification
                     Patient.save()
                     error="The Patient was created sucesfully"
                     return render_to_response('dashboard_screen/add_patient.html', {
                         'title': 'Add Patient',
                         'message':error,
                         'states':states,
                     },c)
             else:
                 error='Something wrong happended'
                 return render_to_response('dashboard_screen/add_patient.html', {
                     'title': 'Add Patient',
                     'message':error,
                     'states':states,
                     'Clients':Clients_able_to_work,
                 },c)

         return render_to_response('dashboard_screen/add_patient.html', {
             'title': 'Add Patient',
             'message':error,
             'states':states,
             'Clients':Clients_able_to_work,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def add_exam(request, exam_id=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         if exam_id:
             exam_id=int(exam_id)

         error=''
         Exams=models.Exam.objects.all()
########################################################################################################################
         if request.is_ajax() or 'edit_exam' in request.POST:

             if 'exam_id' in request.POST:
                  exam_id = int(request.POST.get('exam_id', ''))
                  try:
                      Exam=models.Exam.objects.get(exam_id=exam_id)
                  except ObjectDoesNotExist:
                      Exam=''

             if not Exam:
                  error='This Test was previously removed, please contact your IT administrator'

             if 'cpt_name' in request.POST:
                 cpt_name = str(request.POST.get('cpt_name', ''))
             else:
                 error='Please fill Mandatory Fields'

             if cpt_name != Exam.cpt_name:
                 try:
                     Exam2= models.Exam.objects.filter(~Q(exam_id=Exam.exam_id)).filter(cpt_name=cpt_name)
                 except ObjectDoesNotExist:
                     Exam2=''

                 if Exam2:
                     error='This CPT Code is already in used'


             if 'exam_case_type' in request.POST:
                 exam_case_type = request.POST.get('exam_case_type', '')
             else:
                 error='Please fill Mandatory Fields'

             if 'exam_name' in request.POST:
                     exam_name = request.POST.get('exam_name', '')
             else:
                 error='Please fill Mandatory Fields'

             if exam_name != Exam.exam_name:
                 try:
                     Exam2= models.Exam.objects.filter(~Q(exam_id = Exam.exam_id)).filter(exam_name=exam_name)
                 except ObjectDoesNotExist:
                     Exam2=''

                 if Exam2:
                     error='This Test Name is already in used by other Test.'

             if 'test_code' in request.POST:
                 test_code = request.POST.get('test_code', '')

                 if test_code:
                     try:

                         Exam2= models.Exam.objects.filter(~Q(exam_id = Exam.exam_id)).filter(test_code=test_code)
                     except ObjectDoesNotExist:
                         Exam2=''
                     if Exam2:
                         error='This Test Code is already in used'
             else:
                 error='Please fill Mandatory Fields'


             if 'exam_descript' in request.POST:
                 exam_descript = request.POST.get('exam_descript', '')
             else:
                 error='Please fill Mandatory Fields'

             if 'exam_price' in request.POST:
                 exam_price = request.POST.get('exam_price', '')
             else:
                 error='Please fill Mandatory Fields'

             if not error:
                  if Exam:
                          CaseType=models.CaseType.objects.get(case_type_id=exam_case_type)
                          Exam.exam_name = exam_name
                          Exam.test_code=test_code
                          Exam.exam_default_price=exam_price
                          Exam.exam_description=exam_descript
                          Exam.cpt_name=cpt_name
                          Exam.exam_casetype=CaseType
                          Exam.save()
                          error='We have successfully Updated the Test.'
                          Exams=models.Exam.objects.all()
                          casetype=models.CaseType.objects.all()
                          return render_to_response('dashboard_screen/add_exam.html', {
                              'message':error,
                              'exams':Exams,
                              'casetype':casetype,
                          }, context_instance=RequestContext(request))
             else:
                  Exams=models.Exam.objects.all()
                  casetype=models.CaseType.objects.all()
                  return render_to_response('dashboard_screen/add_exam.html', {
                      'message':error,
                      'exams':Exams,
                      'casetype':casetype,
                  }, context_instance=RequestContext(request))
########################################################################################################################
         if request.is_ajax() or 'save_exam' in request.POST:

                 if 'exam_name' in request.POST:
                     exam_name = request.POST.get('exam_name', '')

                     if exam_name:
                         try:
                             Exam= models.Exam.objects.get(exam_name=exam_name)
                         except ObjectDoesNotExist:
                             Exam=''
                         if Exam:
                             error='This Test Name is already in used'
                 else:
                     error='Please fill Mandatory Fields'

                 if 'test_code' in request.POST:
                     test_code = request.POST.get('test_code', '')

                     if test_code:
                         try:
                             Exam= models.Exam.objects.get(test_code=test_code)
                         except ObjectDoesNotExist:
                             Exam=''
                         if Exam:
                             error='This Test Code is already in used'
                 else:
                     error='Please fill Mandatory Fields'

                 if 'cpt_name' in request.POST:
                     cpt_name = request.POST.get('cpt_name', '')

                     if cpt_name:
                         try:
                             Exam= models.Exam.objects.get(cpt_name=cpt_name)
                         except ObjectDoesNotExist:
                             Exam=''

                         if Exam:
                             error='This CPT Code is already in used'
                 else:
                     error='Please fill Mandatory Fields'

                 if 'exam_case_type' in request.POST:
                     exam_case_type = request.POST.get('exam_case_type', '')
                 else:
                     error='Please fill Mandatory Fields'

                 if 'exam_descript' in request.POST:
                     exam_descript = request.POST.get('exam_descript', '')
                 else:
                     error='Please fill Mandatory Fields'

                 if 'exam_price' in request.POST:
                     exam_price = request.POST.get('exam_price', '')
                 else:
                     error='Please fill Mandatory Fields'

                 if not error:
                     CaseType=models.CaseType.objects.get(case_type_id=exam_case_type)
                     Exam=models.Exam.objects.create(
                         exam_name = exam_name,
                         exam_description= exam_descript,
                         test_code=test_code,
                         exam_default_price=exam_price,
                         cpt_name=cpt_name,
                         exam_casetype=CaseType,
                     )
                     Exam.save()
                     Exams=models.Exam.objects.all()
                     error='We have successfully saved the new Test.'
                 casetype=models.CaseType.objects.all()
                 return render_to_response('dashboard_screen/add_exam.html', {
                    'message':error,
                    'exams':Exams,
                    'casetype':casetype,
                 }, context_instance=RequestContext(request))
         else:
             if exam_id:
                 try:
                      Exam=models.Exam.objects.get(exam_id=exam_id)
                 except ObjectDoesNotExist:
                      Exam=''
             else:
                 Exam=''
             casetype=models.CaseType.objects.all()
             return render_to_response('dashboard_screen/add_exam.html', {
                 'title': 'Add Exam',
                 'message':error,
                 'exams':Exams,
                 'exam':Exam,
                 'casetype':casetype,
             },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def del_exam(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         states = models.state.objects.all()

         return render_to_response('dashboard_screen/del_exam.html', {
             'title': 'List Exams',
             'states':states,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def list_result(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         states = models.state.objects.all()

        # if request.user.

         return render_to_response('dashboard_screen/list_result.html', {
             'title': 'List Result',
             'states':states,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def add_result(request, code_id=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         if code_id:
             code_id=int(code_id)

         error=''
######################################################################################################################
         if request.is_ajax() or 'edit_code' in request.POST:

             if 'code_id' in request.POST:
                code_id = int(request.POST.get('code_id', ''))
                try:
                      Code=models.Result_code.objects.get(code_id=code_id)
                except ObjectDoesNotExist:
                      Code=''

             if not Code:
                 error='This Code was previously removed, please contact your IT administrator'

             if 'code_name' in request.POST:
                 code_name =str(request.POST.get('code_name',''))
             else:
                 error='Please fill Mandatory Fields'



             if code_name != Code.code_name:
                 try:
                     Code2= models.Result_code.objects.filter(~Q(code_id=Code.code_id)).filter(code_name=Code.code_name)

                 except ObjectDoesNotExist:
                     Code2=''

                 if Code2:
                     error='This Code Name is already in used by other Result Code.'


             if 'code_descript' in request.POST:
                 code_descript =str(request.POST.get('code_descript',''))
             else:
                 error='Please fill Mandatory Fields'

             if 'code_case_type' in request.POST:
                 code_case_type = int(request.POST.get('code_case_type', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'code_result_area' in request.POST:
                     code_result_area = int(request.POST.get('code_result_area', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'code_case_type' in request.POST:
                 code_case_type = int(request.POST.get('code_case_type', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'result_type' in request.POST:
                 result_type = int(request.POST.get('result_type', ''))
             else:
                 error='Please fill Mandatory Fields'

             if 'code_result_subarea' in request.POST:
                     code_result_subarea = int(request.POST.get('code_result_subarea', ''))
             else:
                 error='Please fill Mandatory Fields'

             if not error:

                  if Code:

                          CaseType=models.CaseType.objects.get(case_type_id=code_case_type)
                          ResultCat=models.ResultCategory.objects.get(cat_id=code_result_area)
                          ResultSubCat=models.ResultSubCategory.objects.get(subcat_id=code_result_subarea)

                          Code.code_name =code_name
                          Code.code_description=code_descript

                          Code.code_result_area=ResultCat
                          Code.code_casetype_result=CaseType
                          Code.code_result_subcat=ResultSubCat
                          Code.code_result_type=result_type

                          Code.save()
                          error='We have successfully Updated the Code Info.'

                          categories=models.ResultCategory.objects.all()
                          casetype=models.CaseType.objects.all()
                          codes=models.Result_code.objects.all()
                          resultsubcategory=models.ResultSubCategory.objects.all()

                          return render_to_response('dashboard_screen/add_result.html', {
                               'message':error,
                               'categories':categories,
                               'casetype':casetype,
                               'codes':codes,
                               'resultsubcategory':resultsubcategory,
                          }, context_instance=RequestContext(request))
             else:
                 categories=models.ResultCategory.objects.all()
                 casetype=models.CaseType.objects.all()
                 codes=models.Result_code.objects.all()
                 resultsubcategory=models.ResultSubCategory.objects.all()
                 return render_to_response('dashboard_screen/add_result.html', {
                       'message':error,
                       'categories':categories,
                       'casetype':casetype,
                       'codes':codes,
                       'resultsubcategory':resultsubcategory,
                 }, context_instance=RequestContext(request))


######################################################################################################################
         if request.is_ajax() or 'save_code' in request.POST:

                 if 'code_name' in request.POST:
                     code_name =str(request.POST.get('code_name', ''))
                     if code_name:
                         try:
                             code= models.Result_code.objects.get(code_name=code_name)
                             error='This Code Name is already in used'
                         except ObjectDoesNotExist:
                             code=''
                 else:
                     error='Please fill Mandatory Fields'

                 if 'code_descript' in request.POST:
                     code_descript = str(request.POST.get('code_descript', ''))
                 else:
                     error='Please fill Mandatory Fields'


                 if 'code_result_area' in request.POST:
                     code_result_area = int(request.POST.get('code_result_area', ''))
                 else:
                     error='Please fill Mandatory Fields'

                 if 'code_case_type' in request.POST:
                     code_case_type = int(request.POST.get('code_case_type', ''))
                 else:
                     error='Please fill Mandatory Fields'

                 if 'result_type' in request.POST:
                     result_type = int(request.POST.get('result_type', ''))
                 else:
                     error='Please fill Mandatory Fields'


                 if 'code_result_subarea' in request.POST:
                     code_result_subarea = int(request.POST.get('code_result_subarea', ''))
                 else:
                     error='Please fill Mandatory Fields'

                 if not error:
                     CaseType=models.CaseType.objects.get(case_type_id=code_case_type)
                     ResultCat=models.ResultCategory.objects.get(cat_id=code_result_area)
                     ResultSubCat=models.ResultSubCategory.objects.get(subcat_id=code_result_subarea)

                     code=models.Result_code.objects.create(
                            code_name = code_name,
                            code_description= code_descript,
                            code_result_area=ResultCat,
                            code_casetype_result=CaseType,
                            code_result_type=result_type,
                            code_result_subcat=ResultSubCat,
                     )
                     code.save()
                     error='We have successfully saved the new code.'

                 categories=models.ResultCategory.objects.all()
                 casetype=models.CaseType.objects.all()
                 codes=models.Result_code.objects.all()
                 resultsubcategory=models.ResultSubCategory.objects.all()

                 return render_to_response('dashboard_screen/add_result.html', {
                     'message':error,
                     'categories':categories,
                     'casetype':casetype,
                     'resultsubcategory':resultsubcategory,
                     'codes':codes,
                 }, context_instance=RequestContext(request))


         if code_id:
             try:
                Code=models.Result_code.objects.get(code_id=code_id)
             except ObjectDoesNotExist:
                Code=''
         else:
             Code=''


         categories=models.ResultCategory.objects.all()
         CaseType=models.CaseType.objects.all()
         Codes=models.Result_code.objects.all()
         resultsubcategory=models.ResultSubCategory.objects.all()
         return render_to_response('dashboard_screen/add_result.html', {
             'title': 'Add Result',
             'message':error,
             'categories':categories,
             'codes':Codes,
             'code':Code,
             'casetype':CaseType,
             'resultsubcategory':resultsubcategory,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)


def report(request):
     c = RequestContext(request)
     if request.user.is_authenticated():

         return render_to_response('dashboard_screen/report.html', {
               'title': 'DashBoard',
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def dashboard(request):
     c = RequestContext(request)
     if request.user.is_authenticated():

         return render_to_response('dashboard_screen/dashboard.html', {
             'title': 'DashBoard',
             'pagetype':11,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def forgot_passwd(request):
     c = RequestContext(request)
     return render_to_response('dashboard_screen/forgot_passwd.html', {
           'title': 'Forgot Passwd',
     },c)

def login_user(request):
    c = RequestContext(request)

    if not request.user.is_authenticated():
        if request.method == "POST":
             username = str(request.POST['username'])
             password = str(request.POST['password'])

             user = authenticate(username=username, password=password)
             if user is not None:
                if user.is_active:
                    login(request, user)

                    return render_to_response('dashboard_screen/dashboard.html', {
                       'title': 'DashBoard',
                       'pagetype':11,
                     },c)
                else:
                    message= 'The User and password is valid, but the account has been disabled!'
                    return render_to_response('dashboard_screen/login_user.html', {
                        'title': 'Login',
                        'message':message,
                        'pagetype':11,
                    },c)
             else:
                message='The username and password were incorrect.'
                return render_to_response('dashboard_screen/login_user.html', {
                    'title': ' Login',
                    'message': message,
                    'pagetype':11,
                },c)
        else:

             return render_to_response('dashboard_screen/login_user.html', {
                 'title': 'Login',
                 'pagetype':11,
             },c)
    else:

         return render_to_response('dashboard_screen/dashboard.html', {
            'title': 'DashBoard',
            'pagetype':11,
         },c)

def signup(request):
    c = RequestContext(request)

    error=''

    if request.method == "POST":
         username = str(request.POST['username'])
         email = str(request.POST['email'])
         password1 = str(request.POST['password1'])
         password2 = str(request.POST['password2'])

         try:
             query= models.User.objects.get(username=username)

         except ObjectDoesNotExist:
             query=''

         try:
             query2= models.User.objects.get(email=email)

         except ObjectDoesNotExist:
             query2=''

         if query:
             error='This Username is already in use.'

         if query2:
             error='This Email is already in use.'

         if password1 != password2:
             error='Password are not Identical'

         if not 'term' in request.POST:
             error='You must accept term and Conditions.'

         if not error:

             user = models.User.objects.create(
                username=username,
                email=email,
                )

             user.set_password(password1)
             user.save()

             new_user = authenticate(username=username,password=password1)

             login(request, new_user)

             message='The User was created successfully'

            # html_body= notifications.html_header + notifications.html_welcome_users + notifications.html_footer
             #user_fullname= request.user.username
            # link_to_activate='https://myairdo.com/home/activate/'+ str(request.user.email)


            # body = Template(html_body).safe_substitute(new_user=user_fullname)
            # body = Template(body).safe_substitute(link=link_to_activate)

           #  sg = sendgrid.SendGridClient(settings.SENDRID_API_KEY)
           #  msg = sendgrid.Mail()
           #  msg.set_from('no_reply@myairdo.com')
           #  msg.set_from_name(settings.FROM_AIRDO)
           #  msg.add_to(request.user.email)

           #  msg.set_subject('Welcome to Myairdo.com')
           #  msg.set_html(body)
           #  status, msg2= sg.send(msg)

         else:
             message=error
             return render_to_response('dashboard_screen/signup.html', {
                  'title': 'Sign Up',
                  'pagetype':11,
                  'message':message,
             },c)
    else:
        return render_to_response('dashboard_screen/signup.html', {
              'title': 'Sign Up',
              'pagetype':11,
        },c)
def logout_user(request):
    c = RequestContext(request)
    logout(request)
    return render_to_response('dashboard_screen/login_user.html', {
        'title': 'Login',
        'pagetype':11,
     },c)

def export_pdf(request):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

         if request.is_ajax() or 'export' in request.POST:


             if 'entry_id' in request.POST:
                 entry_id =request.POST.get('entry_id', '')
                 if entry_id:
                     try:
                          Entry = models.Entry.objects.get(entry_id=int(entry_id))
                     except ObjectDoesNotExist:
                          Entry=''


             html_body= notifications.fullfilldoc(Entry.entry_id)


             config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
             pdfkit.from_string(html_body, 'demo.pdf', configuration=config)
             pdf =''

             return render_to_response('dashboard_screen/view_pdf.html', {
                       'Entry':Entry,
                       'Lab':Lab,
                       'pdf':pdf,
                 }, context_instance=RequestContext(request))
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def toPDF(request, entry_id=None, accession_id=None):
    c = RequestContext(request)
    Results=models.Result_code.objects.all()
    ResultCat_specimen=models.ResultCategory.objects.get(cat_id=1)
    ResultCat_interpretation=models.ResultCategory.objects.get(cat_id=2)
    ResultCat_additional=models.ResultCategory.objects.get(cat_id=3)
    ResultCat_hormonal=models.ResultCategory.objects.get(cat_id=4)
    no_gyn_specimen_sources=models.Non_GYN_Specimen_Sources.objects.all()

    Results_in_specimen=models.Result_code.objects.filter(code_result_area=ResultCat_specimen)
    Results_in_interpretation=models.Result_code.objects.filter(code_result_area=ResultCat_interpretation)
    Results_in_additional=models.Result_code.objects.filter(code_result_area=ResultCat_additional)
    Results_in_hormonal=models.Result_code.objects.filter(code_result_area=ResultCat_hormonal)

    Result_area=models.ResultCategory.objects.all()

    Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
    if entry_id:
          entry_id=int(entry_id)
    if accession_id:
        accesion_id=int(accession_id)
    try:
        Entry = models.Entry.objects.get(entry_id=entry_id)
    except ObjectDoesNotExist:
        Entry=''
    try:
        Accession= models.Accession.objects.get(id=accession_id)
    except ObjectDoesNotExist:
        Accession=''



    return render_to_response('dashboard_screen/toPDF.html', {
         'title': 'View Details in PDF',
         'Entry':Entry,
         'Lab':Lab,
         'Results':Results,
         'Result_area':Result_area,
         'Results_in_specimen':Results_in_specimen,
         'Results_in_additional':Results_in_additional,
         'Results_in_interpretation':Results_in_interpretation,
         'Results_in_hormonal':Results_in_hormonal,
         'no_gyn_specimen_sources':no_gyn_specimen_sources,
         'Accession':Accession,
         },c)


def view_pdf(request, entry_id=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Results=models.Result_code.objects.all()
         ResultCat_specimen=models.ResultCategory.objects.get(cat_id=1)
         ResultCat_interpretation=models.ResultCategory.objects.get(cat_id=2)
         ResultCat_additional=models.ResultCategory.objects.get(cat_id=3)
         ResultCat_hormonal=models.ResultCategory.objects.get(cat_id=4)
         no_gyn_specimen_sources=models.Non_GYN_Specimen_Sources.objects.all()

         Results_in_specimen=models.Result_code.objects.filter(code_result_area=ResultCat_specimen)
         Results_in_interpretation=models.Result_code.objects.filter(code_result_area=ResultCat_interpretation)
         Results_in_additional=models.Result_code.objects.filter(code_result_area=ResultCat_additional)
         Results_in_hormonal=models.Result_code.objects.filter(code_result_area=ResultCat_hormonal)

         Result_area=models.ResultCategory.objects.all()

         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)
         if entry_id:
              entry_id=int(entry_id)
         try:
            Entry = models.Entry.objects.get(entry_id=entry_id)
         except ObjectDoesNotExist:
            Entry=''

         if request.is_ajax() or 'export' in request.POST:

             if 'entry_id' in request.POST:
                 entry_id =request.POST.get('entry_id', '')
                 if entry_id:
                     try:
                          Entry = models.Entry.objects.get(entry_id=int(entry_id))
                     except ObjectDoesNotExist:
                          Entry=''


             if 'accesion_id' in request.POST:
                 accesion_id =request.POST.get('accesion_id', '')

             url='http://127.0.0.1:8000/dashboard/toPDF/'+str(Entry.entry_id)+'/'+str(accesion_id)+'/'

             config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
             options = {
                'page-size': 'Letter',
                'margin-top': '0.75in',
                'margin-right': '0.75in',
                'margin-bottom': '0.75in',
                'margin-left': '0.75in',
                'encoding': "UTF-8",
                'no-outline': None
            }

             directory='media/entries/'+str(Entry.entry_id)
             if not os.path.exists(directory):
                os.makedirs(directory)
             filename=directory+'/'+str(Entry.lab_id)+'.pdf'
             css='static/dashboard/css/style.css'
             path=filename
             Entry.entry_report=''

             from django.core.files.base import File as DjangoFile
             if not os.path.exists(path):
                 pdfkit.from_url(url, path, configuration=config,options=options)
                 Entry.entry_report.name=path
             else:
                 os.remove(path)
                 pdfkit.from_url(url, path, configuration=config, options=options)
                 Entry.entry_report.name=path

             Entry.save()


             with open(str(Entry.entry_report), 'rb') as pdf:
                 response = HttpResponse(pdf.read(),content_type='application/pdf')
                 response["Cache-Control"] = "max-age=0"
                 response["Accept-Ranges"] = "none"
                 response['Content-Disposition'] = 'attachment; filename='+str(Entry.lab_id)+'.pdf'


             return response

         return render_to_response('dashboard_screen/view_pdf.html', {
             'title': 'View Details in PDF',
             'Entry':Entry,
             'Lab':Lab,
             'Results':Results,
             'Result_area':Result_area,
             'Results_in_specimen':Results_in_specimen,
             'Results_in_additional':Results_in_additional,
             'Results_in_interpretation':Results_in_interpretation,
             'Results_in_hormonal':Results_in_hormonal,
             'no_gyn_specimen_sources':no_gyn_specimen_sources,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def billing(request, month=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

         if month:
             m_start=int(month)
             start_date= date.today()
             y_start=start_date.year
             d_start=1
             d_end= calendar.monthrange(y_start,m_start)[1]
             month=m_start
             start_date= date(y_start, m_start, d_start)
             end_date = date(y_start, m_start, d_end)
             date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
             start_date = date_with_time.replace(hour=00, minute=00)
             date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
             end_date = date_with_time2.replace(hour=23, minute=59)

         else:
             start_date= date.today()
             d_start=1
             y_start=start_date.year
             m_start=start_date.month
             d_end= calendar.monthrange(y_start,m_start)[1]
             month=start_date.month
             start_date= date(y_start, m_start, d_start)
             end_date = date(y_start, m_start, d_end)
             date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
             start_date = date_with_time.replace(hour=00, minute=00)
             date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
             end_date = date_with_time2.replace(hour=23, minute=59)


         Clients=[]
         Clients1 = models.Client.objects.filter(is_aproved=1)
         for Client in Clients1:
             client_patient_list= models.Patient.objects.filter(patient_client=Client)
             for Patient in client_patient_list:
                 try:
                     Entries=models.Entry.objects.filter(patient=Patient, initial_info=1, created_date__range=(start_date,end_date))
                 except ObjectDoesNotExist:
                     Entries=''

                 if Entries.count() > 0:
                     Clients.append(Client)
         return render_to_response('dashboard_screen/billing.html', {
             'title': 'All Client',
             'clients':Clients,
             'month':month,
             'Lab':Lab,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
def invoicetoPDF(request, client_id=None, month=None, year=None):
     c = RequestContext(request)
     Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

     if month:
         m_start=int(month)
         start_date= date.today()
         y_start=start_date.year
         d_start=1
         month=m_start
         d_end= calendar.monthrange(y_start,m_start)[1]
         start_date1= date(y_start, m_start, d_start)
         end_date1 = date(y_start, m_start, d_end)
         date_with_time = datetime(year=start_date1.year, month=start_date1.month, day=start_date1.day)
         start_date = date_with_time.replace(hour=00, minute=00)
         date_with_time2 = datetime(year=end_date1.year, month=end_date1.month, day=end_date1.day)
         end_date = date_with_time2.replace(hour=23, minute=59)
     else:
         start_date= date.today()
         d_start=1
         y_start=start_date.year
         m_start=start_date.month
         month=m_start
         d_end= calendar.monthrange(y_start,m_start)[1]
         start_date1= date(y_start, m_start, d_start)
         end_date1 = date(y_start, m_start, d_end)
         date_with_time = datetime(year=start_date1.year, month=start_date1.month, day=start_date1.day)
         start_date = date_with_time.replace(hour=00, minute=00)
         date_with_time2 = datetime(year=end_date1.year, month=end_date1.month, day=end_date1.day)
         end_date = date_with_time2.replace(hour=23, minute=59)

     if client_id:
         client_id=int(client_id)
         try:
            Client = models.Client.objects.get(client_id=client_id)
         except ObjectDoesNotExist:
            Client=''
     else:
         Client=''

     Entries2=[]
     arrEntry=[]
     Total=0
     if Client:
         client_patient_list= models.Patient.objects.filter(patient_client=Client)
         for Patient in client_patient_list:
             try:
                 Entries=models.Entry.objects.filter(patient=Patient, initial_info=1, created_date__range=(start_date,end_date))
             except ObjectDoesNotExist:
                 Entries=''

             if Entries:
                 for Entry in Entries:
                    Entries2.append(Entry)
     if Entries2:
         for Entry in Entries2:
             id=Entry.entry_id
             Entry.updated_price_per_exam()
             price=Entry.price_total()
             Total=Total + price


     return render_to_response('dashboard_screen/invoicetoPDF.html', {
         'title': 'View Invoice',
         'Client':Client,
         'Entries':Entries2,
         'month':month,
         'Lab':Lab,
         'Total':Total,
         'start_date':start_date1,
         'end_date':end_date1

         },c)

def invoice(request, client_id=None, month=None, year=None):
     c = RequestContext(request)
     if request.user.is_authenticated():
         Lab=models.Lab.objects.get(lab_id=settings.LAB_ID)

         if request.is_ajax() or 'generate_invoice' in request.POST:

             if 'month' in request.POST:
                 month =request.POST.get('month', '')

             if 'client_id' in request.POST:
                 client_id =int(request.POST.get('client_id', ''))
                 Client = models.Client.objects.get(client_id=client_id)

             url='http://127.0.0.1:8000/dashboard/invoicetoPDF/'+str(Client.client_id)+'/'+str(month)+'/'

             config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
             options = {
                'page-size': 'Letter',
                'margin-top': '0.75in',
                'margin-right': '0.75in',
                'margin-bottom': '0.75in',
                'margin-left': '0.75in',
                'encoding': "UTF-8",
                'no-outline': None
            }
             directory='media/clients/'+str(Client.client_id)
             if not os.path.exists(directory):
                os.makedirs(directory)

             directory2='media/clients/'+str(Client.client_id)+'/'+str(month)
             if not os.path.exists(directory2):
                os.makedirs(directory2)

             filename=directory2+'/'+str(month)+'.pdf'
             css='static/dashboard/css/style.css'
             path=filename
             # replace existing invoice or create the new one.
             try:
                 Inv=models.ClientInvoices.objects.get(for_month=month,created_for=Client)
             except ObjectDoesNotExist:
                 Inv=models.ClientInvoices.objects.create(
                     for_month=month,
                     created_for=Client,
                 )
             from django.core.files.base import File as DjangoFile
             if not os.path.exists(path):
                 pdfkit.from_url(url, path, configuration=config,options=options)
                 Inv.invoice=path
             else:
                 os.remove(path)
                 pdfkit.from_url(url, path, configuration=config, options=options)
                 Inv.invoice=path

             Inv.save()
             with open(str(Inv.invoice), 'rb') as pdf:
                 response = HttpResponse(pdf.read(),content_type='application/pdf')
                 response["Cache-Control"] = "max-age=0"
                 response["Accept-Ranges"] = "none"
                 response['Content-Disposition'] = 'attachment; filename='+str(Inv.invoice)+'.pdf'


             return response


         if month:
             m_start=int(month)
             start_date= date.today()
             y_start=start_date.year
             d_start=1
             month=m_start
             d_end= calendar.monthrange(y_start,m_start)[1]
             start_date= date(y_start, m_start, d_start)
             end_date = date(y_start, m_start, d_end)
             date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
             start_date = date_with_time.replace(hour=00, minute=00)
             date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
             end_date = date_with_time2.replace(hour=23, minute=59)

         else:
             start_date= date.today()
             d_start=1
             y_start=start_date.year
             m_start=start_date.month
             month=m_start
             d_end= calendar.monthrange(y_start,m_start)[1]
             start_date= date(y_start, m_start, d_start)
             end_date = date(y_start, m_start, d_end)
             date_with_time = datetime(year=start_date.year, month=start_date.month, day=start_date.day)
             start_date = date_with_time.replace(hour=00, minute=00)
             date_with_time2 = datetime(year=end_date.year, month=end_date.month, day=end_date.day)
             end_date = date_with_time2.replace(hour=23, minute=59)

         if client_id:
             client_id=int(client_id)
             try:
                Client = models.Client.objects.get(client_id=client_id)
             except ObjectDoesNotExist:
                Client=''
         else:
             Client=''

         Entries2=[]
         arrEntry=[]
         Total=0
         if Client:
             client_patient_list= models.Patient.objects.filter(patient_client=Client)
             for Patient in client_patient_list:
                 try:
                     Entries=models.Entry.objects.filter(patient=Patient, initial_info=1, created_date__range=(start_date,end_date))
                 except ObjectDoesNotExist:
                     Entries=''

                 if Entries:
                     for Entry in Entries:
                        Entries2.append(Entry)
         if Entries2:
             for Entry in Entries2:
                 id=Entry.entry_id
                 Entry.updated_price_per_exam()
                 price=Entry.price_total()
                 Total=Total + price


         return render_to_response('dashboard_screen/invoice.html', {
             'title': 'View Invoice',
             'Client':Client,
             'Entries':Entries2,
             'month':month,
             'Lab':Lab,
             'Total':Total,

             },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def view_detail(request, entry_id):
     c = RequestContext(request)
     if request.user.is_authenticated():
         entry_id=int(entry_id)
         try:
            Entry = models.Entry.objects.get(entry_id=entry_id)
         except ObjectDoesNotExist:
            Entry=''
         no_gyn_specimen_sources=models.Non_GYN_Specimen_Sources.objects.all()


         return render_to_response('dashboard_screen/view_detail.html', {
             'title': 'View Details',
             'Entry':Entry,
             'no_gyn_specimen_sources':no_gyn_specimen_sources,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)

def enter_result(request,entry_id):
     c = RequestContext(request)
     if request.user.is_authenticated():
         entry_id=int(entry_id)
         try:
            Entry = models.Entry.objects.get(entry_id=entry_id)
         except ObjectDoesNotExist:
            Entry=''

         Results=models.Result_code.objects.all()
         ResultCat_specimen=models.ResultCategory.objects.get(cat_id=1)
         ResultCat_interpretation=models.ResultCategory.objects.get(cat_id=2)
         ResultCat_additional=models.ResultCategory.objects.get(cat_id=3)
         ResultCat_hormonal=models.ResultCategory.objects.get(cat_id=4)
         no_gyn_specimen_sources=models.Non_GYN_Specimen_Sources.objects.all()

         Results_in_specimen=models.Result_code.objects.filter(code_result_area=ResultCat_specimen)
         Results_in_interpretation=models.Result_code.objects.filter(code_result_area=ResultCat_interpretation)
         Results_in_additional=models.Result_code.objects.filter(code_result_area=ResultCat_additional)
         Results_in_hormonal=models.Result_code.objects.filter(code_result_area=ResultCat_hormonal)

         CaseType=models.CaseType.objects.get(case_type_id=3)

         result_in_molecular=models.Result_code.objects.filter(code_result_area=ResultCat_interpretation,code_casetype_result=CaseType )


         Result_area=models.ResultCategory.objects.all()


         if request.method == "POST":

             if 'save_gyn_result' in request.POST:

                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''

                     if 'exam_id' in request.POST:
                         exam_id =int(request.POST.get('exam_id', ''))
                         Exam=models.Exam.objects.get(exam_id=exam_id)

                     if request.POST.getlist('specimen[]'):
                         result_specimen = request.POST.getlist('specimen[]')
                     else:
                         result_specimen=''

                     if request.POST.getlist('additional[]'):
                        result_additional = request.POST.getlist('additional[]')
                     else:
                         result_additional=''

                     if request.POST.getlist('interpretation[]'):
                        result_interpretation = request.POST.getlist('interpretation[]')
                     else:
                         result_interpretation=''

                     if request.POST.getlist('hormonal[]'):
                        result_hormonal = request.POST.getlist('hormonal[]')
                     else:
                         result_hormonal=''
                     Acc=''
                     if Entry:
                         all_acc=Entry.accession_number.all()

                         if all_acc:
                             for acc in all_acc:
                                 if acc.exam_in.exam_id == Exam.exam_id:
                                     Acc=acc

                     if Acc:

                         if 'GYN_result_photo' in request.FILES:
                            Acc.GYN_result_photo= request.FILES['GYN_result_photo']

                         if 'GYN_result_comment' in request.POST:
                            Acc.GYN_result_comment=request.POST.get('GYN_result_comment', '')

                         if 'GYN_result_caption' in request.POST:
                             Acc.GYN_result_caption=request.POST.get('GYN_result_caption', '')

                         if result_interpretation:
                             old_result=Acc.result_in_interpretation.all()
                             for result in old_result:
                                 res=models.Result_code.objects.get(code_id=result.code_id)
                                 if res:
                                     Acc.result_in_interpretation.remove(res)

                             Acc.save()

                         if result_interpretation:
                             for interpretation in result_interpretation:
                                 Result=models.Result_code.objects.get(code_id=interpretation)
                                 Result.interpretation.add(Acc)
                                 if Result.code_result_type:
                                     Acc.pathology_queve=True

                         if result_hormonal:
                             old_result=Acc.result_in_hormonal.all()
                             for result in old_result:
                                 res=models.Result_code.objects.get(code_id=result.code_id)
                                 if res:
                                     Acc.result_in_hormonal.remove(res)
                             Acc.save()

                         if result_hormonal:
                             for hormonal in result_hormonal:
                                 Result=models.Result_code.objects.get(code_id=hormonal)
                                 Result.hormonal.add(Acc)
                                 if Result.code_result_type:
                                     Acc.pathology_queve=True

                         if result_additional:
                             old_result=Acc.result_in_additional.all()
                             for result in old_result:
                                 res=models.Result_code.objects.get(code_id=result.code_id)
                                 if res:
                                     Acc.result_in_additional.remove(res)
                             Acc.save()

                         if result_additional:
                             for additional in result_additional:
                                 Result=models.Result_code.objects.get(code_id=additional)
                                 Result.additional.add(Acc)
                                 if Result.code_result_type:
                                     Acc.pathology_queve=True

                         if result_specimen:
                             old_result=Acc.result_in_speciment.all()
                             for result in old_result:
                                 res=models.Result_code.objects.get(code_id=result.code_id)
                                 if res:
                                     Acc.result_in_speciment.remove(res)
                             Acc.save()
                         if result_specimen:
                             for speciment in result_specimen:
                                 Result=models.Result_code.objects.get(code_id=speciment)
                                 Result.speciment.add(Acc)
                                 if Result.code_result_type:
                                     Acc.pathology_queve=True

                         Acc.GYN_completed=1
                         today=date.today()
                         Acc.completed_date=today
                         Acc.save()
                         Entry.save()


                    # {% for access in Entry.accession_number.all %} {% if case.exam_id == access.exam_in.exam_id %}{{ access.accession_number }} {% endif %}{% endfor %}

                     return render_to_response('dashboard_screen/enter_result.html', {
                         'title': 'Enter Result',
                         'Entry':Entry,
                         'Results':Results,
                         'Result_area':Result_area,
                         'result_list_value':Acc,
                         'Results_in_specimen':Results_in_specimen,
                         'Results_in_additional':Results_in_additional,
                         'Results_in_interpretation':Results_in_interpretation,
                         'Results_in_hormonal':Results_in_hormonal,
                         'no_gyn_specimen_sources':no_gyn_specimen_sources,
                         'result_in_molecular':result_in_molecular,

                     },c)

             if 'save_non_gyn_result' in request.POST:
                 Acc=''
                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''

                     if 'exam_id' in request.POST:
                         exam_id =int(request.POST.get('exam_id', ''))
                         Exam=models.Exam.objects.get(exam_id=exam_id)

                     if Entry:
                         all_acc=Entry.accession_number.all()
                         if all_acc:
                             for acc in all_acc:
                                 if acc.exam_in.exam_id == Exam.exam_id:
                                     Acc=acc

                         if Acc:
                             if 'Non_GYN_result_photo' in request.FILES:
                                Acc.Non_GYN_result_photo= request.FILES['Non_GYN_result_photo']

                             if 'Non_GYN_result_speciment_received' in request.POST:
                                Acc.Non_GYN_result_speciment_received=str(request.POST.get('Non_GYN_result_speciment_received', ''))
                             if 'Non_GYN_result_clinical_data' in request.POST:
                                Acc.Non_GYN_result_clinical_data=str(request.POST.get('Non_GYN_result_clinical_data', ''))
                             if 'Non_GYN_result_gross_description' in request.POST:
                                Acc.Non_GYN_result_gross_description=str(request.POST.get('Non_GYN_result_gross_description', ''))
                             if 'Non_GYN_result_diagnosis' in request.POST:
                                Acc.Non_GYN_result_diagnosis=str(request.POST.get('Non_GYN_result_diagnosis', ''))
                             if 'Non_GYN_result_comment' in request.POST:
                                Acc.Non_GYN_result_comment=str(request.POST.get('Non_GYN_result_comment', ''))
                             if 'Non_GYN_result_caption' in request.POST:
                                Acc.Non_GYN_result_caption=str(request.POST.get('Non_GYN_result_caption', ''))
                             Acc.Non_gyn_completed=1
                             Acc.completed_date=date.today()
                             Acc.save()
                             return render_to_response('dashboard_screen/enter_result.html', {
                                 'title': 'Enter Result',
                                 'Entry':Entry,
                                 'Results':Results,
                                 'Result_area':Result_area,
                                 'result_list_value':Acc,
                                 'Results_in_specimen':Results_in_specimen,
                                 'Results_in_additional':Results_in_additional,
                                 'Results_in_interpretation':Results_in_interpretation,
                                 'Results_in_hormonal':Results_in_hormonal,
                                 'no_gyn_specimen_sources':no_gyn_specimen_sources,
                                 'result_in_molecular':result_in_molecular,

                             },c)

             if 'save_mp_result' in request.POST:
                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''

                     if 'exam_id' in request.POST:
                         exam_id =int(request.POST.get('exam_id', ''))
                         Exam=models.Exam.objects.get(exam_id=exam_id)
                 Acc=''
                 if Entry:
                     all_acc=Entry.accession_number.all()
                     if all_acc:
                         for acc in all_acc:
                             if acc.exam_in.exam_id == Exam.exam_id:
                                 Acc=acc

                 if request.POST.getlist('interpretation_gonorrhoeae[]'):
                    interpretation_gonorrhoeae = request.POST.getlist('interpretation_gonorrhoeae[]')
                 else:
                    interpretation_gonorrhoeae=''

                 if request.POST.getlist('interpretation_trachomatic[]'):
                    interpretation_trachomatic = request.POST.getlist('interpretation_trachomatic[]')
                 else:
                    interpretation_trachomatic=''

                 if Acc:
                     if Acc.result_in_molecular_CHlamydia_trachomatis.all():
                         old_result=Acc.result_in_molecular_CHlamydia_trachomatis.all()
                         for result in old_result:
                             res=models.Result_code.objects.get(code_id=result.code_id)
                             if res:
                                 Acc.result_in_molecular_CHlamydia_trachomatis.remove(res)
                         Acc.save()

                     if interpretation_trachomatic:
                         for interpretation in interpretation_trachomatic:
                             Result=models.Result_code.objects.get(code_id=interpretation)
                             Result.chlamydia.add(Acc)

                     if Acc.result_in_molecular_Neiseria_gonorroeae.all():
                         old_result=Acc.result_in_molecular_Neiseria_gonorroeae.all()
                         for result in old_result:
                             res=models.Result_code.objects.get(code_id=result.code_id)
                             if res:
                                 Acc.result_in_molecular_Neiseria_gonorroeae.remove(res)
                         Acc.save()

                     if interpretation_gonorrhoeae:
                         for interpretation in interpretation_gonorrhoeae:
                             Result=models.Result_code.objects.get(code_id=interpretation)
                             Result.gonorroea.add(Acc)

                     if 'MP_result_photo' in request.FILES:
                        Acc.MP_result_photo= request.FILES['MP_result_photo']

                     if 'MP_result_comment' in request.POST:
                        Acc.MP_result_comment=str(request.POST.get('MP_result_comment', ''))

                     if 'MP_result_caption' in request.POST:
                        Acc.MP_result_caption=str(request.POST.get('MP_result_caption', ''))
                     Acc.MP_completed=1
                     Acc.completed_date=date.today()
                     Acc.save()
                     return render_to_response('dashboard_screen/enter_result.html', {
                         'title': 'Enter Result',
                         'Entry':Entry,
                         'Results':Results,
                         'Result_area':Result_area,
                         'result_list_value':Acc,
                         'Results_in_specimen':Results_in_specimen,
                         'Results_in_additional':Results_in_additional,
                         'Results_in_interpretation':Results_in_interpretation,
                         'Results_in_hormonal':Results_in_hormonal,
                         'no_gyn_specimen_sources':no_gyn_specimen_sources,
                         'result_in_molecular':result_in_molecular,

                     },c)


             if 'save_sp_result' in request.POST:
                 if 'entry_id' in request.POST:
                     entry_id =request.POST.get('entry_id', '')
                     if entry_id:
                         try:
                              Entry = models.Entry.objects.get(entry_id=int(entry_id))
                         except ObjectDoesNotExist:
                              Entry=''

                     if 'exam_id' in request.POST:
                         exam_id =int(request.POST.get('exam_id', ''))
                         Exam=models.Exam.objects.get(exam_id=exam_id)
                 Acc=''
                 if Entry:
                     all_acc=Entry.accession_number.all()
                     if all_acc:
                         for acc in all_acc:
                             if acc.exam_in.exam_id == Exam.exam_id:
                                 Acc=acc

                 if Acc:
                     if 'SP_result_photo' in request.FILES:
                        Acc.SP_result_photo= request.FILES['SP_result_photo']

                     if 'SP_result_caption' in request.POST:
                        Acc.SP_result_caption=str(request.POST.get('SP_result_caption', ''))

                     if 'SP_result_comment' in request.POST:
                        Acc.SP_result_comment=str(request.POST.get('SP_result_comment', ''))

                     if 'SP_result_part_1' in request.POST:
                        Acc.SP_result_part_1=str(request.POST.get('SP_result_part_1', ''))

                     if 'SP_result_part_1' in request.POST:
                        Acc.SP_result_part_1=str(request.POST.get('SP_result_part_1', ''))

                     if 'SP_result_part_2' in request.POST:
                        Acc.SP_result_part_2=str(request.POST.get('SP_result_part_2', ''))

                     if 'SP_result_part_3' in request.POST:
                        Acc.SP_result_part_3=str(request.POST.get('SP_result_part_3', ''))

                     if 'SP_result_part_4' in request.POST:
                        Acc.SP_result_part_4=str(request.POST.get('SP_result_part_4', ''))

                     if 'SP_result_part_5' in request.POST:
                        Acc.SP_result_part_5=str(request.POST.get('SP_result_part_5', ''))

                     if 'SP_result_part_6' in request.POST:
                        Acc.SP_result_part_6=str(request.POST.get('SP_result_part_6', ''))

                     if 'SP_result_part_7' in request.POST:
                        Acc.SP_result_part_7=str(request.POST.get('SP_result_part_7', ''))

                     if 'SP_result_part_8' in request.POST:
                        Acc.SP_result_part_8=str(request.POST.get('SP_result_part_8', ''))

                     if 'SP_result_part_9' in request.POST:
                        Acc.SP_result_part_9=str(request.POST.get('SP_result_part_9', ''))

                     if 'SP_result_part_10' in request.POST:
                        Acc.SP_result_part_10=str(request.POST.get('SP_result_part_10', ''))

                     if 'SP_result_part_11' in request.POST:
                        Acc.SP_result_part_11=str(request.POST.get('SP_result_part_11', ''))

                     if 'SP_result_part_12' in request.POST:
                        Acc.SP_result_part_12=str(request.POST.get('SP_result_part_12', ''))
                     Acc.SP_completed=1
                     Acc.completed_date=date.today()
                     Acc.save()
                     return render_to_response('dashboard_screen/enter_result.html', {
                         'title': 'Enter Result',
                         'Entry':Entry,
                         'Results':Results,
                         'Result_area':Result_area,
                         'result_list_value':Acc,
                         'Results_in_specimen':Results_in_specimen,
                         'Results_in_additional':Results_in_additional,
                         'Results_in_interpretation':Results_in_interpretation,
                         'Results_in_hormonal':Results_in_hormonal,
                         'no_gyn_specimen_sources':no_gyn_specimen_sources,
                         'result_in_molecular':result_in_molecular,
                     },c)





         return render_to_response('dashboard_screen/enter_result.html', {
             'title': 'Enter Result',
             'Entry':Entry,
             'Results':Results,
             'Result_area':Result_area,
             'Results_in_specimen':Results_in_specimen,
             'Results_in_additional':Results_in_additional,
             'Results_in_interpretation':Results_in_interpretation,
             'Results_in_hormonal':Results_in_hormonal,
             'no_gyn_specimen_sources':no_gyn_specimen_sources,
             'result_in_molecular':result_in_molecular,
         },c)
     else:
         message='Your user session is expired!'
         return render_to_response('dashboard_screen/login_user.html', {
            'title': 'Login',
            'message': message,
            'pagetype':11,
         },c)
