com.registryKit.client.engagementDAO.java Source code

Java tutorial

Introduction

Here is the source code for com.registryKit.client.engagementDAO.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.Arrays;
import java.util.Date;
import java.util.Iterator;
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 engagementDAO {

    @Autowired
    private SessionFactory sessionFactory;

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

        String sql = "select e.id, e.programPatientId, e.programId, e.systemUserId, e.dateCreated, CONCAT(u.firstName,' ', u.lastName) as enteredBy "
                + "from patientEngagements e inner join users u on u.id = e.systemUserId " + "where e.programId = "
                + programId + " and e.programpatientId = " + clientId;

        /* Get a list of client engagements */
        Query q1 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        q1.setResultTransformer(Transformers.aliasToBean(engagements.class));

        return q1.list();
    }

    /**
     * The 'getEngagementDetails' function will return the details of the selected engagement
     * 
     * @param engagementId The id of the selected engagement
     * @return
     * @throws Exception 
     */
    public engagements getEngagementDetails(Integer engagementId) throws Exception {
        String sql = "select e.id, e.programPatientId, e.programId, e.systemUserId, e.dateCreated, CONCAT(u.firstName,' ', u.lastName) as enteredBy "
                + "from patientEngagements e inner join users u on u.id = e.systemUserId " + "where e.id = "
                + engagementId;

        /* Get a list of client engagements */
        Query q1 = sessionFactory.getCurrentSession().createSQLQuery(sql);
        q1.setResultTransformer(Transformers.aliasToBean(engagements.class));

        return (engagements) q1.uniqueResult();
    }

    /**
     * The 'getEngagementFieldDetails' function will return the details for the passed in program engagement 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 programEngagementFields getEngagementFieldDetails(Integer programId, Integer fieldId) throws Exception {

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

        return (programEngagementFields) query.uniqueResult();

    }

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

        return q1.list();
    }

    /**
     * The 'getEngagementFields' function will return a list of engagement 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<programEngagementFields> getEngagementFields(Integer programId, Integer engagementId,
            Integer clientId) throws Exception {

        Query query = sessionFactory.getCurrentSession().createSQLQuery(
                "SELECT a.*, b.saveToTableName, b.saveToTableCol, b.answerType as fieldType FROM program_engagementFields 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(programEngagementFields.class));

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

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

            for (programEngagementFields field : fields) {

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

        return fields;

    }

    /**
     * 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
     */
    public String getTableData(String tableName, String tableCol, Integer engagementId, Integer clientId) {

        Query tableData = null;
        if (tableName.contains("patient")) {
            tableData = sessionFactory.getCurrentSession().createSQLQuery(
                    "select " + tableCol + " from " + tableName + " where programpatientId = " + clientId);
        } else {
            tableData = sessionFactory.getCurrentSession().createSQLQuery(
                    "select " + tableCol + " from " + tableName + " where engagementId = " + engagementId);
        }

        if (tableData.list().size() > 0) {

            if (tableData.list().size() > 1) {
                String valuestring = "";
                for (Iterator it = tableData.list().iterator(); it.hasNext();) {
                    valuestring += it.next();
                    if (it.hasNext()) {
                        valuestring += ",";
                    }
                }
                return valuestring;
            } else {
                if (tableData.uniqueResult() != null) {
                    return tableData.uniqueResult().toString();
                } else {
                    return "";
                }

            }
        } else {
            return "";
        }

    }

    /**
     * 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 engagementId) {

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

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

    /**
     * The 'updateEngagementFields' will update the fields from the engagement form
     * 
     * @param engagementId The id of the engagement 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 updateEngagementFields(boolean newEnagement, Integer engagementId, 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 table is a patient table */
        if (tableName.contains("patient")) {

            /* 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();
        } else {
            /* See if an entry exists in the table */
            Query findEngagement = sessionFactory.getCurrentSession()
                    .createSQLQuery("select id from " + tableName + " where engagementId = " + engagementId);

            if (findEngagement.list().size() > 0) {

                if (fieldValue != null) {

                    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 engagementId = " + engagementId;

                    } else {

                        /* If fieldValue contain multilple items then clear out the values first */
                        if (fieldValue.contains(",") && "storage_engagementMedicalServices".equals(tableName)) {
                            String deleteQuery = "delete from " + tableName + " where engagementId = "
                                    + engagementId + " and engagementFieldId = " + fieldId;

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

                            List<String> fieldValues = Arrays.asList(fieldValue.split(","));

                            sqlQuery = "insert into " + tableName + " (engagementId, engagementFieldId, codeId, "
                                    + tableCol + ") values ";

                            for (Iterator it = fieldValues.iterator(); it.hasNext();) {
                                String itValue = it.next().toString();

                                if (itValue.contains("~")) {
                                    Integer codeId = 0;
                                    String textValue = "";

                                    List<String> values = Arrays.asList(itValue.split("~"));
                                    codeId = Integer.parseInt(values.get(0));
                                    textValue = values.get(1);

                                    sqlQuery += "(" + engagementId + "," + fieldId + "," + codeId + ", '"
                                            + textValue + "')";
                                } else {
                                    sqlQuery += "(" + engagementId + "," + fieldId + ",0, '" + itValue + "')";
                                }

                                if (it.hasNext()) {
                                    sqlQuery += ",";
                                }
                            }

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

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

                    /* Insert the modified entry */
                    if (!newEnagement && !currFieldValue.equals(fieldValue)) {
                        modifiedEngagementFields modifiedField = new modifiedEngagementFields();
                        modifiedField.setFieldId(fieldId);
                        modifiedField.setEngagementId(engagementId);
                        modifiedField.setSystemUserId(systemUserId);

                        String oldFieldValue = "";
                        if (currFieldValue.contains(",")) {
                            List<String> currfieldValues = Arrays.asList(currFieldValue.split(","));

                            for (Iterator it = currfieldValues.iterator(); it.hasNext();) {

                                String itValue = it.next().toString();

                                if (itValue.contains("~")) {
                                    List<String> values = Arrays.asList(itValue.split("~"));
                                    oldFieldValue += values.get(1);
                                } else {
                                    oldFieldValue += itValue;
                                }

                                if (it.hasNext()) {
                                    oldFieldValue += ",";
                                }
                            }
                        } else {
                            oldFieldValue = currFieldValue;
                        }
                        modifiedField.setOldFieldValue(oldFieldValue);

                        String newFieldValue = "";
                        if (fieldValue.contains(",")) {
                            List<String> newfieldValues = Arrays.asList(fieldValue.split(","));

                            for (Iterator it = newfieldValues.iterator(); it.hasNext();) {

                                String itValue = it.next().toString();

                                if (itValue.contains("~")) {
                                    List<String> values = Arrays.asList(itValue.split("~"));
                                    newFieldValue += values.get(1);
                                } else {
                                    newFieldValue += itValue;
                                }

                                if (it.hasNext()) {
                                    newFieldValue += ",";
                                }
                            }
                        } else {
                            newFieldValue = fieldValue;
                        }
                        modifiedField.setNewFieldValue(newFieldValue);

                        sessionFactory.getCurrentSession().save(modifiedField);
                    }
                }
            } else {
                if (fieldType == 6) {
                    DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
                    Date date = format.parse(fieldValue);
                    Timestamp timestamp = new Timestamp(date.getTime());

                    sqlQuery = "insert into " + tableName + " (engagementId, " + tableCol + ") values ("
                            + engagementId + ",'" + timestamp + "')";
                    Query insertQuery = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
                    insertQuery.executeUpdate();

                } else {
                    sqlQuery = "insert into " + tableName + " (engagementId, " + tableCol + ") values ("
                            + engagementId + ",'" + fieldValue + "')";
                    Query insertQuery = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
                    insertQuery.executeUpdate();
                }

            }
        }

    }

    /**
     * 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 engagementId  The engagementId is the engagement to check for modifications
     * @return
     * @throws Exception 
     */
    public List<modifiedEngagementFields> getFieldModifications(Integer programId, Integer fieldId,
            Integer engagementId) throws Exception {
        /* Get a list of client details */
        Query q1 = sessionFactory.getCurrentSession().createQuery(
                "from modifiedEngagementFields where engagementId = :engagementId and fieldId = :fieldId");
        q1.setParameter("fieldId", fieldId);
        q1.setParameter("engagementId", engagementId);

        return q1.list();

    }

    /**
     * The 'getEngagementFieldValues' 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 programEngagementFieldValues objects
     * @throws Exception 
     */
    public List<programEngagementFieldValues> getEngagementFieldValues(Integer fieldId) throws Exception {
        Query query = sessionFactory.getCurrentSession()
                .createQuery("from programEngagementFieldValues where engagementFieldId = :fieldId");
        query.setParameter("fieldId", fieldId);

        return query.list();
    }

    /**
     * The 'saveEngagement' function will save the new engagement.
     * 
     * @param engagement    The object holding the engagement details
     * @return  This function will return the id assigned to the new engagement
     * @throws Exception 
     */
    public Integer saveEngagement(engagements engagement) throws Exception {
        Integer lastId = null;

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

        return lastId;
    }
}