com.registryKit.client.clientDAO.java Source code

Java tutorial

Introduction

Here is the source code for com.registryKit.client.clientDAO.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registryKit.client;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author chadmccue
 */
@Repository
public class clientDAO {

    @Autowired
    private SessionFactory sessionFactory;

    /**
     * The 'getClientSearchFields' function will return the list of client search fields set up for the passed in program.
     * 
     * @param programId The id of the program the user is logged into
     * @return This function will return a list of clientSearchFields objects
     * 
     */
    public List<clientSearchFields> getClientSearchFields(Integer programId) throws Exception {

        /* Get a list of client search fields */
        Query q1 = sessionFactory.getCurrentSession().createQuery(
                "from programClientFields where programId = :programId and searchField = 1 order by searchDspPos asc");
        q1.setParameter("programId", programId);

        /* Get a list of client engagement search fields */
        Query q2 = sessionFactory.getCurrentSession().createQuery(
                "from programEngagementFields where programId = :programId and searchField = 1 order by searchDspPos asc");
        q2.setParameter("programId", programId);

        List<programClientFields> csearchFields = q1.list();
        List<programEngagementFields> engagementSearchFields = q2.list();

        ArrayList<clientSearchFields> searchFields = new ArrayList<clientSearchFields>();

        if (!csearchFields.isEmpty()) {

            for (programClientFields field : csearchFields) {

                dataElements fieldDetails = getFieldDetails(field.getFieldId());

                clientSearchFields searchField = new clientSearchFields();
                searchField.setFieldName(field.getFieldDisplayname());
                searchField.setFieldId(field.getFieldId());
                searchField.setSaveToTableCol(fieldDetails.getSaveToTableCol());

                if (field.getCrosswalkId() > 0) {
                    List<crosswalkData> cwData = getCrosswalkData(field.getCrosswalkId());

                    ArrayList<fieldSelectOptions> selectOptions = new ArrayList<fieldSelectOptions>();
                    for (crosswalkData data : cwData) {
                        fieldSelectOptions selectOption = new fieldSelectOptions();
                        selectOption.setoptionValue(data.getTargetValue());
                        selectOption.setoptionDesc(data.getDescValue());
                        selectOptions.add(selectOption);
                    }
                    searchField.setFieldSelectOptions(selectOptions);
                }

                searchFields.add(searchField);
            }
        }

        if (!engagementSearchFields.isEmpty()) {

            for (programEngagementFields field : engagementSearchFields) {

                dataElements fieldDetails = getFieldDetails(field.getFieldId());

                clientSearchFields searchField = new clientSearchFields();
                searchField.setFieldName(field.getFieldDisplayname());
                searchField.setFieldId(field.getFieldId());
                searchField.setSaveToTableCol(fieldDetails.getSaveToTableCol());

                if (field.getCrosswalkId() > 0) {
                    List<crosswalkData> cwData = getCrosswalkData(field.getCrosswalkId());

                    ArrayList<fieldSelectOptions> selectOptions = new ArrayList<fieldSelectOptions>();
                    for (crosswalkData data : cwData) {
                        fieldSelectOptions selectOption = new fieldSelectOptions();
                        selectOption.setoptionValue(data.getTargetValue());
                        selectOption.setoptionDesc(data.getDescValue());
                        selectOptions.add(selectOption);
                    }
                    searchField.setFieldSelectOptions(selectOptions);
                }

                searchFields.add(searchField);

            }
        }

        return searchFields;
    }

    /**
     * The 'getClients' function will search the programClients table for a list of clientResultList associated to the 
    passed in programId. If search parameters exist then it will filter out hte clientResultList based on the passed
    in search parameters
     * 
     * @param programId The id of the program the logged in user is associated to
     * @param searchParameters  The list of parameters and values to filter on.
     * 
     * @return This function will return a list of client Ids.
     */
    public List<Integer> getClients(Integer programId, String searchParameters) throws Exception {

        String[] searchParams = null;

        if (searchParameters != null) {
            searchParams = searchParameters.split("\\|", -1);
        }

        List<Integer> clientIds = new ArrayList<Integer>();

        String sqlQuery = "select id from programPatients where status = 1 and MCIReview = 0 and programId = "
                + programId;

        for (int i = 0; i < searchParams.length; i++) {
            String[] paramSplit = searchParams[i].split(":", -1);
            if (paramSplit.length > 1) {
                Integer fieldId = Integer.parseInt(paramSplit[0]);
                String fieldValue = paramSplit[1];

                if (fieldValue != null && !"".equals(fieldValue)) {
                    dataElements fieldDetails = getFieldDetails(fieldId);

                    sqlQuery += " and id in (select programpatientid from " + fieldDetails.getSaveToTableName()
                            + " where " + fieldDetails.getSaveToTableCol() + " like '%" + fieldValue + "%')";

                }
            }
        }

        Query clientQuery = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);

        return clientQuery.list();
    }

    /**
     * The 'getClientDetails' function will return the details for the client.
     * 
     * @table storage_clients
     * @param clientId  The id of the client
     * @return
     * @throws Exception 
     */
    public storageClients getClientDetails(Integer clientId) throws Exception {
        /* Get a list of client details */
        Query q1 = sessionFactory.getCurrentSession()
                .createQuery("from storageClients where programpatientId = :clientId");
        q1.setParameter("clientId", clientId);

        return (storageClients) q1.uniqueResult();
    }

    /**
     * The 'getClientAddressInfo' function will return the address information for the client.
     * 
     * @table storage_clients
     * @param clientId  The id of the client
     * @return
     * @throws Exception 
     */
    public storageClientAddressInfo getClientAddressInfo(Integer clientId) throws Exception {
        /* Get a list of client details */
        Query q1 = sessionFactory.getCurrentSession()
                .createQuery("from storageClientAddressInfo where programpatientId = :clientId");
        q1.setParameter("clientId", clientId);

        return (storageClientAddressInfo) q1.uniqueResult();
    }

    /**
     * The 'getFieldDetails' function will return the details of the passed in field
     * 
     * @param fieldId   The id of the passed in field.
     */
    public dataElements getFieldDetails(Integer fieldId) throws Exception {

        Query q1 = sessionFactory.getCurrentSession().createQuery("from dataElements where id = :fieldId");
        q1.setParameter("fieldId", fieldId);

        return (dataElements) q1.uniqueResult();
    }

    /**
     * The 'getCrosswalkData' function will return the data associated with the passed in crosswalk id.
     * 
     * @param cwId The id of the crosswalk .
     */
    public List<crosswalkData> getCrosswalkData(Integer cwId) throws Exception {
        /* Get a list of client search fields */
        Query q1 = sessionFactory.getCurrentSession().createQuery("from crosswalkData where crosswalkId = :cwId");
        q1.setParameter("cwId", cwId);

        return q1.list();
    }

    /**
     * The 'getSections' function will return a list of sections set up for the client detail page.
     * 
     * @param programId The id of the program the user is logged into
     * @return
     * @throws Exception 
     */
    public List<programClientSections> getSections(Integer programId) throws Exception {
        /* Get a list of client detail sections */
        Query q1 = sessionFactory.getCurrentSession().createQuery(
                "from programClientSections where programId = :programId and status = 1 order by dspPos asc");
        q1.setParameter("programId", programId);

        return q1.list();
    }

    /**
     * The 'getClientFields' function will return a list of client fields associated to the passed in programId.
     * 
     * @param programId The id of the program the user is logged into
     * 
     * @return This function will return a list of fields for the section
     * @throws Exception 
     */
    public List<programClientFields> getClientFields(Integer programId, Integer clientId) throws Exception {

        Query query = sessionFactory.getCurrentSession().createSQLQuery(
                "SELECT a.*, b.saveToTableName, b.saveToTableCol, b.answerType as fieldType FROM program_patientFields a inner join dataElements b on b.id = a.fieldId where a.programId = :programId order by a.dspPos asc")
                .setParameter("programId", programId);

        query.setResultTransformer(Transformers.aliasToBean(programClientFields.class));

        List<programClientFields> fields = query.list();

        if (!query.list().isEmpty()) {

            for (programClientFields field : fields) {

                /* Get the actual data */
                field.setFieldValue(getTableData(field.getSaveToTableName(), field.getSaveToTableCol(), clientId));
                field.setModified(isFieldModified(field.getFieldId(), clientId));
            }

        }

        return fields;

    }

    /**
     * The 'getClientFieldDetails' function will return the details for the passed in program field.
     * 
     * @param programId The id of the program the user is logged into
     * @param fieldId   The id for the field to get the details for
     * @return  This function will return a single programClientFields object.
     * @throws Exception 
     */
    public programClientFields getClientFieldDetails(Integer programId, Integer fieldId) throws Exception {

        Query query = sessionFactory.getCurrentSession()
                .createQuery("from programClientFields where programId = :programId and fieldId = :fieldId");
        query.setParameter("programId", programId);
        query.setParameter("fieldId", fieldId);

        return (programClientFields) query.uniqueResult();

    }

    /**
     * The 'isFieldModified' function will check to see if the passed in field for the passed in client has
     * been modified.
     * 
     * @param fieldId   The id of the field to check
     * @param clientId  The id of the client to check
     * 
     * @return boolean
     */
    private boolean isFieldModified(Integer fieldId, Integer clientId) {

        Query query = sessionFactory.getCurrentSession()
                .createQuery("from modifiedFields where programPatientId = :clientId and fieldId = :fieldId");
        query.setParameter("clientId", clientId);
        query.setParameter("fieldId", fieldId);

        if (query.list().size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * The 'getTableData' function will return the data based on the passed in table, column and client id.
     * 
     * @param tableName The table name to search
     * @param tableCol  The table column to retrieve
     * @param clientId  The clientId to look for
     * 
     * @return This function will return a string
     */
    private String getTableData(String tableName, String tableCol, Integer clientId) {

        Query tableData = sessionFactory.getCurrentSession().createSQLQuery(
                "select " + tableCol + " from " + tableName + " where programpatientId = " + clientId);

        if (tableData.uniqueResult() != null) {
            return tableData.uniqueResult().toString();
        } else {
            return "";
        }

    }

    /**
     * The 'getProgramClient' function will return the programClients object for the passed in clientId
     * 
     * @param clientId The clicked client
     * @return
     * @throws Exception 
     */
    public programClients getProgramClient(Integer clientId) throws Exception {
        return (programClients) sessionFactory.getCurrentSession().get(programClients.class, clientId);
    }

    /**
     * The 'updateClientFields' function will update the fields from the client form
     * 
     * @param clientId The id of the client being updated
     * @param tableName The table to be updated
     * @param tableCol  The column to update
     * @param tableValue  The new value to save into the column
     */
    public void updateClientFields(Integer clientId, String tableName, String tableCol, String fieldValue,
            String currFieldValue, Integer fieldId, Integer fieldType, Integer systemUserId) throws Exception {

        String sqlQuery;

        /* Check to see if the field is a date field */
        if (fieldType == 6) {
            DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
            Date date = format.parse(fieldValue);
            Timestamp timestamp = new Timestamp(date.getTime());

            sqlQuery = "update " + tableName + " set " + tableCol + " = '" + timestamp
                    + "' where programpatientId = " + clientId;

        } else {
            sqlQuery = "update " + tableName + " set " + tableCol + " = '" + fieldValue
                    + "' where programpatientId = " + clientId;
        }

        Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
        query.executeUpdate();

        /* Insert the modified entry */
        if (!currFieldValue.equals(fieldValue)) {
            modifiedFields modifiedField = new modifiedFields();
            modifiedField.setFieldId(fieldId);
            modifiedField.setProgramPatientId(clientId);
            modifiedField.setSystemUserId(systemUserId);
            modifiedField.setOldFieldValue(currFieldValue);
            modifiedField.setNewFieldValue(fieldValue);

            sessionFactory.getCurrentSession().save(modifiedField);
        }
    }

    /**
     * The 'updateClient' function will update the status of the client
     * 
     * @param clientDetails The object holding the client to update
     */
    public void updateClient(programClients clientDetails) {
        sessionFactory.getCurrentSession().update(clientDetails);
    }

    /**
     * The 'getValidationType' function will return the validation type based on the id passed in.
     * 
     * @param validationId  The id of the validation
     * @return  This function will return a string (Validation type)
     * @throws Exception 
     */
    public String getValidationType(Integer validationId) throws Exception {

        Query validationType = sessionFactory.getCurrentSession()
                .createSQLQuery("select validationType from lu_validationTypes where id = " + validationId);

        if (validationType.uniqueResult() != null) {
            return validationType.uniqueResult().toString();
        } else {
            return "";
        }
    }

    /**
     * The 'getFieldModifications' function will return a list of modifications made to the passed in field for the passed in
     * client. 
     * 
     * @param programId The programId the logged in user is logged into
     * @param fieldId   The fieldId is the field to check for modifications
     * @param clientId  The cleintId is the client to check for modifications
     * @return
     * @throws Exception 
     */
    public List<modifiedFields> getFieldModifications(Integer programId, Integer fieldId, Integer clientId)
            throws Exception {
        /* Get a list of client details */
        Query q1 = sessionFactory.getCurrentSession()
                .createQuery("from modifiedFields where programPatientId = :clientId and fieldId = :fieldId");
        q1.setParameter("fieldId", fieldId);
        q1.setParameter("clientId", clientId);

        return q1.list();

    }

    /**
     * The 'mergeClientData' function will merge the existing surveys and engagements from the selected
     * similar client to the new client.
     * 
     * @param newClientData The client id of the new client
     * @param simClientData The client id of the selected similar client
     * @throws Exception 
     */
    public void mergeClientData(Integer newClientData, Integer simClientData) throws Exception {

        /* Update taken suveys */
        String sql = "";
        sql = "update survey_patientAnswers set programPatientId = " + simClientData + " where programPatientId = "
                + newClientData;
        Query update1 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        update1.executeUpdate();

        sql = "update engagementSurveys set programPatientId = " + simClientData + " where programPatientId = "
                + newClientData;
        Query update2 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        update2.executeUpdate();

        /* Update Patient Activities */
        sql = "update patientActivities set programPatientId = " + simClientData + " where programPatientId = "
                + newClientData;
        Query update3 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        update3.executeUpdate();

        /* Update Patient Counseling Appts */
        sql = "update patientCounselingAppts set programPatientId = " + simClientData + " where programPatientId = "
                + newClientData;
        Query update4 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        update4.executeUpdate();

        /* Update Patient Engagements */
        sql = "update patientEngagements set programPatientId = " + simClientData + " where programPatientId = "
                + newClientData;
        Query update5 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        update5.executeUpdate();

        /* Log the merge */
        mergeLogs log = new mergeLogs();
        log.setNewClientId(newClientData);
        log.setSimilarClientId(simClientData);
        sessionFactory.getCurrentSession().save(log);

    }

    /**
     * The 'getPatientFieldValues' function will return a list of selected values to populate the field with.
     * 
     * @param fieldId   The id of the selected field
     * @return  This function will return a list of programPatientFieldValues objects
     * @throws Exception 
     */
    public List<programPatientFieldValues> getPatientFieldValues(Integer fieldId) throws Exception {
        Query query = sessionFactory.getCurrentSession()
                .createQuery("from programPatientFieldValues where patientFieldId = :fieldId");
        query.setParameter("fieldId", fieldId);

        return query.list();
    }

    /**
     * The 'getClientEntryMethods' function will return the patient entry methods entered for a program.
     * 
     * @param programId The id of the selected program.
     * 
     * @return  This function will return a list of entry method objects
     * @throws Exception 
     */
    public List<programPatientEntryMethods> getClientEntryMethods(Integer programId) throws Exception {
        Query query = sessionFactory.getCurrentSession()
                .createQuery("from programPatientEntryMethods where programId = :programId order by displayPos");
        query.setParameter("programId", programId);

        List<programPatientEntryMethods> entryMethods = query.list();
        return entryMethods;
    }

    /**
     * 
     * @param clientNumber
     * @return
     * @throws Exception 
     */
    public Integer findExistingClient(Integer clientNumber, Integer programId) throws Exception {

        /* Update Patient Engagements */
        String sql = "select id from storage_patients where sourcePatientId = " + clientNumber
                + " and programPatientId in (select id from programPatients where programId = " + programId + ")";

        Query findClient = sessionFactory.getCurrentSession().createSQLQuery(sql);

        if (findClient.list().size() > 0) {
            return 1;
        } else {
            return 0;
        }

    }

    /**
     * The 'saveNewClient' function will save the new program client into the system and return back
     * the auto generated id.
     * 
     * @param newClient The programClients object holding the new client information
     * 
     * @return this function will return the auto id generated for the new client.
     */
    public Integer saveNewClient(programClients newClient) throws Exception {
        Integer lastId = null;

        lastId = (Integer) sessionFactory.getCurrentSession().save(newClient);

        return lastId;
    }

    /**
     * The 'savePatientClientNumber' function will submit the client number into the storage_patients table for the newly 
     * created client.
     * 
     * @param clientId  The id of the new client
     * @param clientNumber The client number (sourcePatientId) for the new client
     * 
     */
    public void savePatientClientNumber(Integer clientId, Integer clientNumber) throws Exception {

        String sql = "insert into storage_patients (programpatientId, sourcePatientId) values (" + clientId + ","
                + clientNumber + ")";

        Query insert = sessionFactory.getCurrentSession().createSQLQuery(sql);
        insert.executeUpdate();

        String addrSql = "insert into storage_patientAddressInfo (programpatientId) values (" + clientId + ")";

        Query insertAddr = sessionFactory.getCurrentSession().createSQLQuery(addrSql);
        insertAddr.executeUpdate();

    }
}