public ims.core.vo.PatientAlertLiteVoCollection listAlerts(
      ims.core.patient.vo.PatientRefVo patient, IAppRole role) {
    if (patient == null)
      throw new CodingRuntimeException("Cannot list Patient Alerts on null Patient Id.");

    ArrayList<String> names = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    DomainFactory factory = getDomainFactory();
    StringBuffer hql =
        new StringBuffer(
            "select patAlrt from PatientAlert patAlrt left join patAlrt.alertType as alertType ");
    hql.append(" where patAlrt.patient.id = :patient");
    names.add("patient");
    values.add(patient.getID_Patient());

    hql.append(" and patAlrt.isCurrentlyActiveAlert = :isActive");
    names.add("isActive");
    values.add(Boolean.TRUE);

    String alertCategoryIds = getAlertCategoryIds(role);
    if (alertCategoryIds == null || alertCategoryIds.length() == 0) return null;

    hql.append(" and alertType.parent is not null and alertType.parent.id in (");
    hql.append(alertCategoryIds);
    hql.append(")");

    hql.append(" order by patAlrt.systemInformation.creationDateTime desc");

    List<?> list = factory.find(hql.toString(), names, values);
    return (PatientAlertLiteVoAssembler.createPatientAlertLiteVoCollectionFromPatientAlert(list));
  }
  /**
   * Impl for TTO HL7 messages you finds the current I/P care context for the patient in the message
   * (Note there will always be one open(no end/discharge date) I/P care context), then the
   * MedicationDetails record for the care context and replace the TTO coll
   */
  public void setPatientCareContextTTORecord(ims.clinical.vo.PatientTTOIfVo patientTTOs) {
    if (patientTTOs == null)
      throw new DomainRuntimeException("Message details are null, cannot process message");
    if (patientTTOs.getPatient() == null)
      throw new DomainRuntimeException("Patient details are null, cannot process message");

    DomainFactory factory = getDomainFactory();
    CareContext careContext = getOpenInPatientCareContext(patientTTOs.getPatient());
    if (careContext == null)
      throw new DomainRuntimeException("Open inpatient care context cannot be found for patient");
    MedicationDetails md = getMedicationDetailsFromCareContext(careContext);
    if (md == null)
      throw new DomainRuntimeException("Failed to get or create Medication Details record");

    md.getTTAs().clear();
    md.getAdmissionMedicationChanges().clear();
    Set<?> ttoFromMessage =
        TTODetailsIFVoAssembler.extractTTAMedicationSet(factory, patientTTOs.getTTOs());
    md.getTTAs().addAll(ttoFromMessage);

    Set<?> medChanges =
        AdmissionMedicationChangesVoAssembler.extractAdmissionMedicationChangesSet(
            factory, patientTTOs.getMedicationChanges());
    md.getAdmissionMedicationChanges().addAll(medChanges);
    try {
      factory.save(md);
    } catch (StaleObjectException soe) {
      throw new DomainRuntimeException(soe);
    }
  }
  public Boolean isStaleOnDiagnosis(ValueObject diagnosis) // WDEV-19239
      {
    if (diagnosis == null) return false;

    DomainFactory factory = getDomainFactory();

    List<?> appts = null;

    if (diagnosis instanceof PatientDiagnosisAtConsultationVo) {
      PatientDiagnosisAtConsultationVo patDiag = (PatientDiagnosisAtConsultationVo) diagnosis;
      appts =
          factory.find(
              "select a.id from PatientDiagnosis as a where a.id = :DiagnosisId and a.version > :DiagnosisVersion",
              new String[] {"DiagnosisId", "DiagnosisVersion"},
              new Object[] {
                patDiag.getID_PatientDiagnosis(), patDiag.getVersion_PatientDiagnosis()
              });
    } else if (diagnosis instanceof CodedDiagnosesForAttendanceVo) {
      CodedDiagnosesForAttendanceVo codedDiag = (CodedDiagnosesForAttendanceVo) diagnosis;
      appts =
          factory.find(
              "select a.id from CodedDiagForAttendance as a where a.id = :DiagnosisId and a.version > :DiagnosisVersion",
              new String[] {"DiagnosisId", "DiagnosisVersion"},
              new Object[] {
                codedDiag.getID_CodedDiagForAttendance(),
                codedDiag.getVersion_CodedDiagForAttendance()
              });
    }

    if (appts != null && appts.size() > 0) return true;

    return false;
  }
  public DischargeDetailsVo saveDischargeDetails(DischargeDetailsVo voDischargeDetails)
      throws DomainInterfaceException, StaleObjectException {
    if (voDischargeDetails == null) throw new CodingRuntimeException("DischargeDetailsVo is null");

    if (!voDischargeDetails.isValidated())
      throw new CodingRuntimeException("DischargeDetailsVo Value Object has not been validated");

    DomainFactory factory = getDomainFactory();
    DischargeDetails doDD =
        DischargeDetailsVoAssembler.extractDischargeDetails(factory, voDischargeDetails);

    factory.save(doDD);

    // WDEV-19871 - create RTLSummary when starting e-Discharge process only if one does not already
    // exist for the care context
    IEDischargeHelper eDischImpl = (IEDischargeHelper) getDomainImpl(EDischargeHelper.class);
    RTLSummaryVo rtlSummary =
        eDischImpl.getRTLSummaryForCareContext(voDischargeDetails.getCareContext());
    if (voDischargeDetails.getID_DischargeDetails() == null && rtlSummary == null) {
      rtlSummary = new RTLSummaryVo();
      rtlSummary.setCareContext(voDischargeDetails.getCareContext());

      RTLSummary rTLSummaryDO = RTLSummaryVoAssembler.extractRTLSummary(factory, rtlSummary);

      factory.save(rTLSummaryDO);
    }
    // WDEV-19871 -- ends here

    return DischargeDetailsVoAssembler.create(doDD);
  }
  /** get Discharge Details */
  public ims.clinical.vo.DischargeDetailsVo getDischargeDetails(
      ims.core.admin.vo.CareContextRefVo careContextRefvo) {
    if (careContextRefvo == null)
      throw new CodingRuntimeException("careContextRefVo Filter not provided for list call. ");

    if (careContextRefvo != null) {
      DomainFactory factory = getDomainFactory();
      StringBuffer hql = new StringBuffer(" from DischargeDetails dd where ");
      String andStr = " ";

      ArrayList<String> markers = new ArrayList<String>();
      ArrayList<Serializable> values = new ArrayList<Serializable>();

      hql.append(andStr + " dd.careContext.id = :careContextId");
      markers.add("careContextId");
      values.add(careContextRefvo.getID_CareContext());
      andStr = " and ";

      List list = factory.find(hql.toString(), markers, values);
      if (list != null && list.size() > 0) {
        DischargeDetailsVoCollection voColl =
            DischargeDetailsVoAssembler.createDischargeDetailsVoCollectionFromDischargeDetails(
                list);
        if (voColl != null && voColl.size() > 0) return voColl.get(0);
      }
    }
    return null;
  }
  public DischargeSupplementaryNotesVo getSupplementary(CareContextRefVo voCareContextRefVo) {
    if (voCareContextRefVo == null)
      throw new CodingRuntimeException("voCareContextRefVo Filter not provided for list call. ");

    if (voCareContextRefVo != null) {
      DomainFactory factory = getDomainFactory();
      StringBuffer hql = new StringBuffer(" from DischargeSupplementaryNotes ds where ");
      String andStr = " ";

      ArrayList<String> markers = new ArrayList<String>();
      ArrayList<Serializable> values = new ArrayList<Serializable>();

      hql.append(andStr + " ds.careContext.id = :careContextId");
      markers.add("careContextId");
      values.add(voCareContextRefVo.getID_CareContext());
      andStr = " and ";

      List list = factory.find(hql.toString(), markers, values);
      if (list != null && list.size() > 0) {
        DischargeSupplementaryNotesVoCollection voColl =
            DischargeSupplementaryNotesVoAssembler
                .createDischargeSupplementaryNotesVoCollectionFromDischargeSupplementaryNotes(list);
        if (voColl != null && voColl.size() > 0) return voColl.get(0);
      }
    }
    return null;
  }
  public InvestigationAttendenceDetailVo inactivateInvestigationAttendenceDetail(
      InvestigationAttendenceDetailVo record, AttendDiagInvTreatStatusVo attendDiagInvTreatStatus)
      throws StaleObjectException {
    if (record == null)
      throw new CodingRuntimeException("Cannot save a null InvestigationAttendenceDetailVo.");

    if (!record.isValidated())
      throw new CodingRuntimeException("InvestigationAttendenceDetailVo is not validated.");

    DomainFactory factory = getDomainFactory();

    InvestigationAttendenceDetail doRecord =
        InvestigationAttendenceDetailVoAssembler.extractInvestigationAttendenceDetail(
            factory, record);
    factory.save(doRecord);

    if (attendDiagInvTreatStatus != null) {
      AttendDiagInvTreatStatus doAttendDiagInvTreat =
          AttendDiagInvTreatStatusVoAssembler.extractAttendDiagInvTreatStatus(
              factory, attendDiagInvTreatStatus);
      factory.save(doAttendDiagInvTreat);
    }

    return record;
  }
  public UserAssessmentShortVoCollection listUserAssessments(UserDefinedAssessmentType type) {
    DomainFactory factory = getDomainFactory();
    StringBuffer hql = new StringBuffer(" ");
    String query = "select u1_1 from UserAssessment as u1_1 ";

    ArrayList markers = new ArrayList();
    ArrayList values = new ArrayList();
    String andStr = " ";

    if (type != null) {
      hql.append(andStr + " u1_1.assessmentType.id = :TYPE");
      markers.add("TYPE");
      values.add(new Integer(type.getId()));
      andStr = " and ";
    }

    if (markers.size() > 0) query += " where ";

    query += hql.toString();

    List list = factory.find(query, markers, values);

    return UserAssessmentShortVoAssembler.createUserAssessmentShortVoCollectionFromUserAssessment(
            list)
        .sort();
  }
  /** getReportAndTemplate */
  public String[] getReportAndTemplate(Integer reportId, Integer templateId)
      throws ims.domain.exceptions.DomainInterfaceException {
    String[] result = null;

    DomainFactory factory = getDomainFactory();

    List lst =
        factory.find(
            "select r1_1.reportXml, t1_1.templateXml, r1_1.reportName, r1_1.reportDescription, t1_1.name, t1_1.description from ReportBo as r1_1 left join r1_1.templates as t1_1 where (r1_1.id = :rid  and t1_1.id = :tid)",
            new String[] {"rid", "tid"},
            new Object[] {reportId, templateId});

    if (lst.iterator().hasNext()) {
      Object[] obj = (Object[]) lst.iterator().next();

      result =
          new String[] {
            (String) obj[0],
            (String) obj[1],
            (String) obj[2],
            (String) obj[3],
            (String) obj[4],
            (String) obj[5]
          };
    }

    return result;
  }
  public VaccineManufacturerBatchVoCollection listBatchVaccine(
      String batchNumber, VaccineLiteVo vaccine) throws DomainInterfaceException {
    if (batchNumber == null)
      throw new DomainInterfaceException(
          "Can not search for batch vaccines after an empty batch number");

    if (vaccine == null)
      throw new DomainInterfaceException(
          "Can not search for batch vaccines with no selected vaccine");

    DomainFactory factory = getDomainFactory();

    String query =
        "from VaccineManufacturerBatch as vmb where vmb.vaccine.id = :ID and UPPER(vmb.batchNumber) like :BATCHNUMBER and vmb.status.id = -617";
    ArrayList<String> markers = new ArrayList<String>();
    markers.add("ID");
    markers.add("BATCHNUMBER");
    ArrayList<Object> values = new ArrayList<Object>();
    values.add(vaccine.getID_Vaccine());
    values.add("%" + batchNumber.toUpperCase() + "%");

    return VaccineManufacturerBatchVoAssembler
        .createVaccineManufacturerBatchVoCollectionFromVaccineManufacturerBatch(
            factory.find(query, markers, values));
  }
  @SuppressWarnings("unchecked")
  private void saveTargetEvents(
      EventVo event, DomainFactory factory, EventTargetVoCollection eventTargets)
      throws ForeignKeyViolationException, StaleObjectException, UniqueKeyViolationException,
          UnqViolationUncheckedException {
    if (event.getID_Event() != null) {
      List oldEventsTargets =
          factory.find(
              "from EventTarget et where et.event.id = '" + event.getID_Event().toString() + "'");
      Iterator oldEventsTargetsList = oldEventsTargets.iterator();
      while (oldEventsTargetsList.hasNext()) {
        EventTarget doOldEventTarget = (EventTarget) oldEventsTargetsList.next();
        factory.delete(doOldEventTarget);
      }
    } else {
      return;
    }

    for (int i = 0; i < eventTargets.size(); i++) {
      eventTargets.get(i).getEvent().setID_Event(event.getID_Event());
      eventTargets.get(i).setID_EventTarget(null);
    }

    // Save eventTarget
    List newEventsTargets = EventTargetVoAssembler.extractEventTargetList(factory, eventTargets);
    Iterator newEventsTargetsList = newEventsTargets.iterator();

    while (newEventsTargetsList.hasNext()) {
      EventTarget doNewEventTarget = (EventTarget) newEventsTargetsList.next();
      factory.save(doNewEventTarget);
    }
  }
  public GpLiteWithNameVoCollection listGp(String name) throws DomainInterfaceException {
    if (name == null || name.trim() == null || name.trim().length() == 0)
      throw new DomainInterfaceException("Can not search for GP with no name provided");

    DomainFactory factory = getDomainFactory();

    String query = "from Gp as gp ";

    StringBuffer hql = new StringBuffer();
    ArrayList<String> markers = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    hql.append(" where ");

    // Break the name
    String[] splitNames = name.toUpperCase().trim().split(" ");

    for (int i = 0; i < splitNames.length; i++) {
      if (splitNames[i] != null || splitNames[i].length() > 0) {
        hql.append(
            "gp.name.upperSurname like :NAME" + i + " or gp.name.upperForename like :NAME" + i);
        markers.add("NAME" + i);
        values.add("%" + splitNames[i].toUpperCase() + "%");
      }

      if (i < splitNames.length - 1) {
        hql.append(" or ");
      }
    }

    if (markers.size() > 0) query += hql;

    return GpLiteWithNameVoAssembler.createGpLiteWithNameVoCollectionFromGp(
        factory.find(query, markers, values));
  }
  // WDEV-15661
  public SurgicalAuditOperationDetailVo saveAndMarkAsRIE(
      SurgicalAuditOperationDetailVo surgAuditToSave,
      SurgicalAuditProcedureDetailsVo surgAuditProcedureDetails,
      FormName form,
      Integer patId,
      Integer careContextId,
      String comment)
      throws StaleObjectException {
    if (surgAuditToSave == null || surgAuditProcedureDetails == null) {
      throw new CodingRuntimeException("Cannot get SurgicalAuditOperationDetailVo on null Id ");
    }

    DomainFactory factory = getDomainFactory();

    SurgicalAuditOperationDetail domainSurgicalAudit =
        SurgicalAuditOperationDetailVoAssembler.extractSurgicalAuditOperationDetail(
            factory, surgAuditToSave);
    factory.save(domainSurgicalAudit);
    factory.markAsRie(
        SurgicalAuditProcedureDetails.class,
        surgAuditProcedureDetails.getID_SurgicalAuditProcedureDetails(),
        form,
        patId,
        null,
        careContextId,
        comment);
    return SurgicalAuditOperationDetailVoAssembler.create(domainSurgicalAudit);
  }
  /** saveSite */
  public ims.core.vo.AppSiteVo saveSite(ims.core.vo.AppSiteVo siteVo)
      throws ims.domain.exceptions.DomainInterfaceException,
          ims.domain.exceptions.StaleObjectException {
    if (!siteVo.isValidated()) {
      throw new DomainRuntimeException("AppSiteVo has not been validated");
    }

    DomainFactory factory = getDomainFactory();

    if (siteVo.getID_AppSite() == null) {
      // there must be only one record
      List list = factory.find("from AppSite");

      if (list.size() > 0) {
        throw new ims.domain.exceptions.DomainInterfaceException(
            "There is already one record in core_appsite table !");
      }
    }

    AppSite domAppSite = AppSiteVoAssembler.extractAppSite(factory, siteVo);

    factory.save(domAppSite);

    return AppSiteVoAssembler.create(domAppSite);
  }
  // WDEV-19572
  public EventLiteVoCollection listEvents(String value, EventRefVo excludedEvent) {
    if (value == null || value.length() == 0)
      throw new DomainRuntimeException("Value passed to the search query is null");

    DomainFactory factory = getDomainFactory();

    ArrayList<String> marques = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    String hqlquery =
        "select ev from Event as ev left join ev.status as stat where ev.upperName like :EVENT_NAME and stat.id = :STATUS_ID ";
    marques.add("EVENT_NAME");
    values.add(value.trim().toUpperCase() + "%");
    marques.add("STATUS_ID");
    values.add(PreActiveActiveInactiveStatus.ACTIVE.getID());

    if (excludedEvent != null) {
      hqlquery += " and ev.id <> :EVENT_ID";
      marques.add("EVENT_ID");
      values.add(excludedEvent.getID_Event());
    }

    hqlquery += " order by ev.upperName asc";

    List<?> eventList =
        factory.find(hqlquery, marques.toArray(new String[marques.size()]), values.toArray());
    if (eventList == null || eventList.isEmpty()) return null;

    return EventLiteVoAssembler.createEventLiteVoCollectionFromEvent(eventList);
  }
  public ims.clinicaladmin.vo.TreatmentInterventionLiteVoCollection
      listTreatmentsInterventionsFromHotlist(
          String listOfTreatmentsInterventionsAllreadyAdded, TreatmentInterventionType type) {
    DomainFactory factory = getDomainFactory();
    StringBuilder query =
        new StringBuilder(
            "select ti from TreatmentInterventionHotlist as th left join th.hotListItem as titem left join titem.treatmentIntervention as ti left join th.specialty as sp left join ti.treatmentInterventionType as tType where sp.id = :Emergency and ti.isActive = 1 ");

    ArrayList<String> markers = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    markers.add("Emergency");
    values.add(Specialty.EMERGENCY.getID());

    if (listOfTreatmentsInterventionsAllreadyAdded != null
        && listOfTreatmentsInterventionsAllreadyAdded.length() > 0) {
      query.append(" and ti.id not in (" + listOfTreatmentsInterventionsAllreadyAdded + ") ");
    }

    if (type != null) {
      query.append(" and tType.id = :TType ");
      markers.add("TType");
      values.add(type.getID());
    }

    query.append(" order by UPPER(tType.text) asc, UPPER(ti.treatmentInterventionName) asc");

    List<?> tiList = factory.find(query.toString(), markers, values);

    return TreatmentInterventionLiteVoAssembler
        .createTreatmentInterventionLiteVoCollectionFromTreatmentIntervention(tiList);
  }
  public PMHChecklistConfigVoCollection listConfiguredProcedures() {
    DomainFactory factory = getDomainFactory();
    List procs = factory.find("select p from PMHChecklistConfig p order by p.specialty.text asc");

    return PMHChecklistConfigVoAssembler.createPMHChecklistConfigVoCollectionFromPMHChecklistConfig(
        procs);
  }
  /** listPrescriptions */
  public ims.RefMan.vo.PrescriptionsVoCollection listPrescriptions(
      ims.RefMan.vo.CatsReferralRefVo catsRefVo) {
    if (catsRefVo == null || catsRefVo.getID_CatsReferral() == null) {
      throw new CodingRuntimeException("CatsReferralVo is null or id not provided");
    }

    DomainFactory factory = getDomainFactory();
    StringBuffer hql =
        new StringBuffer(
            "select prescriptions from ReferralOutcome as ro join ro.catsReferral as cats join ro.prescriptions as prescriptions ");

    ArrayList<String> names = new ArrayList<String>();
    ArrayList<Integer> values = new ArrayList<Integer>();

    hql.append("  where cats.id = :idCatsRefferal");
    names.add("idCatsRefferal");
    values.add(catsRefVo.getID_CatsReferral());

    List result = factory.find(hql.toString(), names, values);

    if (result != null && result.size() > 0) {
      PrescriptionsVoCollection voColl =
          PrescriptionsVoAssembler.createPrescriptionsVoCollectionFromPrescription(result);
      if (voColl != null && voColl.size() > 0) {
        voColl.sort(SortOrder.DESCENDING);
        return voColl;
      }
    }

    return null;
  }
  public ims.emergency.vo.TrackingAreaVoCollection listTrackingAreas(
      ims.core.resource.place.vo.LocationRefVo locRef, TrackingAreaRefVo trackingAreaRef) {
    if (locRef == null) return null;

    DomainFactory factory = getDomainFactory();

    List trackingAreas = null;

    if (trackingAreaRef == null) // AttendanceDetails
    {
      String hsql =
          "select t1_1 from TrackingArea as t1_1 left join t1_1.eDLocation as l1_1 where(l1_1.id = :idLocation and t1_1.isRegistrationArea = 1)";
      trackingAreas =
          factory.find(hsql, new String[] {"idLocation"}, new Object[] {locRef.getID_Location()});
    } else // Tracking form, Move button
    {
      String hsql =
          "select t2_1 from TrackingArea as t1_1 left join t1_1.eDLocation as l1_1 left join t1_1.sendToAreas as t2_1 left join t2_1.status as l2_1 where	(t1_1.id = :idtrackingArea and l1_1.id = :idLocation and l2_1.id = :idStatus)";
      trackingAreas =
          factory.find(
              hsql,
              new String[] {"idtrackingArea", "idLocation", "idStatus"},
              new Object[] {
                trackingAreaRef.getID_TrackingArea(),
                locRef.getID_Location(),
                PreActiveActiveInactiveStatus.ACTIVE.getID()
              });
    }

    return TrackingAreaVoAssembler.createTrackingAreaVoCollectionFromTrackingArea(trackingAreas);
  }
  public String[] getSystemReportAndTemplate(Integer imsId) {
    String[] result = null;

    DomainFactory factory = getDomainFactory();

    List lst =
        factory.find(
            "select r1_1.reportXml, t1_1.templateXml, r1_1.reportName, r1_1.reportDescription, t1_1.name, t1_1.description from ReportBo as r1_1 left join r1_1.templates as t1_1 where (r1_1.imsId= :imsid) order by t1_1.name",
            new String[] {"imsid"},
            new Object[] {imsId});

    if (lst.iterator().hasNext()) {
      Object[] obj = (Object[]) lst.iterator().next();

      result =
          new String[] {
            (String) obj[0],
            (String) obj[1],
            (String) obj[2],
            (String) obj[3],
            (String) obj[4],
            (String) obj[5]
          };
    }

    return result;
  }
  public ims.clinicaladmin.vo.TreatmentInterventionLiteVoCollection listTreatmentsInterventions(
      String criteria, String listOfTreatmentsInterventionsAllreadyAdded) {
    if (criteria == null || criteria.length() == 0)
      throw new CodingRuntimeException("Cannot search on null TreatmentIntervention name.");

    DomainFactory factory = getDomainFactory();
    StringBuilder query =
        new StringBuilder(
            "select ti from TreatmentIntervention as ti left join ti.keywords as kw where ti.isActive = 1 and ti.id not in (select tisec.id from TreatmentInterventionHotlist as th left join th.hotListItem as titem left join titem.treatmentIntervention as tisec left join th.specialty as sp where sp.id = :Emergency) and (ti.treatmentInterventionName like :TreatmentName or kw.keyword like :TreatmentName) ");

    if (listOfTreatmentsInterventionsAllreadyAdded != null
        && listOfTreatmentsInterventionsAllreadyAdded.length() > 0) {
      query.append(" and ti.id not in (" + listOfTreatmentsInterventionsAllreadyAdded + ") ");
    }

    query.append(" order by UPPER(ti.treatmentInterventionName) asc");

    List<?> tiList =
        factory.find(
            query.toString(),
            new String[] {"Emergency", "TreatmentName"},
            new Object[] {Specialty.EMERGENCY.getID(), criteria + "%"});

    return TreatmentInterventionLiteVoAssembler
        .createTreatmentInterventionLiteVoCollectionFromTreatmentIntervention(tiList);
  }
  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 TrackingConfigurationVo saveTrackinConfig(
      TrackingConfigurationVo trackingConfigToSave, TrackingAreaVo trackingAreaToSave)
      throws StaleObjectException {
    if (trackingConfigToSave == null && trackingAreaToSave == null)
      throw new CodingRuntimeException(
          "Cannot save TrackingConfiguration/TrackingArea if null or get TrackingConfiguration/TrackingArea on null ID . ");

    DomainFactory factory = getDomainFactory();
    if (trackingConfigToSave != null) {
      if (!trackingConfigToSave.isValidated())
        throw new CodingRuntimeException("TrackingConfigurationVo not Validated");

      TrackingConfiguration trackingConfig =
          TrackingConfigurationVoAssembler.extractTrackingConfiguration(
              factory, trackingConfigToSave);

      factory.save(trackingConfig);
      return TrackingConfigurationVoAssembler.create(trackingConfig);
    } else if (trackingAreaToSave != null) {
      if (!trackingAreaToSave.isValidated())
        throw new CodingRuntimeException("TrackingAreaVo not Validated");

      TrackingArea trackingArea =
          TrackingAreaVoAssembler.extractTrackingArea(factory, trackingAreaToSave);

      factory.save(trackingArea);

      return null;
    }

    return null;
  }
  @SuppressWarnings("unchecked")
  private String checkForUniqueExternalMappings(
      EventExternalEventMappingVoCollection externalMappings) {
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<Serializable> values = new ArrayList<Serializable>();

    DomainFactory factory = getDomainFactory();
    StringBuffer ids = new StringBuffer();
    StringBuffer exclude = new StringBuffer();
    exclude.append(externalMappings.get(0).getEvent().getID_Event());

    String errors = new String();

    for (int i = 0; i < externalMappings.size(); i++) {
      if (externalMappings.get(i).getStatus().equals(PreActiveActiveInactiveStatus.ACTIVE)) {
        if (i > 0 && i < externalMappings.size()) {
          ids.append(" , ");
        }
        ids.append(externalMappings.get(i).getExternalEventMapping().getID_ExternalEventMapping());
      }
    }

    if (ids.length() == 0) return null;

    names.add("id_status");
    values.add(PreActiveActiveInactiveStatus.ACTIVE.getID());

    List eventsMappings =
        factory.find(
            "select ext.event.id, ext.externalEventMapping.id, event.id, event.name, event.status, event.status.id, external.id, external.group, external.detail, external.specialty, mosname.name.surname, mosname.name.forename, external.clinicCode, provider.systemName from EventExternalEventMapping as ext left join ext.event as event left join ext.externalEventMapping as external left join external.consultant as consult left join consult.mos as mosname left join external.providerSystem as provider where ext.externalEventMapping.id in ("
                + ids
                + ") and event.id <> "
                + exclude
                + " and event.status.id = :id_status ",
            names,
            values);

    Iterator eventsMappingsList = eventsMappings.iterator();
    while (eventsMappingsList.hasNext()) {
      Object[] obj = (Object[]) eventsMappingsList.next();
      errors +=
          ("External system "
              + ((String) obj[13]).toUpperCase()
              + ", "
              + ((LookupInstance) obj[7]).getText()
              + ", "
              + ((LookupInstance) obj[8]).getText()
              + ", "
              + ((LookupInstance) obj[9]).getText()
              + (((String) obj[10]) != null ? ", " + ((String) obj[10]) + " " : "")
              + (((String) obj[11]) != null ? ((String) obj[11]) + " , " : "")
              + (((String) obj[12]) != null ? ((String) obj[12]) : "")
              + " is already linked to event "
              + ((String) obj[3]).toUpperCase()
              + "\n");
    }

    return errors;
  }
  // WDEV-19918 - MAXIMS 10.1.2
  public Boolean existAttendanceNotes(
      PatientRefVo patientRef,
      CareContextRefVo careContextRef,
      AttendanceClinicalNoteType noteType) {
    if (patientRef == null)
      throw new CodingRuntimeException(
          "Cannot list AttendanceClinicalNotes for a null Patient Id.");

    String hql =
        "select count(attClinicalNotes.id) from AttendanceClinicalNotes as attClinicalNotes ";
    StringBuffer hqlConditions = new StringBuffer();

    ArrayList<String> markers = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    String andStr = "";

    if (patientRef != null) {
      hqlConditions.append(andStr);
      hqlConditions.append("attClinicalNotes.patient.id = :PatientId ");
      markers.add("PatientId");
      values.add(patientRef.getID_Patient());
      andStr = " and ";
    }

    if (careContextRef != null) {
      hqlConditions.append(andStr);
      hqlConditions.append(" attClinicalNotes.attendance.id = :CareContextId ");
      markers.add("CareContextId");
      values.add(careContextRef.getID_CareContext());
      andStr = " and ";
    }

    if (noteType != null) {
      hqlConditions.append(andStr);
      hqlConditions.append("attClinicalNotes.noteType.id = :noteTypeId ");
      markers.add("noteTypeId");
      values.add(noteType.getID());
      andStr = " and ";
    }

    if (hqlConditions.length() > 0) {
      hqlConditions.insert(0, " where (");
      hqlConditions.append(" ) ");
    }

    hqlConditions.append(
        andStr + " (attClinicalNotes.isRIE is null OR attClinicalNotes.isRIE = 0) ");

    hql = hql + hqlConditions.toString();

    DomainFactory factory = getDomainFactory();

    List<?> list = factory.find(hql, markers, values);

    if (list != null && list.size() > 0 && ((Long) list.get(0)).intValue() > 0) return true;

    return false;
  }
  public MedicLiteVoCollection listConsultants(MedicLiteVo filterVo)
      throws DomainInterfaceException {
    if (filterVo == null) throw new DomainInterfaceException("Can not search on null medic filter");

    if (filterVo.getName() == null
        || (filterVo.getName().getSurname() == null && filterVo.getName().getForename() == null)
        || (filterVo.getName().getSurname().length() == 00
            && filterVo.getName().getForename().length() == 0))
      throw new DomainInterfaceException("Can not search on null or zero length consultant name");

    String[] names;

    if (filterVo.getName().getSurnameIsNotNull() && filterVo.getName().getSurname().length() > 0)
      names = filterVo.getName().getSurname().split(" ");
    else names = filterVo.getName().getForename().split(" ");

    DomainFactory factory = getDomainFactory();

    StringBuffer hql = new StringBuffer();
    String query = " from Medic md ";
    ArrayList<String> markers = new ArrayList<String>();
    ArrayList<Object> values = new ArrayList<Object>();

    // Build search criteria
    {
      if (markers.size() > 0) hql.append(" AND (");
      else hql.append("(");

      for (int i = 0; i < names.length; i++) {
        hql.append("md.mos.name.upperSurname like :SURNAME" + i);
        markers.add("SURNAME" + i);
        values.add("%" + names[i].toUpperCase() + "%");

        hql.append(" OR ");

        hql.append("md.mos.name.upperForename like :FORENAME" + i);
        markers.add("FORENAME" + i);
        values.add("%" + names[i].toUpperCase() + "%");

        if (i != names.length - 1) hql.append(" OR ");
      }

      hql.append(")");
    }

    if (markers.size() > 0) query += " where ";

    query += hql.toString();

    try {
      List<DomainObject> listMedics;
      listMedics = factory.find(query, markers, values);
      return MedicLiteVoAssembler.createMedicLiteVoCollectionFromMedic(listMedics);
    } catch (RuntimeException e) {
      e.printStackTrace();
      return null;
    }
  }
 /** Lists all floor layouts */
 public ims.core.vo.FloorBedSpaceLayoutLiteVoCollection list() {
   DomainFactory factory = getDomainFactory();
   String hql =
       " from FloorBedLayout fbl where fbl.status.id = "
           + PreActiveActiveInactiveStatus.ACTIVE.getID();
   return FloorBedSpaceLayoutLiteVoAssembler
       .createFloorBedSpaceLayoutLiteVoCollectionFromFloorBedSpaceLayout(factory.find(hql))
       .sort();
 }
  public ims.ocrr.vo.LeadConsultantForSpecialtyConfigVoCollection listLeadConsultantForSpecialty() {
    DomainFactory factory = getDomainFactory();
    String query = "from SpecialtyLeadConsultant as specLeadCons";

    List<?> LeadConsList = factory.find(query);
    return LeadConsultantForSpecialtyConfigVoAssembler
        .createLeadConsultantForSpecialtyConfigVoCollectionFromSpecialtyLeadConsultant(
            LeadConsList);
  }
  /** listPresentingProblems */
  public PresProblemChecklistConfigVoCollection listPresentingProblems() {
    DomainFactory factory = getDomainFactory();
    List probs =
        factory.find(
            "select p from PresProblemChecklistConfig as p left join p.presentingProblem as p2_1 left join p2_1.presentingProblem as c1_1 left join p.specialty as l1_1 order by l1_1.text asc, c1_1.pCName asc");

    return PresProblemChecklistConfigVoAssembler
        .createPresProblemChecklistConfigVoCollectionFromPresProblemChecklistConfig(probs);
  }
  public VitalSignMonitoringGroupVoCollection listVitalSignMonitoringGroups()
      throws DomainInterfaceException {
    DomainFactory factory = getDomainFactory();
    List vsMonitoringGroupsList = factory.find(" from VitalSignMonitoringGroup");

    return VitalSignMonitoringGroupVoAssembler
        .createVitalSignMonitoringGroupVoCollectionFromVitalSignMonitoringGroup(
            vsMonitoringGroupsList);
  }