public EventVo getEvent(EventRefVo voRef) {
    if (voRef == null) throw new DomainRuntimeException("Cannot get EventVo for null EventRefVo");

    DomainFactory factory = getDomainFactory();
    Event doEvent = (Event) factory.getDomainObject(Event.class, voRef.getID_Event());
    return EventVoAssembler.create(doEvent);
  }
 public void removeQueuedNotification(IQueuedNotification notification) throws Exception {
   DomainFactory factory = getDomainFactory();
   QueuedNotification domainObject =
       (QueuedNotification)
           factory.getDomainObject(QueuedNotification.class, notification.getINotificationId());
   if (domainObject != null) {
     factory.delete(domainObject);
   }
 }
  public PatientDiagnosisAtConsultationVo getPatientDiagnosis(PatientDiagnosisRefVo patDiagnosis) {
    if (patDiagnosis == null || patDiagnosis.getID_PatientDiagnosis() == null) return null;

    DomainFactory factory = getDomainFactory();
    PatientDiagnosis doPatDiagnosis =
        (PatientDiagnosis)
            factory.getDomainObject(PatientDiagnosis.class, patDiagnosis.getID_PatientDiagnosis());

    return PatientDiagnosisAtConsultationVoAssembler.create(doPatDiagnosis);
  }
  // WDEV-19239
  public CodedDiagnosesForAttendanceVo getCodedDiagForAttendance(
      CodedDiagForAttendanceRefVo codedDiagRef) {
    if (codedDiagRef == null || codedDiagRef.getID_CodedDiagForAttendance() == null) return null;

    DomainFactory factory = getDomainFactory();
    CodedDiagForAttendance doCodedDiag =
        (CodedDiagForAttendance)
            factory.getDomainObject(
                CodedDiagForAttendance.class, codedDiagRef.getID_CodedDiagForAttendance());

    return CodedDiagnosesForAttendanceVoAssembler.create(doCodedDiag);
  }
  public PatientShort getPatient(PatientRefVo patientRef) {
    if (patientRef == null || patientRef.getID_Patient() == null) {
      throw new CodingRuntimeException("Cannot get Patient on null Id ");
    }

    DomainFactory factory = getDomainFactory();

    Patient domainPatient =
        (Patient) factory.getDomainObject(Patient.class, patientRef.getID_Patient());

    return PatientShortAssembler.create(domainPatient);
  }
  public DementiaForWorklistVo getDementiaForWorklist(DementiaRefVo dementiaRef) {
    if (dementiaRef == null || dementiaRef.getID_Dementia() == null) {
      throw new CodingRuntimeException("Cannot get DementiaVo on null Id ");
    }

    DomainFactory factory = getDomainFactory();

    Dementia domainDementia =
        (Dementia) factory.getDomainObject(Dementia.class, dementiaRef.getID_Dementia());

    return DementiaForWorklistVoAssembler.create(domainDementia);
  }
  public RTTStatusEventMapVo getRTTStatusPointToEvent(RTTStatusEventMapRefVo recordRef) {
    if (recordRef == null || recordRef.getID_RTTStatusEventMap() == null) {
      throw new CodingRuntimeException(
          "Cannot get details for a null RTTStatusEventMapVo reference");
    }
    DomainFactory factory = getDomainFactory();

    RTTStatusEventMap rttStatusEventDO =
        (RTTStatusEventMap)
            factory.getDomainObject(RTTStatusEventMap.class, recordRef.getID_RTTStatusEventMap());

    return RTTStatusEventMapVoAssembler.create(rttStatusEventDO);
  }
  public ims.core.vo.LocSiteLiteVo getCurrentHospital(ims.framework.interfaces.ILocation location) {
    if (location == null) return null;

    DomainFactory factory = getDomainFactory();

    Location currentHospital =
        getHospital((Location) factory.getDomainObject(Location.class, location.getID()));

    if (currentHospital instanceof LocSite)
      return LocSiteLiteVoAssembler.create((LocSite) currentHospital);

    return null;
  }
  // WDEV-15908
  public LocationLiteVo getCurrentHospital(ILocation location) {
    if (location == null) return null;

    DomainFactory factory = getDomainFactory();

    Location currentHospital =
        getHospital((Location) factory.getDomainObject(Location.class, location.getID()));

    if (currentHospital instanceof LocSite)
      return LocationLiteVoAssembler.create((Location) currentHospital);

    return null;
  }
  public PatientAssessmentVo save(
      PatientAssessmentVo patientAssessment, ConsultationAssessmentsLiteVo consultationAssessment)
      throws StaleObjectException {
    // Check parameters
    if (patientAssessment == null || consultationAssessment == null)
      throw new CodingRuntimeException("Can't save null records.");

    if (patientAssessment.isValidated() == false || consultationAssessment.isValidated() == false)
      throw new CodingRuntimeException("Can't save records not validated.");

    DomainFactory factory = getDomainFactory();

    // Ensure the latest Consultation Assessments record is used (to avoid StaleObject)
    if (consultationAssessment.getID_ConsultationAssessments() != null) {
      // If the Consultation Assessment was saved then retrieve the latest version of it
      consultationAssessment =
          ConsultationAssessmentsLiteVoAssembler.create(
              (ConsultationAssessments)
                  factory.getDomainObject(
                      ConsultationAssessments.class,
                      consultationAssessment.getID_ConsultationAssessments()));
    } else {
      // IF the Consultation Assessment isn't saved then check database for a saved record
      ConsultationAssessmentsLiteVo recordInDB =
          getConsultationAssessments(consultationAssessment.getCatsReferral());

      if (recordInDB != null) consultationAssessment = recordInDB;
    }

    // Extract domain objects
    PatientAssessment domPatientAssessment =
        PatientAssessmentVoAssembler.extractPatientAssessment(factory, patientAssessment);

    // Commit PatientAssessment to database
    factory.save(domPatientAssessment);

    PatientAssessmentShortVo shortAssessment =
        PatientAssessmentShortVoAssembler.create(domPatientAssessment);
    consultationAssessment.getPatientAssessment().add(shortAssessment);

    ConsultationAssessments domConsultationAssessments =
        ConsultationAssessmentsLiteVoAssembler.extractConsultationAssessments(
            factory, consultationAssessment);

    factory.save(domConsultationAssessments);

    // Return the saved record
    return PatientAssessmentVoAssembler.create(domPatientAssessment);
  }
  /** Get the vitalSignMonitoringGroupVo */
  public ims.core.vo.VitalSignMonitoringGroupVo getVitalSignMonitoringGroupVo(
      VitalSignMonitoringGroupRefVo vitalSignMonitoringGroupRefVo) {
    if (vitalSignMonitoringGroupRefVo == null) return null;

    DomainFactory factory = getDomainFactory();
    VitalSignMonitoringGroup domVitalSignMonitoringGroup =
        (VitalSignMonitoringGroup)
            factory.getDomainObject(
                VitalSignMonitoringGroup.class,
                vitalSignMonitoringGroupRefVo.getID_VitalSignMonitoringGroup());
    VitalSignMonitoringGroupVo vitalSignMonitoringGroupVo =
        VitalSignMonitoringGroupVoAssembler.create(domVitalSignMonitoringGroup);

    return vitalSignMonitoringGroupVo;
  }
  /** Saves the default schedule for current date to a provided client ClientImmunisationSchedule */
  public ClientImmunisationScheduleVo saveDefaultScheduleToClient(
      PatientRefVo clientRef, MemberOfStaffLiteVo mos)
      throws DomainInterfaceException, StaleObjectException, ForeignKeyViolationException,
          UniqueKeyViolationException {
    if (clientRef == null)
      throw new DomainInterfaceException(
          "A client must be selected before a schedule can be added");

    // Look for a client in the database
    DomainFactory factory = getDomainFactory();
    ClientLiteVo clientLiteVo =
        ClientLiteVoAssembler.create(
            (Patient) factory.getDomainObject(Patient.class, clientRef.getID_Patient()));

    if (clientLiteVo == null) throw new DomainInterfaceException("Desired client does not exist");

    Date dateOfBirth = new Date();
    dateOfBirth.setDay(
        clientLiteVo.getDob().getDay() == null ? new Integer(1) : clientLiteVo.getDob().getDay());
    dateOfBirth.setMonth(
        clientLiteVo.getDob().getMonth() == null
            ? new Integer(1)
            : clientLiteVo.getDob().getMonth());
    dateOfBirth.setYear(
        clientLiteVo.getDob().getYear() == null
            ? new Integer(new Date().getYear())
            : clientLiteVo.getDob().getYear());

    ScheduleConfigurationLiteVo defaultScheduleConfiguration =
        getDefaultScheduleConfiguration(dateOfBirth);

    if (defaultScheduleConfiguration == null)
      throw new DomainInterfaceException(
          "There is no default schedule for the current date. Please define a default schedule for this date or select a schedule");

    ClientImmunisationScheduleVo clientSchedule =
        addScheduleToClient(clientRef, defaultScheduleConfiguration, mos);

    String[] errors = clientSchedule.validate();

    if (errors != null && errors.length != 0) {
      throw new DomainInterfaceException(
          "Can not add a default schedule to client. Errors present");
    }

    return saveClientImmunisationSchedule(clientSchedule);
  }
  public IUINotification createUINotification(IQueuedNotification notification) throws Exception {
    if (notification == null) throw new CodingRuntimeException("Invalid notification.");

    if (notification.getINotificationMessage() == null)
      throw new CodingRuntimeException("Notification message is null.");

    if (notification.getINotificationPriority() == null)
      throw new CodingRuntimeException("Notification priority is null.");

    NotificationVo instance = new NotificationVo();
    DomainFactory domainFactory = this.getDomainFactory();

    AppUser doUser =
        (AppUser)
            domainFactory.getDomainObject(AppUser.class, notification.getINotificationUserId());

    if (doUser == null)
      throw new DomainRuntimeException("Invalid User Id passed into createNotification.");

    instance.setUser(AppUserNotificationVoAssembler.create(doUser));
    instance.setDateTime(new DateTime());
    instance.setNotificationPriority(notification.getINotificationPriority().getId());
    instance.setMessage(notification.getINotificationMessage());
    instance.setSource(notification.getINotificationSource());
    instance.setSeen(Boolean.FALSE);

    if (notification.getINotificationEntityType() != null) {
      instance.setEntityType(notification.getINotificationEntityType());
      instance.setEntityId(notification.getINotificationEntityId());
    }

    String[] errors = instance.validate();
    if (errors != null && errors.length > 0) {
      throw new RuntimeException("Validation errors while creating a user notification.");
    }

    try {
      ims.core.admin.domain.objects.Notifications doNotification =
          NotificationVoAssembler.extractNotifications(domainFactory, instance);
      domainFactory.save(doNotification);
      instance = NotificationVoAssembler.create(doNotification);
    } catch (StaleObjectException e) {
      throw new RuntimeException(e);
    }

    return instance;
  }
  public void savePatientDocument(
      PatientDocumentVo document,
      CatsReferralReportsVo catReferral,
      ReferralOutcomeVo voOutcome,
      PrescriptionsVo selectedPrescription)
      throws StaleObjectException {
    if (document != null) {
      if (!document.isValidated())
        throw new DomainRuntimeException("PatientDocumentVo not validated");
    }

    DomainFactory factory = getDomainFactory();

    // WDEV-13956
    Prescription prescription =
        PrescriptionsVoAssembler.extractPrescription(factory, selectedPrescription);
    factory.save(prescription);
    // end

    PatientDocument doc = PatientDocumentVoAssembler.extractPatientDocument(factory, document);
    factory.save(doc);

    CatsReferral doCatsReferral =
        CatsReferralReportsVoAssembler.extractCatsReferral(factory, catReferral);
    if (catReferral != null) doCatsReferral.getReferralDocuments().add(doc);

    factory.save(doCatsReferral);

    // --------------wdev-14193
    prescription =
        (Prescription)
            factory.getDomainObject(Prescription.class, selectedPrescription.getID_Prescription());
    PrescriptionsVo temppre = PrescriptionsVoAssembler.create(prescription);
    if (voOutcome != null) {
      if (voOutcome.getPrescriptions().contains(temppre)) {
        voOutcome.getPrescriptions().remove(temppre);
        voOutcome.getPrescriptions().add(temppre);
      }
    }
    // -----------

    ReferralOutcome doRef = ReferralOutcomeVoAssembler.extractReferralOutcome(factory, voOutcome);
    factory.save(doRef);
  }
  public void setUserNotified(INotification notification) {
    if (notification == null)
      throw new CodingRuntimeException("Notification passed into setUserNotified is null.");

    DomainFactory factory = getDomainFactory();

    NotificationVo notificationVo =
        NotificationVoAssembler.create(
            (Notifications)
                factory.getDomainObject(Notifications.class, notification.getINotificationId()));

    notificationVo.setUserNotified(true);

    notificationVo.validate();

    try {
      factory.save(NotificationVoAssembler.extractNotifications(factory, notificationVo));
    } catch (StaleObjectException e) {
      throw new RuntimeException(e);
    }
  }
  public Boolean isStale(LeadConsultantForSpecialtyConfigVo globalContext) {
    if (globalContext == null || globalContext.getID_SpecialtyLeadConsultant() == null) {
      throw new CodingRuntimeException(
          "Cannot get LeadConsultantForSpecialtyConfigFBVo on null Id ");
    }

    DomainFactory factory = getDomainFactory();
    SpecialtyLeadConsultant domainLeadCons =
        (SpecialtyLeadConsultant)
            factory.getDomainObject(
                SpecialtyLeadConsultant.class, globalContext.getID_SpecialtyLeadConsultant());

    if (domainLeadCons == null) {
      return true;
    }

    if (domainLeadCons.getVersion() > globalContext.getVersion_SpecialtyLeadConsultant()) {
      return true;
    }

    return false;
  }
  public void markAsSeen(IUINotification notification) {
    if (notification == null)
      throw new CodingRuntimeException("Notification passed into markAsSeen is null.");

    DomainFactory factory = getDomainFactory();

    NotificationVo notificationVo =
        NotificationVoAssembler.create(
            (Notifications)
                factory.getDomainObject(Notifications.class, notification.getINotificationId()));

    notificationVo.setSeen(Boolean.TRUE);
    notificationVo.setSeenAt(new DateTime());

    notificationVo.validate();

    try {
      factory.save(NotificationVoAssembler.extractNotifications(factory, notificationVo));
    } catch (StaleObjectException e) {
      throw new RuntimeException(e);
    }
  }
  /** save */
  public Boolean saveAllocations(ims.RefMan.vo.WorkAllocationVoCollection voAllocations)
      throws ims.domain.exceptions.StaleObjectException {
    if (voAllocations == null) throw new CodingRuntimeException("Invalid voAllocations");
    if (!voAllocations.isValidated())
      throw new CodingRuntimeException("voAllocations not validated");

    DomainFactory factory = getDomainFactory();
    for (int i = 0; i < voAllocations.size(); i++) {
      WorkAllocation domainObject =
          WorkAllocationVoAssembler.extractWorkAllocation(factory, voAllocations.get(i));
      factory.save(domainObject);

      // wdev-8480
      CatsReferral doCatsReferral =
          (CatsReferral) factory.getDomainObject(voAllocations.get(i).getCatsReferral());
      if (voAllocations.get(i).getUnallocatedDateIsNotNull())
        doCatsReferral.setIsCurrentlyAllocated(Boolean.FALSE);
      else doCatsReferral.setIsCurrentlyAllocated(Boolean.TRUE);
      factory.save(doCatsReferral);
    }

    return true;
  }
  public OrderInvestigationForAttendenceNotesCcVoCollection listOrderInvestigations(
      PatientRefVo patient, CareContextRefVo careContext, String investigationsAlreadyAdded) {
    if (patient == null || patient.getID_Patient() == null)
      throw new CodingRuntimeException(
          "Patient parameter can not be null when listing OrderInvestigations.");

    DomainFactory factory = getDomainFactory();
    java.util.Date fromDate = null;
    java.util.Date dateTo = null;

    if (careContext != null && careContext.getID_CareContext() != null) {
      CareContext doCareContext =
          (CareContext) factory.getDomainObject(CareContext.class, careContext.getID_CareContext());
      if (doCareContext != null) {
        if (doCareContext.getStartDateTime() != null) {
          fromDate = doCareContext.getStartDateTime();
        }

        if (doCareContext.getEndDateTime() != null) {
          return null;
        }

        dateTo = new java.util.Date();
      }
    }

    StringBuilder query = new StringBuilder();

    ArrayList<String> paramNames = new ArrayList<String>();
    ArrayList<Object> paramValues = new ArrayList<Object>();

    query.append("SELECT orderInv FROM OrderInvestigation AS orderInv ");
    query.append(
        " LEFT JOIN FETCH orderInv.orderDetails AS details LEFT JOIN details.patient AS patient left join orderInv.investigation as inv left join inv.investigationIndex as invIndex left join orderInv.ordInvCurrentStatus.ordInvStatus as ordStatus ");

    query.append(
        "WHERE patient.id = :PATIENT_ID and ordStatus.id <> :cancelledStatusId and ordStatus.id <> :cancelRequestStatusId");
    paramNames.add("PATIENT_ID");
    paramValues.add(patient.getID_Patient());

    // WDEV-17303
    paramNames.add("cancelledStatusId");
    paramValues.add(OrderInvStatus.CANCELLED.getID());
    paramNames.add("cancelRequestStatusId");
    paramValues.add(OrderInvStatus.CANCEL_REQUEST.getID());

    if (fromDate != null && dateTo != null) {
      query.append(
          " AND orderInv.systemInformation.creationDateTime BETWEEN :FROM_DATE AND :END_DATE ");

      paramNames.add("FROM_DATE");
      paramValues.add(fromDate);
      paramNames.add("END_DATE");
      paramValues.add(dateTo);
    }

    if (investigationsAlreadyAdded != null && investigationsAlreadyAdded.length() > 0) {
      query.append(" AND orderInv.id not in (");
      query.append(investigationsAlreadyAdded);
      query.append(") ");
    }

    query.append(" order by UPPER(invIndex.name) asc");

    return OrderInvestigationForAttendenceNotesCcVoAssembler
        .createOrderInvestigationForAttendenceNotesCcVoCollectionFromOrderInvestigation(
            factory.find(query.toString(), paramNames, paramValues));
  }
  private ims.generalmedical.vo.AdmisSummary getAdmissionSummary(
      CareContextShortVo careContext, ClinicalContactShortVo clinicalContact) {
    // Get the Medical Contact, everything else can be retrieved from there.
    DomainFactory factory = getDomainFactory();

    AdmisSummary summaryVo = new AdmisSummary();

    InjuryDetailsVoCollection voCollInjuryDetails = new InjuryDetailsVoCollection();

    String hql = " from InjuryDetails injuryDetails ";
    StringBuffer condStr = new StringBuffer();
    String andStr = " ";

    ArrayList markers = new ArrayList();
    ArrayList values = new ArrayList();

    condStr.append(andStr + " injuryDetails.clinicalContact.contactType = :contactType");
    markers.add("contactType");
    values.add(getDomLookup(ContactType.SPINALMEDICALADMISSION));
    andStr = " and ";

    if (careContext != null) {
      condStr.append(andStr + " injuryDetails.clinicalContact.careContext.id = :id_CareContext");
      markers.add("id_CareContext");
      values.add(careContext.getID_CareContext());
      andStr = " and ";
    } else if (clinicalContact != null) {
      condStr.append(andStr + " injuryDetails.clinicalContact.id = :id_ClinicalContact");
      markers.add("id_ClinicalContact");
      values.add(clinicalContact.getID_ClinicalContact());
      andStr = " and ";
    }

    if (andStr.equals(" and ")) hql += " where ";

    hql += condStr.toString();
    voCollInjuryDetails =
        InjuryDetailsVoAssembler.createInjuryDetailsVoCollectionFromInjuryDetails(
            factory.find(hql, markers, values));

    if (voCollInjuryDetails != null && voCollInjuryDetails.size() > 0) {
      InjuryDetails injury =
          InjuryDetailsVoAssembler.extractInjuryDetails(factory, voCollInjuryDetails.get(0));
      if (injury != null) {
        // 1000 - seconds, 60 - minutes, 60 - hours, 24 - days
        long dayDiff =
            ((((new java.util.Date().getTime()
                                - (injury.getInjuryDate() != null
                                    ? injury.getInjuryDate().getTime()
                                    : 0))
                            / 1000)
                        / 60)
                    / 60)
                / 24;

        if (injury.getInjuryDate() != null)
          summaryVo.setDateOfInjury(new ims.framework.utils.Date(injury.getInjuryDate()));
        summaryVo.setDurationSinceInjury(String.valueOf(dayDiff));

        if (injury.getCauseOfInjury() != null)
          summaryVo.setCauseOfInjury(injury.getCauseOfInjury().getText());
        if (injury.getModeOfInjury() != null)
          summaryVo.setModeOfInjury(injury.getModeOfInjury().getText());
        if (injury.getMechanismOfInjury() != null)
          summaryVo.setMechanismOfInjury(injury.getMechanismOfInjury().getText());
      }
    }

    /*NeuroMotorFindingsVoCollection collNeuroMotorFindings = new NeuroMotorFindingsVoCollection();
    hql = " from NeuExamMotor neuExamMotor";
    condStr = new StringBuffer();
    andStr = " ";

    markers.clear();
    values.clear();

    if(careContext!=null)
    {
    	condStr.append(andStr + " neuExamMotor.careContext.id = :id_CareContext");
    	markers.add("id_CareContext");
    	values.add(careContext.getID_CareContext());
    	andStr = " and ";
    }
    else if(clinicalContact!=null)
    {
    	condStr.append(andStr + " neuExamMotor.clinicalContact.id = :id_ClinicalContact");
    	markers.add("id_ClinicalContact");
    	values.add(clinicalContact.getID_ClinicalContact());
    	andStr = " and ";
    }

    if (andStr.equals(" and "))
    	hql += " where ";

    hql += condStr.toString();
    collNeuroMotorFindings = NeuroMotorFindingsVoAssembler.createNeuroMotorFindingsVoCollectionFromNeuExamMotor(factory.find(hql, markers, values));

    if(collNeuroMotorFindings.size()>0)
    {
    	NeuExamMotor motor = NeuroMotorFindingsVoAssembler.extractNeuExamMotor(factory, collNeuroMotorFindings.get(0));
    	if (motor != null)
    	{
    		if (motor.getLeftMotorLevel() != null)
    			summaryVo.setMotorLeft(motor.getLeftMotorLevel().getName());
    		if (motor.getRightMotorLevel() != null)
    			summaryVo.setMotorRight(motor.getRightMotorLevel().getName());

    		summaryVo.setAsiaScore(getAverrallAsiaScore(motor));
    	}
    }
    */
    NeuroSenastionFindingsVoCollection collNeuroSensationFindings =
        new NeuroSenastionFindingsVoCollection();
    hql = " from NeuExamSens neuExamSens";
    condStr = new StringBuffer();
    andStr = " ";

    markers.clear();
    values.clear();

    condStr.append(andStr + " neuExamSens.clinicalContact.contactType = :contactType");
    markers.add("contactType");
    values.add(getDomLookup(ContactType.SPINALMEDICALADMISSION));
    andStr = " and ";

    if (careContext != null) {
      condStr.append(andStr + " neuExamSens.careContext.id = :id_CareContext");
      markers.add("id_CareContext");
      values.add(careContext.getID_CareContext());
      andStr = " and ";
    } else if (clinicalContact != null) {
      condStr.append(andStr + " neuExamSens.clinicalContact.id = :id_ClinicalContact");
      markers.add("id_ClinicalContact");
      values.add(clinicalContact.getID_ClinicalContact());
      andStr = " and ";
    }

    if (andStr.equals(" and ")) hql += " where ";

    hql += condStr.toString();
    collNeuroSensationFindings =
        NeuroSenastionFindingsVoAssembler.createNeuroSenastionFindingsVoCollectionFromNeuExamSens(
            factory.find(hql, markers, values));

    if (collNeuroSensationFindings.size() > 0) {
      NeuExamSens sensation =
          NeuroSenastionFindingsVoAssembler.extractNeuExamSens(
              factory, collNeuroSensationFindings.get(0));
      if (sensation != null) {
        if (sensation.getFrankleGrade() != null)
          summaryVo.setFrankleGrade(sensation.getFrankleGrade().getText());
        if (sensation.getLeftSensoryLevel() != null)
          summaryVo.setSensoryLeft(sensation.getLeftSensoryLevel().getName());
        if (sensation.getRightSensoryLevel() != null)
          summaryVo.setSensoryRight(sensation.getRightSensoryLevel().getName());
      }
    }

    MSKSpinePathologyFindingVoCollection collMSKSpinePathologyFinding =
        new MSKSpinePathologyFindingVoCollection();

    hql = " from MskSpinePath mskSpinePath ";
    condStr = new StringBuffer();
    andStr = " ";

    markers.clear();
    values.clear();

    condStr.append(andStr + " mskSpinePath.clinicalContact.contactType = :contactType");
    markers.add("contactType");
    values.add(getDomLookup(ContactType.SPINALMEDICALADMISSION));
    andStr = " and ";

    if (careContext != null) {
      condStr.append(andStr + " mskSpinePath.careContext.id = :id_CareContext");
      markers.add("id_CareContext");
      values.add(careContext.getID_CareContext());
      andStr = " and ";
    } else if (clinicalContact != null) {
      condStr.append(andStr + " mskSpinePath.clinicalContact.id = :id_ClinicalContact");
      markers.add("id_ClinicalContact");
      values.add(clinicalContact.getID_ClinicalContact());
      andStr = " and ";
    }

    condStr.append(andStr + " mskSpinePath.isPrimaryPathology = :isprimary");
    markers.add("isprimary");
    values.add(Boolean.TRUE);
    andStr = " and ";

    if (andStr.equals(" and ")) hql += " where ";

    hql += condStr.toString();

    collMSKSpinePathologyFinding =
        MSKSpinePathologyFindingVoAssembler
            .createMSKSpinePathologyFindingVoCollectionFromMskSpinePath(
                factory.find(hql, markers, values));

    // java.util.List pathLst = factory.find(domContact.getMskPath(), " where
    // this.isPrimaryPathology = :primary", new String[]{"primary"}, new Object[]{Boolean.TRUE});
    // Should only be one returned
    if (collMSKSpinePathologyFinding != null && collMSKSpinePathologyFinding.size() > 0) {
      MskSpinePath path =
          MSKSpinePathologyFindingVoAssembler.extractMskSpinePath(
              factory, collMSKSpinePathologyFinding.get(0));
      if (path.getPathSite() != null)
        summaryVo.setLevelOfInjury(path.getPathSite().getDescription());
      if (path.getTypeOfInjury() != null)
        summaryVo.setTypeOfInjury(path.getTypeOfInjury().getText());
    }

    NeuroInterpretVoCollection collNeuroInterpretVo = new NeuroInterpretVoCollection();
    hql = " from NeuInterpret neuInterpret";
    condStr = new StringBuffer();
    andStr = " ";

    markers.clear();
    values.clear();

    condStr.append(andStr + " neuInterpret.clinicalContact.contactType = :contactType");
    markers.add("contactType");
    values.add(getDomLookup(ContactType.SPINALMEDICALADMISSION));
    andStr = " and ";

    if (careContext != null) {
      condStr.append(andStr + " neuInterpret.careContext.id = :id_CareContext");
      markers.add("id_CareContext");
      values.add(careContext.getID_CareContext());
      andStr = " and ";
    } else if (clinicalContact != null) {
      condStr.append(andStr + " neuInterpret.clinicalContact.id = :id_ClinicalContact");
      markers.add("id_ClinicalContact");
      values.add(clinicalContact.getID_ClinicalContact());
      andStr = " and ";
    }

    if (andStr.equals(" and ")) hql += " where ";

    hql += condStr.toString();
    collNeuroInterpretVo =
        NeuroInterpretVoAssembler.createNeuroInterpretVoCollectionFromNeuInterpret(
            factory.find(hql, markers, values));

    if (collNeuroInterpretVo != null && collNeuroInterpretVo.size() > 0) {
      NeuInterpret interpret =
          NeuroInterpretVoAssembler.extractNeuInterpret(factory, collNeuroInterpretVo.get(0));
      if (interpret != null) {
        if (interpret.getSpinalSyndrome() != null)
          summaryVo.setSpineSyndrome(interpret.getSpinalSyndrome().getText());
        if (interpret.getAsiaGrade() != null)
          summaryVo.setAsiaGrade(interpret.getAsiaGrade().getText());
        if (interpret.getOverallNeuroLevel() != null)
          summaryVo.setOverallNeuro(interpret.getOverallNeuroLevel().getName());
        if (interpret.getCompleteIncomplete() != null)
          summaryVo.setCompleteIncomplete(interpret.getCompleteIncomplete().getText());
      }
    }

    // Get the First Admission date for this patient.
    EpisodeofCareVo voEpisodeOfCare = null;
    CareContextVoCollection collCareContextVo = null;
    markers.clear();
    values.clear();

    if (careContext != null)
      voEpisodeOfCare =
          EpisodeofCareVoAssembler.create(
              (EpisodeOfCare)
                  factory.getDomainObject(
                      EpisodeOfCare.class, careContext.getEpisodeOfCare().getID_EpisodeOfCare()));
    else if (clinicalContact != null) {
      CareContextVo voCareContext =
          CareContextVoAssembler.create(
              (CareContext)
                  factory.getDomainObject(
                      CareContext.class, clinicalContact.getCareContext().getID_CareContext()));
      voEpisodeOfCare =
          EpisodeofCareVoAssembler.create(
              (EpisodeOfCare)
                  factory.getDomainObject(
                      EpisodeOfCare.class, voCareContext.getEpisodeOfCare().getID_EpisodeOfCare()));
    }

    collCareContextVo = voEpisodeOfCare.getCareContexts().sort();

    if ((collCareContextVo != null) && (collCareContextVo.size() > 0))
      for (int i = 0; i < collCareContextVo.size(); i++) {
        if (collCareContextVo.get(i).getContext().equals(ContextType.INPATIENT))
          summaryVo.setFirstAdmissionDate(collCareContextVo.get(i).getStartDateTime().getDate());
      }

    // MRSA record.
    MRSASitesResultsVoCollection collMRSAVo = new MRSASitesResultsVoCollection();
    hql = "select siteres from MRSAAssessment t join t.sitesAndResults as siteres ";
    condStr = new StringBuffer();
    andStr = " ";

    markers.clear();
    values.clear();

    condStr.append(andStr + " t.clinicalContact.contactType = :contactType");
    markers.add("contactType");
    values.add(getDomLookup(ContactType.SPINALMEDICALADMISSION));
    andStr = " and ";

    if (careContext != null) {
      condStr.append(andStr + " t.careContext.id like :cc");
      markers.add("cc");
      values.add(careContext.getID_CareContext());
      andStr = " and ";
    } else if (clinicalContact != null) {
      condStr.append(andStr + " t.clinicalContact.id like :cc");
      markers.add("cc");
      values.add(clinicalContact.getID_ClinicalContact());
      andStr = " and ";
    }

    condStr.append(andStr + " siteres.result = :res");
    markers.add("res");
    values.add(getDomLookup(MRSAResult.POSITIVE));
    andStr = " and ";

    hql += " where " + condStr.toString();

    collMRSAVo =
        MRSASitesResultsVoAssembler.createMRSASitesResultsVoCollectionFromMRSASitesResults(
            factory.find(hql, markers, values));

    if (collMRSAVo != null && collMRSAVo.size() > 0) summaryVo.setMRSAStatus(Boolean.TRUE);
    else summaryVo.setMRSAStatus(Boolean.FALSE);

    return summaryVo;
  }
  private ClientImmunisationScheduleVo addScheduleToClient(
      PatientRefVo clientRef, ScheduleConfigurationRefVo scheduleRef, MemberOfStaffLiteVo mos)
      throws DomainInterfaceException {
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //	PRELIMINARY CHECKS
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Check for a client
    if (clientRef == null)
      throw new DomainInterfaceException("Can not add schedule. Client was not found in records");

    // Look for a client in the database
    DomainFactory factory = getDomainFactory();
    ClientLiteVo clientLiteVo =
        ClientLiteVoAssembler.create(
            (Patient) factory.getDomainObject(Patient.class, clientRef.getID_Patient()));

    if (clientLiteVo == null) throw new DomainInterfaceException("Desired client does not exist");

    Date dateOfBirth = new Date();
    dateOfBirth.setDay(
        clientLiteVo.getDob().getDay() == null ? new Integer(1) : clientLiteVo.getDob().getDay());
    dateOfBirth.setMonth(
        clientLiteVo.getDob().getMonth() == null
            ? new Integer(1)
            : clientLiteVo.getDob().getMonth());
    dateOfBirth.setYear(
        clientLiteVo.getDob().getYear() == null
            ? new Integer(new Date().getYear())
            : clientLiteVo.getDob().getYear());

    // Check for a member of staff
    if (mos == null)
      throw new DomainInterfaceException(
          "An immunisation schedule for a client can be added only by a member of staff");

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //	RETRIVE - ClientImmunisationScheduleVo, ScheduleConfigurationVo
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Get the client schedule
    ClientImmunisationScheduleVo clientSchedule = getClientImmunisationSchedule(clientRef);

    // Get the schedule configuration to add (return the client schedule as it is - null if there is
    // none - if the schedule configuration is null)
    ScheduleConfigurationVo schedule;
    if (scheduleRef == null) return clientSchedule;
    else {
      // Get the schedule configuration
      schedule =
          ScheduleConfigurationVoAssembler.create(
              (ScheduleConfiguration)
                  factory.getDomainObject(
                      ScheduleConfiguration.class, scheduleRef.getID_ScheduleConfiguration()));

      if (schedule == null) return clientSchedule;
    }

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //	START BUILDING ClientImmunisationSchedule (create a new one if needed)
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // At this point if there was no schedule configuration create a new one
    if (clientSchedule == null) {
      clientSchedule = new ClientImmunisationScheduleVo();
    }

    // Set the client (if not already set)
    if (clientSchedule.getClient() == null) {
      clientSchedule.setClient(clientLiteVo);
    }

    try {
      clientSchedule.addSchedule(schedule, mos, new DateTime());
    } catch (IllegalArgumentException e) {
      //			throw new DomainInterfaceException("Can not add default schedule configuration to client
      // immunisation schedule as it conflicts withs existing schedule.");
      throw new DomainInterfaceException(e.getMessage());
    }

    return clientSchedule;
  }
 public LocMostVo getLocation(LocationRefVo voLocRef) {
   DomainFactory factory = getDomainFactory();
   return LocMostVoAssembler.create(
       (Location) factory.getDomainObject(Location.class, voLocRef.getID_Location()));
 }
 public EpisodeofCareVo getEpisodeOfCare(Integer id) {
   DomainFactory factory = getDomainFactory();
   EpisodeOfCare doEpisodeOfCare =
       (EpisodeOfCare) factory.getDomainObject(EpisodeOfCare.class, id);
   return EpisodeofCareVoAssembler.create(doEpisodeOfCare);
 }
 public UserAssessmentVo getUserAssessmentVo(Integer userAssessId) {
   DomainFactory factory = this.getDomainFactory();
   UserAssessment ua =
       (UserAssessment) factory.getDomainObject(UserAssessment.class, userAssessId);
   return UserAssessmentVoAssembler.create(ua);
 }
 public EpisodeofCareShortVo getEpisodeOfCareBuId(Integer eocId) {
   DomainFactory factory = this.getDomainFactory();
   EpisodeOfCare eoc = (EpisodeOfCare) factory.getDomainObject(EpisodeOfCare.class, eocId);
   return EpisodeofCareShortVoAssembler.create(eoc);
 }