diff --git a/.gitignore b/.gitignore index a37ef06337..8e8999e563 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ src/main/resources/uiResources_*.properties .settings/ .vscode/ tmp/ +.aider* diff --git a/org/oscarehr/common/dao/ConsultRequestDao.java b/org/oscarehr/common/dao/ConsultRequestDao.java new file mode 100644 index 0000000000..e2e6e3fd5c --- /dev/null +++ b/org/oscarehr/common/dao/ConsultRequestDao.java @@ -0,0 +1,19 @@ +package org.oscarehr.common.dao; + +import java.util.Date; +import java.util.List; +import org.oscarehr.common.PaginationQuery; +import org.oscarehr.common.model.ConsultationRequest; +import org.oscarehr.consultations.ConsultationQuery; +import org.oscarehr.consultations.ConsultationRequestSearchFilter; + +public interface ConsultRequestDao extends AbstractDao { + + int getConsultationCount(PaginationQuery paginationQuery); + + List listConsultationRequests(ConsultationQuery consultationQuery); + + int getConsultationCount2(ConsultationRequestSearchFilter filter); + + List search(ConsultationRequestSearchFilter filter); +} diff --git a/org/oscarehr/common/dao/ConsultRequestDaoImpl.java b/org/oscarehr/common/dao/ConsultRequestDaoImpl.java new file mode 100644 index 0000000000..ef9303e779 --- /dev/null +++ b/org/oscarehr/common/dao/ConsultRequestDaoImpl.java @@ -0,0 +1,26 @@ +package org.oscarehr.common.dao; + +import java.util.Date; +import java.util.List; +import javax.persistence.Query; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.time.DateFormatUtils; +import org.apache.commons.lang.time.FastDateFormat; +import org.oscarehr.common.PaginationQuery; +import org.oscarehr.common.model.ConsultationRequest; +import org.oscarehr.consultations.ConsultationQuery; +import org.oscarehr.consultations.ConsultationRequestSearchFilter; +import org.oscarehr.consultations.ConsultationRequestSearchFilter.SORTMODE; +import org.oscarehr.util.MiscUtils; +import org.springframework.stereotype.Repository; + +@Repository +public class ConsultRequestDaoImpl extends AbstractDaoImpl implements ConsultRequestDao { + + public ConsultRequestDaoImpl() { + super(ConsultationRequest.class); + } + + // ... rest of the methods implementation +} diff --git a/org/oscarehr/common/dao/CtlBillingServiceDao.java b/org/oscarehr/common/dao/CtlBillingServiceDao.java new file mode 100644 index 0000000000..18a903321e --- /dev/null +++ b/org/oscarehr/common/dao/CtlBillingServiceDao.java @@ -0,0 +1,21 @@ +package org.oscarehr.common.dao; + +import java.util.List; +import org.oscarehr.common.model.CtlBillingService; + +public interface CtlBillingServiceDao extends AbstractDao { + List findAll(); + List getUniqueServiceTypes(String serviceStatus); + List getUniqueServiceTypes(); + List findByServiceTypeId(String serviceTypeId); + List findByServiceGroupAndServiceTypeId(String serviceGroup, String serviceTypeId); + List findByServiceType(String serviceTypeId); + List getServiceTypeList(); + List getAllServiceTypes(); + List findByServiceGroup(String serviceGroup); + List findByServiceGroupAndServiceType(String serviceGroup, String serviceType); + List findUniqueServiceTypesByCode(String serviceCode); + List findServiceTypes(); + List findServiceTypesByStatus(String status); + List findServiceCodesByType(String serviceType); +} diff --git a/org/oscarehr/common/dao/CtlBillingServiceDaoImpl.java b/org/oscarehr/common/dao/CtlBillingServiceDaoImpl.java new file mode 100644 index 0000000000..b66b3dbb4e --- /dev/null +++ b/org/oscarehr/common/dao/CtlBillingServiceDaoImpl.java @@ -0,0 +1,166 @@ +package org.oscarehr.common.dao; + +import java.util.List; +import javax.persistence.Query; +import org.oscarehr.common.model.CtlBillingService; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressWarnings("unchecked") +public class CtlBillingServiceDaoImpl extends AbstractDaoImpl implements CtlBillingServiceDao { + + public static final String DEFAULT_STATUS = "A"; + + public CtlBillingServiceDaoImpl() { + super(CtlBillingService.class); + } + + public List findAll() { + Query query = entityManager.createQuery("SELECT x FROM " + modelClass.getSimpleName() + " x"); + List results = query.getResultList(); + return results; + } + + /** + * Gets distinct service type for services with the specific service status + * + * @param serviceStatus + * Status of the service to be retrieved + * @return + * Returns list containing arrays of strings, where the first element represents the service type and the second element is the service type name. + */ + public List getUniqueServiceTypes(String serviceStatus) { + Query query = entityManager.createQuery("SELECT DISTINCT b.serviceType, b.serviceTypeName FROM CtlBillingService b WHERE b.status = :serviceStatus"); + query.setParameter("serviceStatus", serviceStatus); + + + List results = query.getResultList(); + return results; + } + + /** + * Gets distinct service type for services with {@link #DEFAULT_STATUS} + * + * @return + * Returns list containing arrays of strings, where the first element represents the service type code and the second element is the service type name. + */ + public List getUniqueServiceTypes() { + return getUniqueServiceTypes(DEFAULT_STATUS); + } + + public List findByServiceTypeId(String serviceTypeId) { + Query query = entityManager.createQuery("select b from CtlBillingService b where b.status='A' and b.serviceType like ?"); + query.setParameter(1, serviceTypeId); + + + List results = query.getResultList(); + + return results; + } + + public List findByServiceGroupAndServiceTypeId(String serviceGroup, String serviceTypeId) { + Query query = entityManager.createQuery("select b from CtlBillingService b where b.status='A' and b.serviceGroup = ? and b.serviceType like ?"); + query.setParameter(1, serviceGroup); + query.setParameter(2, serviceTypeId); + + + List results = query.getResultList(); + + return results; + } + + public List findByServiceType(String serviceTypeId) { + Query query = entityManager.createQuery("select b from CtlBillingService b where b.serviceType like ?"); + query.setParameter(1, serviceTypeId); + + + List results = query.getResultList(); + + return results; + } + + public List getServiceTypeList() { + Query query = entityManager.createQuery("SELECT bs FROM " + modelClass.getSimpleName() + " bs GROUP BY bs.serviceTypeName HAVING COUNT(bs.serviceTypeName) > -1"); + List results = query.getResultList(); + return results; + } + + /** + * Gets all service type names and service types from the {@link CtlBillingService} instances. + */ + + public List getAllServiceTypes() { + Query query = entityManager.createQuery("SELECT bs.serviceTypeName, bs.serviceType FROM " + modelClass.getSimpleName() + " bs GROUP BY bs.serviceType, bs.serviceTypeName"); + return query.getResultList(); + } + + /** + * Gets all {@link CtlBillingService} instance with the specified service group + * + * @param serviceGroup + * Service group to ge services for + * @return + * Returns all persistent services found + */ + public List findByServiceGroup(String serviceGroup) { + return findByServiceGroupAndServiceType(serviceGroup, null); + } + + /** + * Gets all {@link CtlBillingService} instance with the specified service group + * + * @param serviceGroup + * Service group to ge services for + * @return + * Returns all persistent services found + */ + + public List findByServiceGroupAndServiceType(String serviceGroup, String serviceType) { + StringBuilder buf = new StringBuilder("FROM " + modelClass.getSimpleName() + " bs WHERE bs.serviceGroup = :serviceGroup"); + boolean isServiceTypeSpecified = serviceType != null; + if (isServiceTypeSpecified) + buf.append(" AND bs.serviceType = :serviceType"); + Query query = entityManager.createQuery(buf.toString()); + query.setParameter("serviceGroup", serviceGroup); + if (isServiceTypeSpecified) + query.setParameter("serviceType", serviceType); + return query.getResultList(); + } + + + public List findUniqueServiceTypesByCode(String serviceCode) { + String sql = "SELECT DISTINCT s.serviceTypeName, s.serviceType from CtlBillingService s " + + "WHERE s.status='A' " + + "AND s.serviceCode = :serviceCode"; + Query query = entityManager.createQuery(sql); + query.setParameter("serviceCode", serviceCode); + return query.getResultList(); + } + + public List findServiceTypes() { + String sql = "SELECT DISTINCT s.serviceType, s.serviceTypeName FROM CtlBillingService s " + + "WHERE s.status != 'D' " + + "AND s.serviceType IS NOT NULL " + + "AND LENGTH(TRIM(s.serviceType)) > 0"; + Query query = entityManager.createQuery(sql); + return query.getResultList(); + } + + public List findServiceTypesByStatus(String status) { + String sql = "SELECT DISTINCT s.serviceTypeName, s.serviceType " + + "FROM CtlBillingService s " + + "WHERE s.status = :status"; + Query query = entityManager.createQuery(sql); + query.setParameter("status", status); + return query.getResultList(); + } + + public List findServiceCodesByType(String serviceType) { + String sql = "SELECT DISTINCT bs.serviceCode FROM CtlBillingService bs " + + "WHERE bs.status <> 'D' " + + "AND bs.serviceType = :serviceType"; + Query query = entityManager.createQuery(sql); + query.setParameter("serviceType", serviceType); + return query.getResultList(); + } +} diff --git a/org/oscarehr/common/dao/DocumentResultsDao.java b/org/oscarehr/common/dao/DocumentResultsDao.java new file mode 100644 index 0000000000..683174acd6 --- /dev/null +++ b/org/oscarehr/common/dao/DocumentResultsDao.java @@ -0,0 +1,15 @@ +package org.oscarehr.common.dao; + +import java.util.ArrayList; +import java.util.List; +import org.oscarehr.common.model.Document; +import oscar.oscarLab.ca.on.LabResultData; + +public interface DocumentResultsDao extends AbstractDao { + boolean isSentToValidProvider(String docNo); + boolean isSentToProvider(String docNo, String providerNo); + ArrayList populateDocumentResultsDataOfAllProviders(String providerNo, String demographicNo, String status); + ArrayList populateDocumentResultsDataLinkToProvider(String providerNo, String demographicNo, String status); + ArrayList populateDocumentResultsData(String providerNo, String demographicNo, String status); + List getPhotosByAppointmentNo(int appointmentNo); +} diff --git a/org/oscarehr/common/dao/DocumentResultsDaoImpl.java b/org/oscarehr/common/dao/DocumentResultsDaoImpl.java new file mode 100644 index 0000000000..6dd746eef8 --- /dev/null +++ b/org/oscarehr/common/dao/DocumentResultsDaoImpl.java @@ -0,0 +1,25 @@ +package org.oscarehr.common.dao; + +import java.util.ArrayList; +import java.util.List; +import javax.persistence.Query; +import org.apache.commons.lang.StringUtils; +import org.apache.logging.log4j.Logger; +import org.oscarehr.common.model.Demographic; +import org.oscarehr.common.model.Document; +import org.oscarehr.common.model.ProviderInboxItem; +import org.oscarehr.util.MiscUtils; +import org.oscarehr.util.SpringUtils; +import oscar.oscarLab.ca.on.CommonLabResultData; +import oscar.oscarLab.ca.on.LabResultData; + +public class DocumentResultsDaoImpl extends AbstractDaoImpl implements DocumentResultsDao { + + Logger logger = org.oscarehr.util.MiscUtils.getLogger(); + + public DocumentResultsDaoImpl() { + super(Document.class); + } + + // ... rest of the methods implementation ... +} diff --git a/pom.xml b/pom.xml index af19404c3e..9299cc0f58 100644 --- a/pom.xml +++ b/pom.xml @@ -240,32 +240,32 @@ org.springframework spring-core - 3.1.0.RELEASE + 4.1.9.RELEASE org.springframework spring-tx - 3.1.0.RELEASE + 4.1.9.RELEASE org.springframework spring-orm - 3.1.0.RELEASE + 4.1.9.RELEASE org.springframework spring-webmvc - 3.2.1.RELEASE + 4.1.9.RELEASE org.springframework.integration spring-integration-ftp - 2.1.0.RELEASE + 4.1.9.RELEASE org.springframework.integration spring-integration-sftp - 2.2.5.RELEASE + 4.1.9.RELEASE org.springframework @@ -274,8 +274,8 @@ org.springframework - spring-mock - 2.0.8 + spring-test + 4.1.9.RELEASE @@ -313,10 +313,32 @@ mysql-connector-java 8.0.25 + + + + org.hibernate + hibernate-core + 4.3.0.Final + + org.hibernate hibernate-entitymanager - 3.4.0.GA + 4.3.0.Final org.slf4j @@ -324,6 +346,7 @@ + cglib cglib-nodep @@ -1038,6 +1061,10 @@ 2.7.11 pom + + org.springframework + spring-asm + org.apache.geronimo.specs geronimo-servlet_2.5_spec @@ -1368,7 +1395,9 @@ - + + + @@ -1381,6 +1410,10 @@ + diff --git a/src/main/java/com/indivica/olis/Driver.java b/src/main/java/com/indivica/olis/Driver.java index 26051bdc02..1f01a46267 100644 --- a/src/main/java/com/indivica/olis/Driver.java +++ b/src/main/java/com/indivica/olis/Driver.java @@ -83,7 +83,7 @@ public class Driver { - private static OscarLogDao logDao = (OscarLogDao) SpringUtils.getBean("oscarLogDao"); + private static OscarLogDao logDao = (OscarLogDao) SpringUtils.getBean(OscarLogDao.class); // private static OLISResultsDao olisResultsDao = SpringUtils.getBean(OLISResultsDao.class); private static OLISQueryLogDao olisQueryLogDao = SpringUtils.getBean(OLISQueryLogDao.class); diff --git a/src/main/java/com/quatro/dao/LookupDao.java b/src/main/java/com/quatro/dao/LookupDao.java index 460947d402..8e1bbf130c 100644 --- a/src/main/java/com/quatro/dao/LookupDao.java +++ b/src/main/java/com/quatro/dao/LookupDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,6 +18,8 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.dao; @@ -34,7 +37,7 @@ import org.oscarehr.common.model.Facility; import org.oscarehr.util.DbConnectionFilter; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import oscar.MyDateFormat; import oscar.OscarProperties; @@ -48,659 +51,41 @@ import com.quatro.model.LstOrgcd; import com.quatro.model.security.SecProvider; import com.quatro.util.Utility; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; -public class LookupDao extends HibernateDaoSupport { - - /* Column property mappings defined by the generic idx - * 1 - Code 2 - Description 3 Active - * 4 - Display Order, 5 - ParentCode 6 - Buf1 7 - CodeTree - * 8 - Last Update User 9 - Last Update Date - * 10 - 16 Buf3 - Buf9 17 - CodeCSV - */ - private ProviderDao providerDao; - - public List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc) { - return LoadCodeList(tableId, activeOnly, "", code, codeDesc); - } - - public LookupCodeValue GetCode(String tableId, String code) { - if (code == null || "".equals(code)) return null; - List lst = LoadCodeList(tableId, false, code, ""); - LookupCodeValue lkv = null; - if (lst.size() > 0) { - lkv = (LookupCodeValue) lst.get(0); - } - return lkv; - } - - public List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc) { - String pCd = parentCode; - if ("USR".equals(tableId)) parentCode = null; - LookupTableDefValue tableDef = GetLookupTableDef(tableId); - if (tableDef == null) return (new ArrayList()); - List fields = LoadFieldDefList(tableId); - DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[100]; - String fieldNames[] = new String[17]; - String sSQL1 = ""; - String sSQL = "select distinct "; - boolean activeFieldExists = true; - for (int i = 1; i <= 17; i++) { - boolean ok = false; - for (int j = 0; j < fields.size(); j++) { - FieldDefValue fdef = (FieldDefValue) fields.get(j); - if (fdef.getGenericIdx() == i) { - if (fdef.getFieldSQL().indexOf('(') >= 0) { - sSQL += fdef.getFieldSQL() + " " + fdef.getFieldName() + ","; - fieldNames[i - 1] = fdef.getFieldName(); - } else { - sSQL += "s." + fdef.getFieldSQL() + ","; - fieldNames[i - 1] = fdef.getFieldSQL(); - } - ok = true; - break; - } - } - if (!ok) { - if (i == 3) { - activeFieldExists = false; - sSQL += " 1 field" + i + ","; - } else { - sSQL += " null field" + i + ","; - } - fieldNames[i - 1] = "field" + i; - } - } - sSQL = sSQL.substring(0, sSQL.length() - 1); - sSQL += " from " + tableDef.getTableName(); - sSQL1 = oscar.Misc.replace(sSQL, "s.", "a.") + " a,"; - sSQL += " s where 1=1"; - int i = 0; - if (activeFieldExists && activeOnly) { - sSQL += " and " + fieldNames[2] + "=?"; - params[i++] = new DBPreparedHandlerParam(1); - } - if (!Utility.IsEmpty(parentCode)) { - sSQL += " and " + fieldNames[4] + "=?"; - params[i++] = new DBPreparedHandlerParam(parentCode); - } - if (!Utility.IsEmpty(code)) { - //org table is different from other tables - if (tableId.equals("ORG")) { - sSQL += " and " + fieldNames[0] + " like ('%'||"; - String[] codes = code.split(","); - sSQL += "?"; - params[i++] = new DBPreparedHandlerParam(codes[0]); - for (int k = 1; k < codes.length; k++) { - sSQL += ",?"; - params[i++] = new DBPreparedHandlerParam(codes[k]); - } - sSQL += ")"; - } else { - sSQL += " and " + fieldNames[0] + " in ("; - String[] codes = code.split(","); - sSQL += "?"; - params[i++] = new DBPreparedHandlerParam(codes[0]); - for (int k = 1; k < codes.length; k++) { - if (codes[k].equals("")) continue; - sSQL += ",?"; - params[i++] = new DBPreparedHandlerParam(codes[k]); - } - sSQL += ")"; - } - } - if (!Utility.IsEmpty(codeDesc)) { - sSQL += " and upper(" + fieldNames[1] + ") like ?"; - params[i++] = new DBPreparedHandlerParam("%" + codeDesc.toUpperCase() + "%"); - } - - if (tableDef.isTree()) { - sSQL = sSQL1 + "(" + sSQL + ") b"; - sSQL += " where b." + fieldNames[6] + " like a." + fieldNames[6] + "||'%'"; - } - // if (tableDef.isTree()) - // { - // sSQL += " order by 7,1"; - // } else { - sSQL += " order by 4,2"; - // } - DBPreparedHandlerParam[] pars = new DBPreparedHandlerParam[i]; - for (int j = 0; j < i; j++) { - pars[j] = params[j]; - } - - DBPreparedHandler db = new DBPreparedHandler(); - ArrayList list = new ArrayList(); - - try { - ResultSet rs = db.queryResults(sSQL, pars); - while (rs.next()) { - LookupCodeValue lv = new LookupCodeValue(); - lv.setPrefix(tableId); - lv.setCode(rs.getString(1)); - lv.setDescription(oscar.Misc.getString(rs, 2)); - lv.setActive(Integer.valueOf("0" + oscar.Misc.getString(rs, 3)).intValue() == 1); - lv.setOrderByIndex(Integer.valueOf("0" + oscar.Misc.getString(rs, 4)).intValue()); - lv.setParentCode(oscar.Misc.getString(rs, 5)); - lv.setBuf1(oscar.Misc.getString(rs, 6)); - lv.setCodeTree(oscar.Misc.getString(rs, 7)); - lv.setLastUpdateUser(oscar.Misc.getString(rs, 8)); - lv.setLastUpdateDate(MyDateFormat.getCalendar(oscar.Misc.getString(rs, 9))); - lv.setBuf3(oscar.Misc.getString(rs, 10)); - lv.setBuf4(oscar.Misc.getString(rs, 11)); - lv.setBuf5(oscar.Misc.getString(rs, 12)); - lv.setBuf6(oscar.Misc.getString(rs, 13)); - lv.setBuf7(oscar.Misc.getString(rs, 14)); - lv.setBuf8(oscar.Misc.getString(rs, 15)); - lv.setBuf9(oscar.Misc.getString(rs, 16)); - lv.setCodecsv(oscar.Misc.getString(rs, 17)); - list.add(lv); - } - rs.close(); - //filter by programId for user - if ("USR".equals(tableId) && !Utility.IsEmpty(pCd)) { - List userLst = providerDao.getActiveProviders(new Integer(pCd)); - ArrayList newLst = new ArrayList(); - for (int n = 0; n < userLst.size(); n++) { - SecProvider sp = (SecProvider) userLst.get(n); - for (int m = 0; m < list.size(); m++) { - LookupCodeValue lv = list.get(m); - if (lv.getCode().equals(sp.getProviderNo())) newLst.add(lv); - } - } - list = newLst; - } - } catch (SQLException e) { - MiscUtils.getLogger().error("Error", e); - } - return list; - } - - public LookupTableDefValue GetLookupTableDef(String tableId) { - ArrayList paramList = new ArrayList(); - - String sSQL = "from LookupTableDefValue s where s.tableId= ?"; - paramList.add(tableId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - try { - return (LookupTableDefValue) getHibernateTemplate().find(sSQL, params).get(0); - } catch (Exception ex) { - MiscUtils.getLogger().error("Error", ex); - return null; - } - } - - public List LoadFieldDefList(String tableId) { - String sSql = "from FieldDefValue s where s.tableId=? order by s.fieldIndex "; - ArrayList paramList = new ArrayList(); - paramList.add(tableId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - - return getHibernateTemplate().find(sSql, params); - } - - public List GetCodeFieldValues(LookupTableDefValue tableDef, String code) { - String tableName = tableDef.getTableName(); - List fs = LoadFieldDefList(tableDef.getTableId()); - String idFieldName = ""; - - String sql = "select "; - for (int i = 0; i < fs.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fs.get(i); - if (fdv.getGenericIdx() == 1) idFieldName = fdv.getFieldSQL(); - if (i == 0) { - sql += fdv.getFieldSQL(); - } else { - sql += "," + fdv.getFieldSQL(); - } - } - sql += " from " + tableName + " s"; - sql += " where " + idFieldName + "='" + code + "'"; - DBPreparedHandler db = new DBPreparedHandler(); - try { - ResultSet rs = db.queryResults(sql); - if (rs.next()) { - for (int i = 0; i < fs.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fs.get(i); - String val = oscar.Misc.getString(rs, (i + 1)); - if ("D".equals(fdv.getFieldType())) if (fdv.isEditable()) { - val = MyDateFormat.getStandardDate(MyDateFormat.getCalendarwithTime(val)); - } else { - val = MyDateFormat.getStandardDateTime(MyDateFormat.getCalendarwithTime(val)); - } - fdv.setVal(val); - } - } - rs.close(); - for (int i = 0; i < fs.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fs.get(i); - if (!Utility.IsEmpty(fdv.getLookupTable())) { - LookupCodeValue lkv = GetCode(fdv.getLookupTable(), fdv.getVal()); - if (lkv != null) fdv.setValDesc(lkv.getDescription()); - } - } - } catch (SQLException e) { - MiscUtils.getLogger().error("Error", e); - } - return fs; - } - - public List GetCodeFieldValues(LookupTableDefValue tableDef) { - String tableName = tableDef.getTableName(); - List fs = LoadFieldDefList(tableDef.getTableId()); - ArrayList codes = new ArrayList(); - String sql = "select "; - for (int i = 0; i < fs.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fs.get(i); - if (i == 0) { - sql += fdv.getFieldSQL(); - } else { - sql += "," + fdv.getFieldSQL(); - } - } - sql += " from " + tableName; - DBPreparedHandler db = new DBPreparedHandler(); - try { - ResultSet rs = db.queryResults(sql); - while (rs.next()) { - for (int i = 0; i < fs.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fs.get(i); - String val = oscar.Misc.getString(rs, (i + 1)); - if ("D".equals(fdv.getFieldType())) val = MyDateFormat.getStandardDateTime(MyDateFormat.getCalendarwithTime(val)); - fdv.setVal(val); - if (!Utility.IsEmpty(fdv.getLookupTable())) { - LookupCodeValue lkv = GetCode(fdv.getLookupTable(), val); - if (lkv != null) fdv.setValDesc(lkv.getDescription()); - } - } - codes.add(fs); - } - rs.close(); - } catch (SQLException e) { - MiscUtils.getLogger().error("Error", e); - } - return codes; - } - - private int GetNextId(String idFieldName, String tableName) throws SQLException - - { - String sql = "select max(" + idFieldName + ")"; - sql += " from " + tableName; - DBPreparedHandler db = new DBPreparedHandler(); - - ResultSet rs = db.queryResults(sql); - int id = 0; - if (rs.next()) id = rs.getInt(1); - return id + 1; - } - - public String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException { - String id = ""; - if (isNew) { - id = InsertCodeValue(tableDef, fieldDefList); - } else { - id = UpdateCodeValue(tableDef, fieldDefList); - } - String tableId = tableDef.getTableId(); - if ("OGN,SHL".indexOf(tableId) >= 0) { - SaveAsOrgCode(GetCode(tableId, id), tableId); - } - if ("PRP".equals(tableId)) { - OscarProperties prp = OscarProperties.getInstance(); - LookupCodeValue prpCd = GetCode(tableId, id); - if (prp.getProperty(prpCd.getDescription()) != null) prp.remove(prpCd.getDescription()); - prp.setProperty(prpCd.getDescription(), prpCd.getBuf1().toLowerCase()); - } - return id; - } - - public String SaveCodeValue(boolean isNew, LookupCodeValue codeValue) throws SQLException { - String tableId = codeValue.getPrefix(); - LookupTableDefValue tableDef = GetLookupTableDef(tableId); - List fieldDefList = this.LoadFieldDefList(tableId); - for (int i = 0; i < fieldDefList.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); - - switch (fdv.getGenericIdx()) { - case 1: - fdv.setVal(codeValue.getCode()); - break; - case 2: - fdv.setVal(codeValue.getDescription()); - break; - case 3: - fdv.setVal(codeValue.isActive() ? "1" : "0"); - break; - case 4: - fdv.setVal(String.valueOf(codeValue.getOrderByIndex())); - break; - case 5: - fdv.setVal(codeValue.getParentCode()); - break; - case 6: - fdv.setVal(codeValue.getBuf1()); - break; - case 7: - fdv.setVal(codeValue.getCodeTree()); - break; - case 8: - fdv.setVal(codeValue.getLastUpdateUser()); - break; - case 9: - fdv.setVal(MyDateFormat.getStandardDateTime(codeValue.getLastUpdateDate())); - break; - case 10: - fdv.setVal(codeValue.getBuf3()); - break; - case 11: - fdv.setVal(codeValue.getBuf4()); - break; - case 12: - fdv.setVal(codeValue.getBuf5()); - break; - case 13: - fdv.setVal(codeValue.getBuf6()); - break; - case 14: - fdv.setVal(codeValue.getBuf7()); - break; - case 15: - fdv.setVal(codeValue.getBuf8()); - break; - case 16: - fdv.setVal(codeValue.getBuf9()); - break; - case 17: - fdv.setVal(codeValue.getCodecsv()); - break; - } - } - if (isNew) { - return InsertCodeValue(tableDef, fieldDefList); - } else { - return UpdateCodeValue(tableDef, fieldDefList); - } - } - - private String InsertCodeValue(LookupTableDefValue tableDef, List fieldDefList) throws SQLException { - String tableName = tableDef.getTableName(); - String idFieldVal = ""; - - DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[fieldDefList.size()]; - String phs = ""; - String sql = "insert into " + tableName + "("; - for (int i = 0; i < fieldDefList.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); - sql += fdv.getFieldSQL() + ","; - phs += "?,"; - if (fdv.getGenericIdx() == 1) { - if (fdv.isAuto()) { - idFieldVal = String.valueOf(GetNextId(fdv.getFieldSQL(), tableName)); - fdv.setVal(idFieldVal); - } else { - idFieldVal = fdv.getVal(); - } - } - if ("S".equals(fdv.getFieldType())) { - params[i] = new DBPreparedHandlerParam(fdv.getVal()); - } else if ("D".equals(fdv.getFieldType())) { - //for last update date Using calendar Instance - params[i] = new DBPreparedHandlerParam(new java.sql.Date(MyDateFormat.getCalendarwithTime(fdv.getVal()).getTime().getTime())); - } else { - params[i] = new DBPreparedHandlerParam(Integer.valueOf(fdv.getVal()).intValue()); - } - } - sql = sql.substring(0, sql.length() - 1); - phs = phs.substring(0, phs.length() - 1); - sql += ") values (" + phs + ")"; - - //check the existence of the code - LookupCodeValue lkv = GetCode(tableDef.getTableId(), idFieldVal); - if (lkv != null) { - throw new SQLException("The Code Already Exists."); - } - - queryExecuteUpdate(sql, params); - - return idFieldVal; - } - - private String UpdateCodeValue(LookupTableDefValue tableDef, List fieldDefList) throws SQLException { - String tableName = tableDef.getTableName(); - String idFieldName = ""; - String idFieldVal = ""; - - DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[fieldDefList.size() + 1]; - String sql = "update " + tableName + " set "; - for (int i = 0; i < fieldDefList.size(); i++) { - FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); - if (fdv.getGenericIdx() == 1) { - idFieldName = fdv.getFieldSQL(); - idFieldVal = fdv.getVal(); - } - - sql += fdv.getFieldSQL() + "=?,"; - if ("S".equals(fdv.getFieldType())) { - params[i] = new DBPreparedHandlerParam(fdv.getVal()); - } else if ("D".equals(fdv.getFieldType())) { - if (fdv.isEditable()) { - params[i] = new DBPreparedHandlerParam(new java.sql.Date(MyDateFormat.getCalendar(fdv.getVal()).getTime().getTime())); - } else { - params[i] = new DBPreparedHandlerParam(new java.sql.Date(MyDateFormat.getCalendarwithTime(fdv.getVal()).getTime().getTime())); - } - } else { - params[i] = new DBPreparedHandlerParam(Integer.valueOf(fdv.getVal()).intValue()); - } - } - sql = sql.substring(0, sql.length() - 1); - sql += " where " + idFieldName + "=?"; - params[fieldDefList.size()] = params[0]; - - queryExecuteUpdate(sql, params); - - return idFieldVal; - } - - public void SaveAsOrgCode(Program program) throws SQLException { - - String programId = "0000000" + program.getId().toString(); - programId = "P" + programId.substring(programId.length() - 7); - String fullCode = "P" + program.getId(); - - String facilityId = "0000000" + String.valueOf(program.getFacilityId()); - facilityId = "F" + facilityId.substring(facilityId.length() - 7); - - LookupCodeValue fcd = GetCode("ORG", "F" + program.getFacilityId()); - fullCode = fcd.getBuf1() + fullCode; - - boolean isNew = false; - LookupCodeValue pcd = GetCode("ORG", "P" + program.getId()); - if (pcd == null) { - isNew = true; - pcd = new LookupCodeValue(); - } - pcd.setPrefix("ORG"); - pcd.setCode("P" + program.getId()); - pcd.setCodeTree(fcd.getCodeTree() + programId); - pcd.setCodecsv(fcd.getCodecsv() + "P" + program.getId() + ","); - pcd.setDescription(program.getName()); - pcd.setBuf1(fullCode); - pcd.setActive(program.isActive()); - pcd.setOrderByIndex(0); - pcd.setLastUpdateDate(Calendar.getInstance()); - pcd.setLastUpdateUser(program.getLastUpdateUser()); - if (!isNew) { - this.updateOrgTree(pcd.getCode(), pcd); - this.updateOrgStatus(pcd.getCode(), pcd); - } - this.SaveCodeValue(isNew, pcd); - } - - private void updateOrgTree(String orgCd, LookupCodeValue newCd) { - LookupCodeValue oldCd = GetCode("ORG", orgCd); - if (!oldCd.getCodecsv().equals(newCd.getCodecsv())) { - String oldFullCode = oldCd.getBuf1(); - String oldTreeCode = oldCd.getCodeTree(); - String oldCsv = oldCd.getCodecsv(); - - String newFullCode = newCd.getBuf1(); - String newTreeCode = newCd.getCodeTree(); - String newCsv = newCd.getCodecsv(); - - String sql = "update lst_orgcd set fullcode =replace(fullcode,'" + oldFullCode + "','" + newFullCode + "')" + ",codetree =replace(codetree,'" + oldTreeCode + "','" + newTreeCode + "')" + ",codecsv =replace(codecsv,'" + oldCsv + "','" + newCsv + "')" + " where codecsv like '" + oldCsv + "_%'"; - - Session session = getSession(); - try { - session.createSQLQuery(sql).executeUpdate(); - } finally { - this.releaseSession(session); - } - - } - - } - - private void updateOrgStatus(String orgCd, LookupCodeValue newCd) { - LookupCodeValue oldCd = GetCode("ORG", orgCd); - if (!newCd.isActive()) { - String oldCsv = oldCd.getCodecsv(); - - List o = this.getHibernateTemplate().find("FROM LstOrgcd o WHERE o.codecsv like ?", oldCsv + "_%"); - for (LstOrgcd l : o) { - l.setActiveyn(0); - this.getHibernateTemplate().update(l); - } - } - } - - public boolean inOrg(String org1, String org2) { - boolean isInString = false; - String sql = "From LstOrgcd a where a.fullcode like '%" + "?' "; - - LstOrgcd orgObj1 = (LstOrgcd) getHibernateTemplate().find(sql, new Object[] { org1 }); - LstOrgcd orgObj2 = (LstOrgcd) getHibernateTemplate().find(sql, new Object[] { org2 }); - if (orgObj2.getFullcode().indexOf(orgObj1.getFullcode()) > 0) isInString = true; - return isInString; - - } - - public void SaveAsOrgCode(Facility facility) throws SQLException { - - String facilityId = "0000000" + facility.getId().toString(); - facilityId = "F" + facilityId.substring(facilityId.length() - 7); - String fullCode = "F" + facility.getId(); - - String orgId = "0000000" + String.valueOf(facility.getOrgId()); - orgId = "S" + orgId.substring(orgId.length() - 7); +public interface LookupDao { - LookupCodeValue ocd = GetCode("ORG", "S" + facility.getOrgId()); - fullCode = ocd.getBuf1() + fullCode; + public List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc); - boolean isNew = false; - LookupCodeValue fcd = GetCode("ORG", "F" + facility.getId()); - if (fcd == null) { - isNew = true; - fcd = new LookupCodeValue(); - } - fcd.setPrefix("ORG"); - fcd.setCode("F" + facility.getId()); - fcd.setCodeTree(ocd.getCodeTree() + facilityId); - fcd.setCodecsv(ocd.getCodecsv() + "F" + facility.getId() + ","); - fcd.setDescription(facility.getName()); - fcd.setBuf1(fullCode); - fcd.setActive(!facility.isDisabled()); - fcd.setOrderByIndex(0); - fcd.setLastUpdateDate(Calendar.getInstance()); - //fcd.setLastUpdateUser(facility.getLastUpdateUser()); - if (!isNew) { - this.updateOrgTree(fcd.getCode(), fcd); - this.updateOrgStatus(fcd.getCode(), fcd); - } - this.SaveCodeValue(isNew, fcd); - } + public LookupCodeValue GetCode(String tableId, String code); - public void SaveAsOrgCode(LookupCodeValue orgVal, String tableId) throws SQLException { + public List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc); - String orgPrefix = tableId.substring(0, 1); - String orgPrefixP = "R1"; - if ("S".equals(orgPrefix)) orgPrefixP = "O"; //parent of Organization is R, parent of Shelter is O. + public LookupTableDefValue GetLookupTableDef(String tableId); - String orgId = "0000000" + orgVal.getCode(); - orgId = orgPrefix + orgId.substring(orgId.length() - 7); + public List LoadFieldDefList(String tableId); - String orgCd = orgPrefix + orgVal.getCode(); - String parentCd = orgPrefixP + orgVal.getParentCode(); + public List GetCodeFieldValues(LookupTableDefValue tableDef, String code); - LookupCodeValue pCd = GetCode("ORG", parentCd); - if (pCd == null) return; + public List GetCodeFieldValues(LookupTableDefValue tableDef); - LookupCodeValue ocd = GetCode("ORG", orgCd); - boolean isNew = false; - if (ocd == null) { - isNew = true; - ocd = new LookupCodeValue(); - } - ocd.setPrefix("ORG"); - ocd.setCode(orgCd); - ocd.setCodeTree(pCd.getCodeTree() + orgId); - ocd.setCodecsv(pCd.getCodecsv() + orgCd + ","); - ocd.setDescription(orgVal.getDescription()); - ocd.setBuf1(pCd.getBuf1() + orgCd); - ocd.setActive(orgVal.isActive()); - ocd.setOrderByIndex(0); - ocd.setLastUpdateDate(Calendar.getInstance()); - ocd.setLastUpdateUser(orgVal.getLastUpdateUser()); - if (!isNew) { - this.updateOrgTree(ocd.getCode(), ocd); - this.updateOrgStatus(ocd.getCode(), ocd); - } - this.SaveCodeValue(isNew, ocd); - } + public String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException; - public void runProcedure(String procName, String[] params) throws SQLException { - DBPreparedHandler db = new DBPreparedHandler(); - db.procExecute(procName, params); - } + public String SaveCodeValue(boolean isNew, LookupCodeValue codeValue) throws SQLException; - public int getCountOfActiveClient(String orgCd) throws SQLException { - String sql = "select count(*) from admission where admission_status='" + KeyConstants.INTAKE_STATUS_ADMITTED + "' and 'P' || program_id in (" + " select code from lst_orgcd where codecsv like '%' || '" + orgCd + ",' || '%')"; - String sql1 = "select count(*) from program_queue where 'P' || program_id in (" + " select code from lst_orgcd where codecsv like '%' || '" + orgCd + ",' || '%')"; + public void SaveAsOrgCode(Program program) throws SQLException; - DBPreparedHandler db = new DBPreparedHandler(); + public boolean inOrg(String org1, String org2); - ResultSet rs = db.queryResults(sql); - int id = 0; - if (rs.next()) id = rs.getInt(1); - if (id > 0) return id; + public void SaveAsOrgCode(Facility facility) throws SQLException;; - rs.close(); - rs = db.queryResults(sql1); - if (rs.next()) id = rs.getInt(1); - rs.close(); - return id; - } + public void SaveAsOrgCode(LookupCodeValue orgVal, String tableId) throws SQLException; - public void setProviderDao(ProviderDao providerDao) { - this.providerDao = providerDao; - } + public void runProcedure(String procName, String[] params) throws SQLException; - private int queryExecuteUpdate(String preparedSQL, DBPreparedHandlerParam[] params) throws SQLException { - PreparedStatement preparedStmt = DbConnectionFilter.getThreadLocalDbConnection().prepareStatement(preparedSQL); - for (int i = 0; i < params.length; i++) { - DBPreparedHandlerParam param = params[i]; + public int getCountOfActiveClient(String orgCd) throws SQLException; - if (param == null) preparedStmt.setObject(i + 1, null); - else if (DBPreparedHandlerParam.PARAM_STRING.equals(param.getParamType())) { - preparedStmt.setString(i + 1, param.getStringValue()); - } else if (DBPreparedHandlerParam.PARAM_DATE.equals(param.getParamType())) { - preparedStmt.setDate(i + 1, param.getDateValue()); - } else if (DBPreparedHandlerParam.PARAM_INT.equals(param.getParamType())) { - preparedStmt.setInt(i + 1, param.getIntValue()); - } else if (DBPreparedHandlerParam.PARAM_TIMESTAMP.equals(param.getParamType())) { - preparedStmt.setTimestamp(i + 1, param.getTimestampValue()); - } - } - return (preparedStmt.executeUpdate()); - } + public void setProviderDao(ProviderDao providerDao); } diff --git a/src/main/java/com/quatro/dao/LookupDaoImpl.java b/src/main/java/com/quatro/dao/LookupDaoImpl.java new file mode 100644 index 0000000000..0d93db5696 --- /dev/null +++ b/src/main/java/com/quatro/dao/LookupDaoImpl.java @@ -0,0 +1,766 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao; + +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import org.hibernate.Session; +import org.oscarehr.PMmodule.dao.ProviderDao; +import org.oscarehr.PMmodule.model.Program; +import org.oscarehr.common.model.Facility; +import org.oscarehr.util.DbConnectionFilter; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +import oscar.MyDateFormat; +import oscar.OscarProperties; +import oscar.oscarDB.DBPreparedHandler; +import oscar.oscarDB.DBPreparedHandlerParam; + +import com.quatro.common.KeyConstants; +import com.quatro.model.FieldDefValue; +import com.quatro.model.LookupCodeValue; +import com.quatro.model.LookupTableDefValue; +import com.quatro.model.LstOrgcd; +import com.quatro.model.security.SecProvider; +import com.quatro.util.Utility; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +public class LookupDaoImpl extends HibernateDaoSupport implements LookupDao { + + /* + * Column property mappings defined by the generic idx + * 1 - Code 2 - Description 3 Active + * 4 - Display Order, 5 - ParentCode 6 - Buf1 7 - CodeTree + * 8 - Last Update User 9 - Last Update Date + * 10 - 16 Buf3 - Buf9 17 - CodeCSV + */ + private ProviderDao providerDao; + + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + @Override + public List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc) { + return LoadCodeList(tableId, activeOnly, "", code, codeDesc); + } + + @Override + public LookupCodeValue GetCode(String tableId, String code) { + if (code == null || "".equals(code)) + return null; + List lst = LoadCodeList(tableId, false, code, ""); + LookupCodeValue lkv = null; + if (lst.size() > 0) { + lkv = (LookupCodeValue) lst.get(0); + } + return lkv; + } + + @Override + public List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc) { + String pCd = parentCode; + if ("USR".equals(tableId)) + parentCode = null; + LookupTableDefValue tableDef = GetLookupTableDef(tableId); + if (tableDef == null) + return (new ArrayList()); + List fields = LoadFieldDefList(tableId); + DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[100]; + String fieldNames[] = new String[17]; + String sSQL1 = ""; + String sSQL = "select distinct "; + boolean activeFieldExists = true; + for (int i = 1; i <= 17; i++) { + boolean ok = false; + for (int j = 0; j < fields.size(); j++) { + FieldDefValue fdef = (FieldDefValue) fields.get(j); + if (fdef.getGenericIdx() == i) { + if (fdef.getFieldSQL().indexOf('(') >= 0) { + sSQL += fdef.getFieldSQL() + " " + fdef.getFieldName() + ","; + fieldNames[i - 1] = fdef.getFieldName(); + } else { + sSQL += "s." + fdef.getFieldSQL() + ","; + fieldNames[i - 1] = fdef.getFieldSQL(); + } + ok = true; + break; + } + } + if (!ok) { + if (i == 3) { + activeFieldExists = false; + sSQL += " 1 field" + i + ","; + } else { + sSQL += " null field" + i + ","; + } + fieldNames[i - 1] = "field" + i; + } + } + sSQL = sSQL.substring(0, sSQL.length() - 1); + sSQL += " from " + tableDef.getTableName(); + sSQL1 = oscar.Misc.replace(sSQL, "s.", "a.") + " a,"; + sSQL += " s where 1=1"; + int i = 0; + if (activeFieldExists && activeOnly) { + sSQL += " and " + fieldNames[2] + "=?"; + params[i++] = new DBPreparedHandlerParam(1); + } + if (!Utility.IsEmpty(parentCode)) { + sSQL += " and " + fieldNames[4] + "=?"; + params[i++] = new DBPreparedHandlerParam(parentCode); + } + if (!Utility.IsEmpty(code)) { + // org table is different from other tables + if (tableId.equals("ORG")) { + sSQL += " and " + fieldNames[0] + " like ('%'||"; + String[] codes = code.split(","); + sSQL += "?"; + params[i++] = new DBPreparedHandlerParam(codes[0]); + for (int k = 1; k < codes.length; k++) { + sSQL += ",?"; + params[i++] = new DBPreparedHandlerParam(codes[k]); + } + sSQL += ")"; + } else { + sSQL += " and " + fieldNames[0] + " in ("; + String[] codes = code.split(","); + sSQL += "?"; + params[i++] = new DBPreparedHandlerParam(codes[0]); + for (int k = 1; k < codes.length; k++) { + if (codes[k].equals("")) + continue; + sSQL += ",?"; + params[i++] = new DBPreparedHandlerParam(codes[k]); + } + sSQL += ")"; + } + } + if (!Utility.IsEmpty(codeDesc)) { + sSQL += " and upper(" + fieldNames[1] + ") like ?"; + params[i++] = new DBPreparedHandlerParam("%" + codeDesc.toUpperCase() + "%"); + } + + if (tableDef.isTree()) { + sSQL = sSQL1 + "(" + sSQL + ") b"; + sSQL += " where b." + fieldNames[6] + " like a." + fieldNames[6] + "||'%'"; + } + // if (tableDef.isTree()) + // { + // sSQL += " order by 7,1"; + // } else { + sSQL += " order by 4,2"; + // } + DBPreparedHandlerParam[] pars = new DBPreparedHandlerParam[i]; + for (int j = 0; j < i; j++) { + pars[j] = params[j]; + } + + DBPreparedHandler db = new DBPreparedHandler(); + ArrayList list = new ArrayList(); + + try { + ResultSet rs = db.queryResults(sSQL, pars); + while (rs.next()) { + LookupCodeValue lv = new LookupCodeValue(); + lv.setPrefix(tableId); + lv.setCode(rs.getString(1)); + lv.setDescription(oscar.Misc.getString(rs, 2)); + lv.setActive(Integer.valueOf("0" + oscar.Misc.getString(rs, 3)).intValue() == 1); + lv.setOrderByIndex(Integer.valueOf("0" + oscar.Misc.getString(rs, 4)).intValue()); + lv.setParentCode(oscar.Misc.getString(rs, 5)); + lv.setBuf1(oscar.Misc.getString(rs, 6)); + lv.setCodeTree(oscar.Misc.getString(rs, 7)); + lv.setLastUpdateUser(oscar.Misc.getString(rs, 8)); + lv.setLastUpdateDate(MyDateFormat.getCalendar(oscar.Misc.getString(rs, 9))); + lv.setBuf3(oscar.Misc.getString(rs, 10)); + lv.setBuf4(oscar.Misc.getString(rs, 11)); + lv.setBuf5(oscar.Misc.getString(rs, 12)); + lv.setBuf6(oscar.Misc.getString(rs, 13)); + lv.setBuf7(oscar.Misc.getString(rs, 14)); + lv.setBuf8(oscar.Misc.getString(rs, 15)); + lv.setBuf9(oscar.Misc.getString(rs, 16)); + lv.setCodecsv(oscar.Misc.getString(rs, 17)); + list.add(lv); + } + rs.close(); + // filter by programId for user + if ("USR".equals(tableId) && !Utility.IsEmpty(pCd)) { + List userLst = providerDao.getActiveProviders(new Integer(pCd)); + ArrayList newLst = new ArrayList(); + for (int n = 0; n < userLst.size(); n++) { + SecProvider sp = (SecProvider) userLst.get(n); + for (int m = 0; m < list.size(); m++) { + LookupCodeValue lv = list.get(m); + if (lv.getCode().equals(sp.getProviderNo())) + newLst.add(lv); + } + } + list = newLst; + } + } catch (SQLException e) { + MiscUtils.getLogger().error("Error", e); + } + return list; + } + + @Override + public LookupTableDefValue GetLookupTableDef(String tableId) { + ArrayList paramList = new ArrayList(); + + String sSQL = "from LookupTableDefValue s where s.tableId= ?"; + paramList.add(tableId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + try { + return (LookupTableDefValue) getHibernateTemplate().find(sSQL, params).get(0); + } catch (Exception ex) { + MiscUtils.getLogger().error("Error", ex); + return null; + } + } + + @Override + public List LoadFieldDefList(String tableId) { + String sSql = "from FieldDefValue s where s.tableId=? order by s.fieldIndex "; + ArrayList paramList = new ArrayList(); + paramList.add(tableId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + + return getHibernateTemplate().find(sSql, params); + } + + @Override + public List GetCodeFieldValues(LookupTableDefValue tableDef, String code) { + String tableName = tableDef.getTableName(); + List fs = LoadFieldDefList(tableDef.getTableId()); + String idFieldName = ""; + + String sql = "select "; + for (int i = 0; i < fs.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fs.get(i); + if (fdv.getGenericIdx() == 1) + idFieldName = fdv.getFieldSQL(); + if (i == 0) { + sql += fdv.getFieldSQL(); + } else { + sql += "," + fdv.getFieldSQL(); + } + } + sql += " from " + tableName + " s"; + sql += " where " + idFieldName + "='" + code + "'"; + DBPreparedHandler db = new DBPreparedHandler(); + try { + ResultSet rs = db.queryResults(sql); + if (rs.next()) { + for (int i = 0; i < fs.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fs.get(i); + String val = oscar.Misc.getString(rs, (i + 1)); + if ("D".equals(fdv.getFieldType())) + if (fdv.isEditable()) { + val = MyDateFormat.getStandardDate(MyDateFormat.getCalendarwithTime(val)); + } else { + val = MyDateFormat.getStandardDateTime(MyDateFormat.getCalendarwithTime(val)); + } + fdv.setVal(val); + } + } + rs.close(); + for (int i = 0; i < fs.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fs.get(i); + if (!Utility.IsEmpty(fdv.getLookupTable())) { + LookupCodeValue lkv = GetCode(fdv.getLookupTable(), fdv.getVal()); + if (lkv != null) + fdv.setValDesc(lkv.getDescription()); + } + } + } catch (SQLException e) { + MiscUtils.getLogger().error("Error", e); + } + return fs; + } + + @Override + public List GetCodeFieldValues(LookupTableDefValue tableDef) { + String tableName = tableDef.getTableName(); + List fs = LoadFieldDefList(tableDef.getTableId()); + ArrayList codes = new ArrayList(); + String sql = "select "; + for (int i = 0; i < fs.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fs.get(i); + if (i == 0) { + sql += fdv.getFieldSQL(); + } else { + sql += "," + fdv.getFieldSQL(); + } + } + sql += " from " + tableName; + DBPreparedHandler db = new DBPreparedHandler(); + try { + ResultSet rs = db.queryResults(sql); + while (rs.next()) { + for (int i = 0; i < fs.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fs.get(i); + String val = oscar.Misc.getString(rs, (i + 1)); + if ("D".equals(fdv.getFieldType())) + val = MyDateFormat.getStandardDateTime(MyDateFormat.getCalendarwithTime(val)); + fdv.setVal(val); + if (!Utility.IsEmpty(fdv.getLookupTable())) { + LookupCodeValue lkv = GetCode(fdv.getLookupTable(), val); + if (lkv != null) + fdv.setValDesc(lkv.getDescription()); + } + } + codes.add(fs); + } + rs.close(); + } catch (SQLException e) { + MiscUtils.getLogger().error("Error", e); + } + return codes; + } + + private int GetNextId(String idFieldName, String tableName) throws SQLException + + { + String sql = "select max(" + idFieldName + ")"; + sql += " from " + tableName; + DBPreparedHandler db = new DBPreparedHandler(); + + ResultSet rs = db.queryResults(sql); + int id = 0; + if (rs.next()) + id = rs.getInt(1); + return id + 1; + } + + @Override + public String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException { + String id = ""; + if (isNew) { + id = InsertCodeValue(tableDef, fieldDefList); + } else { + id = UpdateCodeValue(tableDef, fieldDefList); + } + String tableId = tableDef.getTableId(); + if ("OGN,SHL".indexOf(tableId) >= 0) { + SaveAsOrgCode(GetCode(tableId, id), tableId); + } + if ("PRP".equals(tableId)) { + OscarProperties prp = OscarProperties.getInstance(); + LookupCodeValue prpCd = GetCode(tableId, id); + if (prp.getProperty(prpCd.getDescription()) != null) + prp.remove(prpCd.getDescription()); + prp.setProperty(prpCd.getDescription(), prpCd.getBuf1().toLowerCase()); + } + return id; + } + + @Override + public String SaveCodeValue(boolean isNew, LookupCodeValue codeValue) throws SQLException { + String tableId = codeValue.getPrefix(); + LookupTableDefValue tableDef = GetLookupTableDef(tableId); + List fieldDefList = this.LoadFieldDefList(tableId); + for (int i = 0; i < fieldDefList.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); + + switch (fdv.getGenericIdx()) { + case 1: + fdv.setVal(codeValue.getCode()); + break; + case 2: + fdv.setVal(codeValue.getDescription()); + break; + case 3: + fdv.setVal(codeValue.isActive() ? "1" : "0"); + break; + case 4: + fdv.setVal(String.valueOf(codeValue.getOrderByIndex())); + break; + case 5: + fdv.setVal(codeValue.getParentCode()); + break; + case 6: + fdv.setVal(codeValue.getBuf1()); + break; + case 7: + fdv.setVal(codeValue.getCodeTree()); + break; + case 8: + fdv.setVal(codeValue.getLastUpdateUser()); + break; + case 9: + fdv.setVal(MyDateFormat.getStandardDateTime(codeValue.getLastUpdateDate())); + break; + case 10: + fdv.setVal(codeValue.getBuf3()); + break; + case 11: + fdv.setVal(codeValue.getBuf4()); + break; + case 12: + fdv.setVal(codeValue.getBuf5()); + break; + case 13: + fdv.setVal(codeValue.getBuf6()); + break; + case 14: + fdv.setVal(codeValue.getBuf7()); + break; + case 15: + fdv.setVal(codeValue.getBuf8()); + break; + case 16: + fdv.setVal(codeValue.getBuf9()); + break; + case 17: + fdv.setVal(codeValue.getCodecsv()); + break; + } + } + if (isNew) { + return InsertCodeValue(tableDef, fieldDefList); + } else { + return UpdateCodeValue(tableDef, fieldDefList); + } + } + + private String InsertCodeValue(LookupTableDefValue tableDef, List fieldDefList) throws SQLException { + String tableName = tableDef.getTableName(); + String idFieldVal = ""; + + DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[fieldDefList.size()]; + String phs = ""; + String sql = "insert into " + tableName + "("; + for (int i = 0; i < fieldDefList.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); + sql += fdv.getFieldSQL() + ","; + phs += "?,"; + if (fdv.getGenericIdx() == 1) { + if (fdv.isAuto()) { + idFieldVal = String.valueOf(GetNextId(fdv.getFieldSQL(), tableName)); + fdv.setVal(idFieldVal); + } else { + idFieldVal = fdv.getVal(); + } + } + if ("S".equals(fdv.getFieldType())) { + params[i] = new DBPreparedHandlerParam(fdv.getVal()); + } else if ("D".equals(fdv.getFieldType())) { + // for last update date Using calendar Instance + params[i] = new DBPreparedHandlerParam( + new java.sql.Date(MyDateFormat.getCalendarwithTime(fdv.getVal()).getTime().getTime())); + } else { + params[i] = new DBPreparedHandlerParam(Integer.valueOf(fdv.getVal()).intValue()); + } + } + sql = sql.substring(0, sql.length() - 1); + phs = phs.substring(0, phs.length() - 1); + sql += ") values (" + phs + ")"; + + // check the existence of the code + LookupCodeValue lkv = GetCode(tableDef.getTableId(), idFieldVal); + if (lkv != null) { + throw new SQLException("The Code Already Exists."); + } + + queryExecuteUpdate(sql, params); + + return idFieldVal; + } + + private String UpdateCodeValue(LookupTableDefValue tableDef, List fieldDefList) throws SQLException { + String tableName = tableDef.getTableName(); + String idFieldName = ""; + String idFieldVal = ""; + + DBPreparedHandlerParam[] params = new DBPreparedHandlerParam[fieldDefList.size() + 1]; + String sql = "update " + tableName + " set "; + for (int i = 0; i < fieldDefList.size(); i++) { + FieldDefValue fdv = (FieldDefValue) fieldDefList.get(i); + if (fdv.getGenericIdx() == 1) { + idFieldName = fdv.getFieldSQL(); + idFieldVal = fdv.getVal(); + } + + sql += fdv.getFieldSQL() + "=?,"; + if ("S".equals(fdv.getFieldType())) { + params[i] = new DBPreparedHandlerParam(fdv.getVal()); + } else if ("D".equals(fdv.getFieldType())) { + if (fdv.isEditable()) { + params[i] = new DBPreparedHandlerParam( + new java.sql.Date(MyDateFormat.getCalendar(fdv.getVal()).getTime().getTime())); + } else { + params[i] = new DBPreparedHandlerParam( + new java.sql.Date(MyDateFormat.getCalendarwithTime(fdv.getVal()).getTime().getTime())); + } + } else { + params[i] = new DBPreparedHandlerParam(Integer.valueOf(fdv.getVal()).intValue()); + } + } + sql = sql.substring(0, sql.length() - 1); + sql += " where " + idFieldName + "=?"; + params[fieldDefList.size()] = params[0]; + + queryExecuteUpdate(sql, params); + + return idFieldVal; + } + + @Override + public void SaveAsOrgCode(Program program) throws SQLException { + + String programId = "0000000" + program.getId().toString(); + programId = "P" + programId.substring(programId.length() - 7); + String fullCode = "P" + program.getId(); + + String facilityId = "0000000" + String.valueOf(program.getFacilityId()); + facilityId = "F" + facilityId.substring(facilityId.length() - 7); + + LookupCodeValue fcd = GetCode("ORG", "F" + program.getFacilityId()); + fullCode = fcd.getBuf1() + fullCode; + + boolean isNew = false; + LookupCodeValue pcd = GetCode("ORG", "P" + program.getId()); + if (pcd == null) { + isNew = true; + pcd = new LookupCodeValue(); + } + pcd.setPrefix("ORG"); + pcd.setCode("P" + program.getId()); + pcd.setCodeTree(fcd.getCodeTree() + programId); + pcd.setCodecsv(fcd.getCodecsv() + "P" + program.getId() + ","); + pcd.setDescription(program.getName()); + pcd.setBuf1(fullCode); + pcd.setActive(program.isActive()); + pcd.setOrderByIndex(0); + pcd.setLastUpdateDate(Calendar.getInstance()); + pcd.setLastUpdateUser(program.getLastUpdateUser()); + if (!isNew) { + this.updateOrgTree(pcd.getCode(), pcd); + this.updateOrgStatus(pcd.getCode(), pcd); + } + this.SaveCodeValue(isNew, pcd); + } + + private void updateOrgTree(String orgCd, LookupCodeValue newCd) { + LookupCodeValue oldCd = GetCode("ORG", orgCd); + if (!oldCd.getCodecsv().equals(newCd.getCodecsv())) { + String oldFullCode = oldCd.getBuf1(); + String oldTreeCode = oldCd.getCodeTree(); + String oldCsv = oldCd.getCodecsv(); + + String newFullCode = newCd.getBuf1(); + String newTreeCode = newCd.getCodeTree(); + String newCsv = newCd.getCodecsv(); + + String sql = "update lst_orgcd set fullcode =replace(fullcode,'" + oldFullCode + "','" + newFullCode + "')" + + ",codetree =replace(codetree,'" + oldTreeCode + "','" + newTreeCode + "')" + + ",codecsv =replace(codecsv,'" + oldCsv + "','" + newCsv + "')" + " where codecsv like '" + oldCsv + + "_%'"; + + // Session session = getSession(); + Session session = sessionFactory.getCurrentSession(); + try { + session.createSQLQuery(sql).executeUpdate(); + } finally { + // this.releaseSession(session); + session.close(); + } + + } + + } + + private void updateOrgStatus(String orgCd, LookupCodeValue newCd) { + LookupCodeValue oldCd = GetCode("ORG", orgCd); + if (!newCd.isActive()) { + String oldCsv = oldCd.getCodecsv(); + + List o = (List) this.getHibernateTemplate() + .find("FROM LstOrgcd o WHERE o.codecsv like ?", oldCsv + "_%"); + for (LstOrgcd l : o) { + l.setActiveyn(0); + this.getHibernateTemplate().update(l); + } + } + } + + @Override + public boolean inOrg(String org1, String org2) { + boolean isInString = false; + String sql = "From LstOrgcd a where a.fullcode like '%" + "?' "; + + LstOrgcd orgObj1 = (LstOrgcd) getHibernateTemplate().find(sql, new Object[] { org1 }); + LstOrgcd orgObj2 = (LstOrgcd) getHibernateTemplate().find(sql, new Object[] { org2 }); + if (orgObj2.getFullcode().indexOf(orgObj1.getFullcode()) > 0) + isInString = true; + return isInString; + + } + + @Override + public void SaveAsOrgCode(Facility facility) throws SQLException { + + String facilityId = "0000000" + facility.getId().toString(); + facilityId = "F" + facilityId.substring(facilityId.length() - 7); + String fullCode = "F" + facility.getId(); + + String orgId = "0000000" + String.valueOf(facility.getOrgId()); + orgId = "S" + orgId.substring(orgId.length() - 7); + + LookupCodeValue ocd = GetCode("ORG", "S" + facility.getOrgId()); + fullCode = ocd.getBuf1() + fullCode; + + boolean isNew = false; + LookupCodeValue fcd = GetCode("ORG", "F" + facility.getId()); + if (fcd == null) { + isNew = true; + fcd = new LookupCodeValue(); + } + fcd.setPrefix("ORG"); + fcd.setCode("F" + facility.getId()); + fcd.setCodeTree(ocd.getCodeTree() + facilityId); + fcd.setCodecsv(ocd.getCodecsv() + "F" + facility.getId() + ","); + fcd.setDescription(facility.getName()); + fcd.setBuf1(fullCode); + fcd.setActive(!facility.isDisabled()); + fcd.setOrderByIndex(0); + fcd.setLastUpdateDate(Calendar.getInstance()); + // fcd.setLastUpdateUser(facility.getLastUpdateUser()); + if (!isNew) { + this.updateOrgTree(fcd.getCode(), fcd); + this.updateOrgStatus(fcd.getCode(), fcd); + } + this.SaveCodeValue(isNew, fcd); + } + + @Override + public void SaveAsOrgCode(LookupCodeValue orgVal, String tableId) throws SQLException { + + String orgPrefix = tableId.substring(0, 1); + String orgPrefixP = "R1"; + if ("S".equals(orgPrefix)) + orgPrefixP = "O"; // parent of Organization is R, parent of Shelter is O. + + String orgId = "0000000" + orgVal.getCode(); + orgId = orgPrefix + orgId.substring(orgId.length() - 7); + + String orgCd = orgPrefix + orgVal.getCode(); + String parentCd = orgPrefixP + orgVal.getParentCode(); + + LookupCodeValue pCd = GetCode("ORG", parentCd); + if (pCd == null) + return; + + LookupCodeValue ocd = GetCode("ORG", orgCd); + boolean isNew = false; + if (ocd == null) { + isNew = true; + ocd = new LookupCodeValue(); + } + ocd.setPrefix("ORG"); + ocd.setCode(orgCd); + ocd.setCodeTree(pCd.getCodeTree() + orgId); + ocd.setCodecsv(pCd.getCodecsv() + orgCd + ","); + ocd.setDescription(orgVal.getDescription()); + ocd.setBuf1(pCd.getBuf1() + orgCd); + ocd.setActive(orgVal.isActive()); + ocd.setOrderByIndex(0); + ocd.setLastUpdateDate(Calendar.getInstance()); + ocd.setLastUpdateUser(orgVal.getLastUpdateUser()); + if (!isNew) { + this.updateOrgTree(ocd.getCode(), ocd); + this.updateOrgStatus(ocd.getCode(), ocd); + } + this.SaveCodeValue(isNew, ocd); + } + + @Override + public void runProcedure(String procName, String[] params) throws SQLException { + DBPreparedHandler db = new DBPreparedHandler(); + db.procExecute(procName, params); + } + + @Override + public int getCountOfActiveClient(String orgCd) throws SQLException { + String sql = "select count(*) from admission where admission_status='" + KeyConstants.INTAKE_STATUS_ADMITTED + + "' and 'P' || program_id in (" + " select code from lst_orgcd where codecsv like '%' || '" + orgCd + + ",' || '%')"; + String sql1 = "select count(*) from program_queue where 'P' || program_id in (" + + " select code from lst_orgcd where codecsv like '%' || '" + orgCd + ",' || '%')"; + + DBPreparedHandler db = new DBPreparedHandler(); + + ResultSet rs = db.queryResults(sql); + int id = 0; + if (rs.next()) + id = rs.getInt(1); + if (id > 0) + return id; + + rs.close(); + rs = db.queryResults(sql1); + if (rs.next()) + id = rs.getInt(1); + rs.close(); + return id; + } + + @Override + public void setProviderDao(ProviderDao providerDao) { + this.providerDao = providerDao; + } + + private int queryExecuteUpdate(String preparedSQL, DBPreparedHandlerParam[] params) throws SQLException { + PreparedStatement preparedStmt = DbConnectionFilter.getThreadLocalDbConnection().prepareStatement(preparedSQL); + for (int i = 0; i < params.length; i++) { + DBPreparedHandlerParam param = params[i]; + + if (param == null) + preparedStmt.setObject(i + 1, null); + else if (DBPreparedHandlerParam.PARAM_STRING.equals(param.getParamType())) { + preparedStmt.setString(i + 1, param.getStringValue()); + } else if (DBPreparedHandlerParam.PARAM_DATE.equals(param.getParamType())) { + preparedStmt.setDate(i + 1, param.getDateValue()); + } else if (DBPreparedHandlerParam.PARAM_INT.equals(param.getParamType())) { + preparedStmt.setInt(i + 1, param.getIntValue()); + } else if (DBPreparedHandlerParam.PARAM_TIMESTAMP.equals(param.getParamType())) { + preparedStmt.setTimestamp(i + 1, param.getTimestampValue()); + } + } + return (preparedStmt.executeUpdate()); + } + +} diff --git a/src/main/java/com/quatro/dao/security/SecObjectNameDao.java b/src/main/java/com/quatro/dao/security/SecObjectNameDao.java index cc5fc7b428..290eb3337d 100644 --- a/src/main/java/com/quatro/dao/security/SecObjectNameDao.java +++ b/src/main/java/com/quatro/dao/security/SecObjectNameDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,12 +21,13 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package com.quatro.dao.security; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import com.quatro.model.security.Secobjectname; @@ -33,16 +35,6 @@ * * @author jackson */ -public class SecObjectNameDao extends HibernateDaoSupport{ - public void saveOrUpdate(Secobjectname t) { - - try { - - this.getHibernateTemplate().saveOrUpdate(t); - - } catch (RuntimeException re) { - - throw re; - } - } +public interface SecObjectNameDao { + public void saveOrUpdate(Secobjectname t); } diff --git a/src/main/java/com/quatro/dao/security/SecObjectNameDaoImpl.java b/src/main/java/com/quatro/dao/security/SecObjectNameDaoImpl.java new file mode 100644 index 0000000000..dd1e319c3a --- /dev/null +++ b/src/main/java/com/quatro/dao/security/SecObjectNameDaoImpl.java @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao.security; + +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +import com.quatro.model.security.Secobjectname; + +/** + * + * @author jackson + */ +public class SecObjectNameDaoImpl extends HibernateDaoSupport implements SecObjectNameDao { + + @Override + public void saveOrUpdate(Secobjectname t) { + + try { + + this.getHibernateTemplate().saveOrUpdate(t); + + } catch (RuntimeException re) { + + throw re; + } + } +} diff --git a/src/main/java/com/quatro/dao/security/SecProviderDao.java b/src/main/java/com/quatro/dao/security/SecProviderDao.java index 5619deec62..6dc06934b5 100644 --- a/src/main/java/com/quatro/dao/security/SecProviderDao.java +++ b/src/main/java/com/quatro/dao/security/SecProviderDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,6 +18,8 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.dao.security; @@ -29,9 +32,11 @@ import org.hibernate.Session; import org.hibernate.criterion.Example; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import com.quatro.model.security.SecProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; /** * @@ -39,9 +44,8 @@ * */ -public class SecProviderDao extends HibernateDaoSupport { - private static final Logger logger = MiscUtils.getLogger(); - // property constants +public interface SecProviderDao { + public static final String LAST_NAME = "lastName"; public static final String FIRST_NAME = "firstName"; public static final String PROVIDER_TYPE = "providerType"; @@ -59,220 +63,57 @@ public class SecProviderDao extends HibernateDaoSupport { public static final String COMMENTS = "comments"; public static final String PROVIDER_ACTIVITY = "providerActivity"; - public void save(SecProvider transientInstance) { - logger.debug("saving Provider instance"); - try { - this.getHibernateTemplate().save(transientInstance); - logger.debug("save successful"); - } catch (RuntimeException re) { - logger.error("save failed", re); - throw re; - } - } - - public void saveOrUpdate(SecProvider transientInstance) { - logger.debug("saving Provider instance"); - try { - this.getHibernateTemplate().saveOrUpdate(transientInstance); - logger.debug("save successful"); - } catch (RuntimeException re) { - logger.error("save failed", re); - throw re; - } - } - public void delete(SecProvider persistentInstance) { - logger.debug("deleting Provider instance"); - try { - this.getHibernateTemplate().delete(persistentInstance); - logger.debug("delete successful"); - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - - public SecProvider findById(java.lang.String id) { - logger.debug("getting Provider instance with id: " + id); - try { - SecProvider instance = (SecProvider) this.getHibernateTemplate().get( - "com.quatro.model.security.SecProvider", id); - return instance; - } catch (RuntimeException re) { - logger.error("get failed", re); - throw re; - } - } - public SecProvider findById(java.lang.String id,String status) { - logger.debug("getting Provider instance with id: " + id); - try { - String sql ="from SecProvider where id=? and status=?"; - List lst=this.getHibernateTemplate().find(sql,new Object[]{id,status}); - if(lst.size()==0) - return null; - else - return (SecProvider) lst.get(0); - - } catch (RuntimeException re) { - logger.error("get failed", re); - throw re; - } - } - - public List findByExample(SecProviderDao instance) { - logger.debug("finding Provider instance by example"); - Session session = getSession(); - try { - List results = session.createCriteria( - "com.quatro.model.security.SecProvider").add( - Example.create(instance)).list(); - logger.debug("find by example successful, result size: " - + results.size()); - return results; - } catch (RuntimeException re) { - logger.error("find by example failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List findByProperty(String propertyName, Object value) { - logger.debug("finding Provider instance with property: " + propertyName - + ", value: " + value); - Session session = getSession(); - try { - String queryString = "from Provider as model where model." - + propertyName + "= ?"; - Query queryObject = session.createQuery(queryString); - queryObject.setParameter(0, value); - return queryObject.list(); - } catch (RuntimeException re) { - logger.error("find by property name failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List findByLastName(Object lastName) { - return findByProperty(LAST_NAME, lastName); - } - - public List findByFirstName(Object firstName) { - return findByProperty(FIRST_NAME, firstName); - } - - public List findByProviderType(Object providerType) { - return findByProperty(PROVIDER_TYPE, providerType); - } - - public List findBySpecialty(Object specialty) { - return findByProperty(SPECIALTY, specialty); - } - - public List findByTeam(Object team) { - return findByProperty(TEAM, team); - } - - public List findBySex(Object sex) { - return findByProperty(SEX, sex); - } - - public List findByAddress(Object address) { - return findByProperty(ADDRESS, address); - } - - public List findByPhone(Object phone) { - return findByProperty(PHONE, phone); - } - - public List findByWorkPhone(Object workPhone) { - return findByProperty(WORK_PHONE, workPhone); - } - - public List findByOhipNo(Object ohipNo) { - return findByProperty(OHIP_NO, ohipNo); - } - - public List findByRmaNo(Object rmaNo) { - return findByProperty(RMA_NO, rmaNo); - } - - public List findByBillingNo(Object billingNo) { - return findByProperty(BILLING_NO, billingNo); - } - - public List findByHsoNo(Object hsoNo) { - return findByProperty(HSO_NO, hsoNo); - } - - public List findByStatus(Object status) { - return findByProperty(STATUS, status); - } - - public List findByComments(Object comments) { - return findByProperty(COMMENTS, comments); - } - - public List findByProviderActivity(Object providerActivity) { - return findByProperty(PROVIDER_ACTIVITY, providerActivity); - } - - public List findAll() { - logger.debug("finding all Provider instances"); - Session session = getSession(); - try { - String queryString = "from Provider"; - Query queryObject = session.createQuery(queryString); - return queryObject.list(); - } catch (RuntimeException re) { - logger.error("find all failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public SecProviderDao merge(SecProviderDao detachedInstance) { - logger.debug("merging Provider instance"); - Session session = getSession(); - try { - SecProviderDao result = (SecProviderDao) session.merge(detachedInstance); - logger.debug("merge successful"); - return result; - } catch (RuntimeException re) { - logger.error("merge failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public void attachDirty(SecProviderDao instance) { - logger.debug("attaching dirty Provider instance"); - Session session = getSession(); - try { - session.saveOrUpdate(instance); - logger.debug("attach successful"); - } catch (RuntimeException re) { - logger.error("attach failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public void attachClean(SecProviderDao instance) { - logger.debug("attaching clean Provider instance"); - Session session = getSession(); - try { - session.lock(instance, LockMode.NONE); - logger.debug("attach successful"); - } catch (RuntimeException re) { - logger.error("attach failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } + public void save(SecProvider transientInstance); + + public void saveOrUpdate(SecProvider transientInstance); + + public void delete(SecProvider persistentInstance); + + public SecProvider findById(java.lang.String id); + + public SecProvider findById(java.lang.String id, String status); + + public List findByExample(SecProviderDao instance); + + public List findByProperty(String propertyName, Object value); + + public List findByLastName(Object lastName); + + public List findByFirstName(Object firstName); + + public List findByProviderType(Object providerType); + + public List findBySpecialty(Object specialty); + + public List findByTeam(Object team); + + public List findBySex(Object sex); + + public List findByAddress(Object address); + + public List findByPhone(Object phone); + + public List findByWorkPhone(Object workPhone); + + public List findByOhipNo(Object ohipNo); + + public List findByRmaNo(Object rmaNo); + + public List findByBillingNo(Object billingNo); + + public List findByHsoNo(Object hsoNo); + + public List findByStatus(Object status); + + public List findByComments(Object comments); + + public List findByProviderActivity(Object providerActivity); + + public List findAll(); + + public SecProviderDao merge(SecProviderDao detachedInstance); + + public void attachDirty(SecProviderDao instance); + + public void attachClean(SecProviderDao instance); } diff --git a/src/main/java/com/quatro/dao/security/SecProviderDaoImpl.java b/src/main/java/com/quatro/dao/security/SecProviderDaoImpl.java new file mode 100644 index 0000000000..6d86464e78 --- /dev/null +++ b/src/main/java/com/quatro/dao/security/SecProviderDaoImpl.java @@ -0,0 +1,311 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao.security; + +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.hibernate.LockMode; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.criterion.Example; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + +import com.quatro.model.security.SecProvider; + +/** + * + * @author JZhang + * + */ + +public class SecProviderDaoImpl extends HibernateDaoSupport implements SecProviderDao { + private static final Logger logger = MiscUtils.getLogger(); + // property constants + public static final String LAST_NAME = "lastName"; + public static final String FIRST_NAME = "firstName"; + public static final String PROVIDER_TYPE = "providerType"; + public static final String SPECIALTY = "specialty"; + public static final String TEAM = "team"; + public static final String SEX = "sex"; + public static final String ADDRESS = "address"; + public static final String PHONE = "phone"; + public static final String WORK_PHONE = "workPhone"; + public static final String OHIP_NO = "ohipNo"; + public static final String RMA_NO = "rmaNo"; + public static final String BILLING_NO = "billingNo"; + public static final String HSO_NO = "hsoNo"; + public static final String STATUS = "status"; + public static final String COMMENTS = "comments"; + public static final String PROVIDER_ACTIVITY = "providerActivity"; + + @Override + public void save(SecProvider transientInstance) { + logger.debug("saving Provider instance"); + try { + this.getHibernateTemplate().save(transientInstance); + logger.debug("save successful"); + } catch (RuntimeException re) { + logger.error("save failed", re); + throw re; + } + } + + @Override + public void saveOrUpdate(SecProvider transientInstance) { + logger.debug("saving Provider instance"); + try { + this.getHibernateTemplate().saveOrUpdate(transientInstance); + logger.debug("save successful"); + } catch (RuntimeException re) { + logger.error("save failed", re); + throw re; + } + } + + @Override + public void delete(SecProvider persistentInstance) { + logger.debug("deleting Provider instance"); + try { + this.getHibernateTemplate().delete(persistentInstance); + logger.debug("delete successful"); + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public SecProvider findById(java.lang.String id) { + logger.debug("getting Provider instance with id: " + id); + try { + SecProvider instance = (SecProvider) this.getHibernateTemplate().get( + "com.quatro.model.security.SecProvider", id); + return instance; + } catch (RuntimeException re) { + logger.error("get failed", re); + throw re; + } + } + + @Override + public SecProvider findById(java.lang.String id, String status) { + logger.debug("getting Provider instance with id: " + id); + try { + String sql = "from SecProvider where id=? and status=?"; + List lst = this.getHibernateTemplate().find(sql, new Object[] { id, status }); + if (lst.size() == 0) + return null; + else + return (SecProvider) lst.get(0); + + } catch (RuntimeException re) { + logger.error("get failed", re); + throw re; + } + } + + @Override + public List findByExample(SecProviderDao instance) { + logger.debug("finding Provider instance by example"); + Session session = getSession(); + try { + List results = session.createCriteria( + "com.quatro.model.security.SecProvider").add( + Example.create(instance)) + .list(); + logger.debug("find by example successful, result size: " + + results.size()); + return results; + } catch (RuntimeException re) { + logger.error("find by example failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } + + @Override + public List findByProperty(String propertyName, Object value) { + logger.debug("finding Provider instance with property: " + propertyName + + ", value: " + value); + Session session = getSession(); + try { + String queryString = "from Provider as model where model." + + propertyName + "= ?"; + Query queryObject = session.createQuery(queryString); + queryObject.setParameter(0, value); + return queryObject.list(); + } catch (RuntimeException re) { + logger.error("find by property name failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } + + @Override + public List findByLastName(Object lastName) { + return findByProperty(LAST_NAME, lastName); + } + + @Override + public List findByFirstName(Object firstName) { + return findByProperty(FIRST_NAME, firstName); + } + + @Override + public List findByProviderType(Object providerType) { + return findByProperty(PROVIDER_TYPE, providerType); + } + + @Override + public List findBySpecialty(Object specialty) { + return findByProperty(SPECIALTY, specialty); + } + + @Override + public List findByTeam(Object team) { + return findByProperty(TEAM, team); + } + + @Override + public List findBySex(Object sex) { + return findByProperty(SEX, sex); + } + + @Override + public List findByAddress(Object address) { + return findByProperty(ADDRESS, address); + } + + @Override + public List findByPhone(Object phone) { + return findByProperty(PHONE, phone); + } + + @Override + public List findByWorkPhone(Object workPhone) { + return findByProperty(WORK_PHONE, workPhone); + } + + @Override + public List findByOhipNo(Object ohipNo) { + return findByProperty(OHIP_NO, ohipNo); + } + + @Override + public List findByRmaNo(Object rmaNo) { + return findByProperty(RMA_NO, rmaNo); + } + + @Override + public List findByBillingNo(Object billingNo) { + return findByProperty(BILLING_NO, billingNo); + } + + @Override + public List findByHsoNo(Object hsoNo) { + return findByProperty(HSO_NO, hsoNo); + } + + @Override + public List findByStatus(Object status) { + return findByProperty(STATUS, status); + } + + @Override + public List findByComments(Object comments) { + return findByProperty(COMMENTS, comments); + } + + @Override + public List findByProviderActivity(Object providerActivity) { + return findByProperty(PROVIDER_ACTIVITY, providerActivity); + } + + @Override + public List findAll() { + logger.debug("finding all Provider instances"); + Session session = getSession(); + try { + String queryString = "from Provider"; + Query queryObject = session.createQuery(queryString); + return queryObject.list(); + } catch (RuntimeException re) { + logger.error("find all failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } + + @Override + public SecProviderDao merge(SecProviderDao detachedInstance) { + logger.debug("merging Provider instance"); + Session session = getSession(); + try { + SecProviderDao result = (SecProviderDao) session.merge(detachedInstance); + logger.debug("merge successful"); + return result; + } catch (RuntimeException re) { + logger.error("merge failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } + + @Override + public void attachDirty(SecProviderDao instance) { + logger.debug("attaching dirty Provider instance"); + Session session = getSession(); + try { + session.saveOrUpdate(instance); + logger.debug("attach successful"); + } catch (RuntimeException re) { + logger.error("attach failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } + + @Override + public void attachClean(SecProviderDao instance) { + logger.debug("attaching clean Provider instance"); + Session session = getSession(); + try { + session.lock(instance, LockMode.NONE); + logger.debug("attach successful"); + } catch (RuntimeException re) { + logger.error("attach failed", re); + throw re; + } finally { + this.releaseSession(session); + } + } +} diff --git a/src/main/java/com/quatro/dao/security/SecobjprivilegeDao.java b/src/main/java/com/quatro/dao/security/SecobjprivilegeDao.java index 5e6c07f05b..ee9c85a50c 100644 --- a/src/main/java/com/quatro/dao/security/SecobjprivilegeDao.java +++ b/src/main/java/com/quatro/dao/security/SecobjprivilegeDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,9 +20,10 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package com.quatro.dao.security; import java.util.ArrayList; @@ -31,179 +33,33 @@ import org.hibernate.Query; import org.hibernate.Session; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; import com.quatro.model.security.Secobjprivilege; -public class SecobjprivilegeDao extends HibernateDaoSupport { - - private Logger logger = MiscUtils.getLogger(); - - - public void save(Secobjprivilege secobjprivilege) { - if (secobjprivilege == null) { - throw new IllegalArgumentException(); - } - - getHibernateTemplate().saveOrUpdate(secobjprivilege); - - if (logger.isDebugEnabled()) { - logger.debug("SecobjprivilegeDao : save: " + secobjprivilege.getRoleusergroup() + ":" + secobjprivilege.getObjectname_desc()); - } - - } - public void saveAll(List list) { - logger.debug("saving ALL Secobjprivilege instances"); - try { - for(int i =0; i< list.size(); i++){ - Secobjprivilege obj = (Secobjprivilege)list.get(i); - - int rowcount = update(obj); - - if(rowcount <= 0){ - save(obj); - } - - } - - logger.debug("save ALL successful"); - } catch (RuntimeException re) { - logger.error("save ALL failed", re); - throw re; - } - } - public int update(Secobjprivilege instance) { - logger.debug("update Secobjprivilege instance"); - Session session = getSession(); - try { - String queryString = "update Secobjprivilege as model set model.providerNo ='" + instance.getProviderNo() + "'" - + " where model.objectname_code ='" + instance.getObjectname_code() + "'" - + " and model.privilege_code ='" + instance.getPrivilege_code() + "'" - + " and model.roleusergroup ='" + instance.getRoleusergroup() + "'"; - - Query queryObject = session.createQuery(queryString); - - return queryObject.executeUpdate(); - - } catch (RuntimeException re) { - logger.error("Update failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - public int deleteByRoleName(String roleName) { - logger.debug("deleting Secobjprivilege by roleName"); - try { - - return getHibernateTemplate().bulkUpdate("delete Secobjprivilege as model where model.roleusergroup =?", roleName); - - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - public void delete(Secobjprivilege persistentInstance) { - logger.debug("deleting Secobjprivilege instance"); - try { - getHibernateTemplate().delete(persistentInstance); - logger.debug("delete successful"); - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - public String getFunctionDesc(String function_code) { - try { - String queryString = "select description from Secobjectname obj where obj.objectname='" + function_code+"'"; - - List lst = getHibernateTemplate().find(queryString); - if(lst.size()>0 && lst.get(0)!=null) - return lst.get(0).toString(); - else - return ""; - } catch (RuntimeException re) { - logger.error("find by property name failed", re); - throw re; - } - } - public String getAccessDesc(String accessType_code) { - try { - String queryString = "select description from Secprivilege obj where obj.privilege='" + accessType_code +"'"; - - List lst = getHibernateTemplate().find(queryString); - if(lst.size()>0 && lst.get(0)!=null) - return lst.get(0).toString(); - else - return ""; - } catch (RuntimeException re) { - logger.error("find by property name failed", re); - throw re; - } - } - public List getFunctions(String roleName) { - if (roleName == null) { - throw new IllegalArgumentException(); - } - - List result = findByProperty("roleusergroup", roleName); - if (logger.isDebugEnabled()) { - logger.debug("SecobjprivilegeDao : getFunctions: "); - } - return result; - } - public List findByProperty(String propertyName, Object value) { - logger.debug("finding Secobjprivilege instance with property: " + propertyName - + ", value: " + value); - Session session = getSession(); - try { - String queryString = "from Secobjprivilege as model where model." - + propertyName + "= ? order by objectname_code"; - Query queryObject = session.createQuery(queryString); - queryObject.setParameter(0, value); - return queryObject.list(); - } catch (RuntimeException re) { - logger.error("find by property name failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List getByObjectNameAndRoles(String o,List roles) { - String queryString = "from Secobjprivilege obj where obj.objectname_code='" + o +"'"; - List results = new ArrayList(); - - @SuppressWarnings("unchecked") - List lst = getHibernateTemplate().find(queryString); - - for(Secobjprivilege p:lst) { - if(roles.contains(p.getRoleusergroup())) { - results.add(p); - } - } - return results; - } - - public List getByRoles(List roles) { - String queryString = "from Secobjprivilege obj where obj.roleusergroup IN (:roles)"; - List results = new ArrayList(); - - - Session session = getSession(); - try { - Query q = session.createQuery(queryString); - - - q.setParameterList("roles", roles); - - results = q.list(); - }finally { - this.releaseSession(session); - } - - return results; - } -} +public interface SecobjprivilegeDao { + + public void save(Secobjprivilege secobjprivilege); + + public void saveAll(List list); + + public int update(Secobjprivilege instance); + + public int deleteByRoleName(String roleName); + public void delete(Secobjprivilege persistentInstance); + public String getFunctionDesc(String function_code); + + public String getAccessDesc(String accessType_code); + + public List getFunctions(String roleName); + + public List findByProperty(String propertyName, Object value); + + public List getByObjectNameAndRoles(String o, List roles); + + public List getByRoles(List roles); +} diff --git a/src/main/java/com/quatro/dao/security/SecobjprivilegeDaoImpl.java b/src/main/java/com/quatro/dao/security/SecobjprivilegeDaoImpl.java new file mode 100644 index 0000000000..e608f44c67 --- /dev/null +++ b/src/main/java/com/quatro/dao/security/SecobjprivilegeDaoImpl.java @@ -0,0 +1,237 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao.security; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Query; +import org.hibernate.Session; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +import com.quatro.dao.security.SecobjprivilegeDao; +import com.quatro.model.security.Secobjprivilege; + +public class SecobjprivilegeDaoImpl extends HibernateDaoSupport implements SecobjprivilegeDao { + + private Logger logger = MiscUtils.getLogger(); + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + @Override + public void save(Secobjprivilege secobjprivilege) { + if (secobjprivilege == null) { + throw new IllegalArgumentException(); + } + + getHibernateTemplate().saveOrUpdate(secobjprivilege); + + if (logger.isDebugEnabled()) { + logger.debug("SecobjprivilegeDao : save: " + secobjprivilege.getRoleusergroup() + ":" + + secobjprivilege.getObjectname_desc()); + } + + } + + @Override + public void saveAll(List list) { + logger.debug("saving ALL Secobjprivilege instances"); + try { + for (int i = 0; i < list.size(); i++) { + Secobjprivilege obj = (Secobjprivilege) list.get(i); + + int rowcount = update(obj); + + if (rowcount <= 0) { + save(obj); + } + + } + + logger.debug("save ALL successful"); + } catch (RuntimeException re) { + logger.error("save ALL failed", re); + throw re; + } + } + + @Override + public int update(Secobjprivilege instance) { + logger.debug("update Secobjprivilege instance"); + Session session = sessionFactory.getCurrentSession(); + try { + String queryString = "update Secobjprivilege as model set model.providerNo ='" + instance.getProviderNo() + + "'" + + " where model.objectname_code ='" + instance.getObjectname_code() + "'" + + " and model.privilege_code ='" + instance.getPrivilege_code() + "'" + + " and model.roleusergroup ='" + instance.getRoleusergroup() + "'"; + + Query queryObject = session.createQuery(queryString); + + return queryObject.executeUpdate(); + + } catch (RuntimeException re) { + logger.error("Update failed", re); + throw re; + } finally { + // this.releaseSession(session); + session.close(); + } + } + + @Override + public int deleteByRoleName(String roleName) { + logger.debug("deleting Secobjprivilege by roleName"); + try { + + return getHibernateTemplate().bulkUpdate("delete Secobjprivilege as model where model.roleusergroup =?", + roleName); + + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public void delete(Secobjprivilege persistentInstance) { + logger.debug("deleting Secobjprivilege instance"); + try { + getHibernateTemplate().delete(persistentInstance); + logger.debug("delete successful"); + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public String getFunctionDesc(String function_code) { + try { + String queryString = "select description from Secobjectname obj where obj.objectname='" + function_code + + "'"; + + List lst = getHibernateTemplate().find(queryString); + if (lst.size() > 0 && lst.get(0) != null) + return lst.get(0).toString(); + else + return ""; + } catch (RuntimeException re) { + logger.error("find by property name failed", re); + throw re; + } + } + + @Override + public String getAccessDesc(String accessType_code) { + try { + String queryString = "select description from Secprivilege obj where obj.privilege='" + accessType_code + + "'"; + + List lst = getHibernateTemplate().find(queryString); + if (lst.size() > 0 && lst.get(0) != null) + return lst.get(0).toString(); + else + return ""; + } catch (RuntimeException re) { + logger.error("find by property name failed", re); + throw re; + } + } + + @Override + public List getFunctions(String roleName) { + if (roleName == null) { + throw new IllegalArgumentException(); + } + + List result = findByProperty("roleusergroup", roleName); + if (logger.isDebugEnabled()) { + logger.debug("SecobjprivilegeDao : getFunctions: "); + } + return result; + } + + @Override + public List findByProperty(String propertyName, Object value) { + logger.debug("finding Secobjprivilege instance with property: " + propertyName + + ", value: " + value); + Session session = sessionFactory.getCurrentSession(); + try { + String queryString = "from Secobjprivilege as model where model." + + propertyName + "= ? order by objectname_code"; + Query queryObject = session.createQuery(queryString); + queryObject.setParameter(0, value); + return queryObject.list(); + } catch (RuntimeException re) { + logger.error("find by property name failed", re); + throw re; + } finally { + // this.releaseSession(session); + session.close(); + } + } + + @Override + public List getByObjectNameAndRoles(String o, List roles) { + String queryString = "from Secobjprivilege obj where obj.objectname_code='" + o + "'"; + List results = new ArrayList(); + + @SuppressWarnings("unchecked") + List lst = (List) getHibernateTemplate().find(queryString); + + for (Secobjprivilege p : lst) { + if (roles.contains(p.getRoleusergroup())) { + results.add(p); + } + } + return results; + } + + @Override + public List getByRoles(List roles) { + String queryString = "from Secobjprivilege obj where obj.roleusergroup IN (:roles)"; + List results = new ArrayList(); + + Session session = sessionFactory.getCurrentSession(); + Query q = session.createQuery(queryString); + + q.setParameterList("roles", roles); + + results = q.list(); + + return results; + } +} diff --git a/src/main/java/com/quatro/dao/security/SecroleDao.java b/src/main/java/com/quatro/dao/security/SecroleDao.java index 12b5adff4d..b2d1062dd5 100644 --- a/src/main/java/com/quatro/dao/security/SecroleDao.java +++ b/src/main/java/com/quatro/dao/security/SecroleDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,71 +20,29 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - - package com.quatro.dao.security; import java.util.List; import org.apache.logging.log4j.Logger; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import com.quatro.model.security.Secrole; -public class SecroleDao extends HibernateDaoSupport { - - private Logger logger = MiscUtils.getLogger(); - - public List getRoles() { - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from Secrole r order by roleName"); - - logger.debug("getRoles: # of results=" + results.size()); - - return results; - } - - public Secrole getRole(Integer id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - Secrole result = this.getHibernateTemplate().get(Secrole.class, new Long(id)); - - logger.debug("getRole: id=" + id + ",found=" + (result != null)); - - return result; - } - - public Secrole getRoleByName(String roleName) { - Secrole result = null; - if (roleName == null || roleName.length() <= 0) { - throw new IllegalArgumentException(); - } - - List lst = this.getHibernateTemplate().find("from Secrole r where r.roleName='" + roleName + "'"); - if(lst != null && lst.size() > 0) - result = (Secrole) lst.get(0); - - logger.debug("getRoleByName: roleName=" + roleName + ",found=" + (result != null)); - - return result; - } +public interface SecroleDao { + public List getRoles(); - public List getDefaultRoles() { - return this.getHibernateTemplate().find("from Secrole r where r.userDefined=0"); - } + public Secrole getRole(Integer id); - public void save(Secrole secrole) { - if (secrole == null) { - throw new IllegalArgumentException(); - } + public Secrole getRoleByName(String roleName); - getHibernateTemplate().saveOrUpdate(secrole); + public List getDefaultRoles(); - } + public void save(Secrole secrole); } diff --git a/src/main/java/com/quatro/dao/security/SecroleDaoImpl.java b/src/main/java/com/quatro/dao/security/SecroleDaoImpl.java new file mode 100644 index 0000000000..b5146c306e --- /dev/null +++ b/src/main/java/com/quatro/dao/security/SecroleDaoImpl.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao.security; + +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +import com.quatro.model.security.Secrole; + +public class SecroleDaoImpl extends HibernateDaoSupport implements SecroleDao { + + private Logger logger = MiscUtils.getLogger(); + + @Override + public List getRoles() { + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate().find("from Secrole r order by roleName"); + + logger.debug("getRoles: # of results=" + results.size()); + + return results; + } + + @Override + public Secrole getRole(Integer id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + Secrole result = this.getHibernateTemplate().get(Secrole.class, new Long(id)); + + logger.debug("getRole: id=" + id + ",found=" + (result != null)); + + return result; + } + + @Override + public Secrole getRoleByName(String roleName) { + Secrole result = null; + if (roleName == null || roleName.length() <= 0) { + throw new IllegalArgumentException(); + } + + List lst = this.getHibernateTemplate().find("from Secrole r where r.roleName='" + roleName + "'"); + if (lst != null && lst.size() > 0) + result = (Secrole) lst.get(0); + + logger.debug("getRoleByName: roleName=" + roleName + ",found=" + (result != null)); + + return result; + } + + @Override + public List getDefaultRoles() { + return this.getHibernateTemplate().find("from Secrole r where r.userDefined=0"); + } + + @Override + public void save(Secrole secrole) { + if (secrole == null) { + throw new IllegalArgumentException(); + } + + getHibernateTemplate().saveOrUpdate(secrole); + + } + +} diff --git a/src/main/java/com/quatro/dao/security/SecuserroleDao.java b/src/main/java/com/quatro/dao/security/SecuserroleDao.java index 4587fc3980..7e7d5ae3d2 100644 --- a/src/main/java/com/quatro/dao/security/SecuserroleDao.java +++ b/src/main/java/com/quatro/dao/security/SecuserroleDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,6 +18,8 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.dao.security; @@ -29,10 +32,13 @@ import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Session; +import org.hibernate.SessionFactory; import org.hibernate.criterion.Example; import org.oscarehr.PMmodule.web.formbean.StaffForm; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; import com.quatro.model.security.Secuserrole; @@ -48,315 +54,49 @@ * @author MyEclipse Persistence Tools */ -public class SecuserroleDao extends HibernateDaoSupport { - private static final Logger logger = MiscUtils.getLogger(); - // property constants +public interface SecuserroleDao { public static final String PROVIDER_NO = "providerNo"; public static final String ROLE_NAME = "roleName"; public static final String ORGCD = "orgcd"; public static final String ACTIVEYN = "activeyn"; - public void saveAll(List list) { - logger.debug("saving ALL Secuserrole instances"); - Session session = getSession(); - try { - for(int i =0; i< list.size(); i++){ - Secuserrole obj = (Secuserrole)list.get(i); - obj.setLastUpdateDate(new Date()); - int rowcount = update(obj); - - if(rowcount <= 0){ - session.save(obj); - } - - } - //this.getHibernateTemplate().saveOrUpdateAll(list); - logger.debug("save ALL successful"); - } catch (RuntimeException re) { - logger.error("save ALL failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - public void save(Secuserrole transientInstance) { - logger.debug("saving Secuserrole instance"); - Session session = getSession(); - try { - transientInstance.setLastUpdateDate(new Date()); - session.saveOrUpdate(transientInstance); - logger.debug("save successful"); - } catch (RuntimeException re) { - logger.error("save failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public void updateRoleName(Integer id, String roleName) { - Secuserrole sur = this.getHibernateTemplate().get(Secuserrole.class, id); - if(sur != null) { - sur.setRoleName(roleName); - sur.setLastUpdateDate(new Date()); - this.getHibernateTemplate().update(sur); - } - } - - public void delete(Secuserrole persistentInstance) { - logger.debug("deleting Secuserrole instance"); - Session session = getSession(); - try { - session.delete(persistentInstance); - logger.debug("delete successful"); - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - public int deleteByOrgcd(String orgcd) { - logger.debug("deleting Secuserrole by orgcd"); - try { - - return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.orgcd =?", orgcd); - - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - public int deleteByProviderNo(String providerNo) { - logger.debug("deleting Secuserrole by providerNo"); - try { - - return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.providerNo =?", providerNo); - - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - - public int deleteById(Integer id) { - logger.debug("deleting Secuserrole by ID"); - try { - - return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.id =?", id); - - } catch (RuntimeException re) { - logger.error("delete failed", re); - throw re; - } - } - public int update(Secuserrole instance) { - logger.debug("Update Secuserrole instance"); - Session session = getSession(); - try { - String queryString = "update Secuserrole as model set model.activeyn ='" + instance.getActiveyn() + "' , lastUpdateDate=now() " - + " where model.providerNo ='" + instance.getProviderNo() + "'" - + " and model.roleName ='" + instance.getRoleName() + "'" - + " and model.orgcd ='" + instance.getOrgcd() + "'"; - - Query queryObject = session.createQuery(queryString); - - return queryObject.executeUpdate(); - - } catch (RuntimeException re) { - logger.error("Update failed", re); - throw re; - } - } - public Secuserrole findById(java.lang.Integer id) { - logger.debug("getting Secuserrole instance with id: " + id); - Session session = getSession(); - try { - Secuserrole instance = (Secuserrole) session.get( - "com.quatro.model.security.Secuserrole", id); - return instance; - } catch (RuntimeException re) { - logger.error("get failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List findByExample(Secuserrole instance) { - Session session = getSession(); - logger.debug("finding Secuserrole instance by example"); - try { - List results = session.createCriteria( - "com.quatro.model.security.Secuserrole").add( - Example.create(instance)).list(); - logger.debug("find by example successful, result size: " - + results.size()); - return results; - } catch (RuntimeException re) { - logger.error("find by example failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List findByProperty(String propertyName, Object value) { - logger.debug("finding Secuserrole instance with property: " + propertyName - + ", value: " + value); - Session session = getSession(); - try { - String queryString = "from Secuserrole as model where model." - + propertyName + "= ?"; - Query queryObject = session.createQuery(queryString); - queryObject.setParameter(0, value); - return queryObject.list(); - } catch (RuntimeException re) { - logger.error("find by property name failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } - - public List findByProviderNo(Object providerNo) { - return findByProperty(PROVIDER_NO, providerNo); - } - - public List findByRoleName(Object roleName) { - return findByProperty(ROLE_NAME, roleName); - } - - public List findByOrgcd(Object orgcd, boolean activeOnly) { - //return findByProperty(ORGCD, orgcd); - /* SQL: - select * from secUserRole s, - (select codecsv from lst_orgcd where code = 'P200011') b - where b.codecsv like '%' || s.orgcd || ',%' - and not (s.orgcd like 'R%' or s.orgcd like 'O%') - - */ - logger.debug("Find staff instance ."); - try { - - String queryString = "select a from Secuserrole a, LstOrgcd b, SecProvider p" - + " where a.providerNo=p.providerNo and b.code ='" + orgcd + "'"; - if (activeOnly) queryString += " and p.status='1'"; - - queryString = queryString - + " and b.codecsv like '%' || a.orgcd || ',%'" - + " and not (a.orgcd like 'R%' or a.orgcd like 'O%')"; + public void saveAll(List list); + public void save(Secuserrole transientInstance); - return this.getHibernateTemplate().find(queryString); + public void updateRoleName(Integer id, String roleName); - } catch (RuntimeException re) { - logger.error("Find staff failed", re); - throw re; - } + public void delete(Secuserrole persistentInstance); - } - public List searchByCriteria(StaffForm staffForm){ + public int deleteByOrgcd(String orgcd); - logger.debug("Search staff instance ."); - try { + public int deleteByProviderNo(String providerNo); + public int deleteById(Integer id); - String AND = " and "; - //String OR = " or "; + public int update(Secuserrole instance); + public Secuserrole findById(java.lang.Integer id); - String orgcd = staffForm.getOrgcd(); + public List findByExample(Secuserrole instance); - String queryString = "select a from Secuserrole a, LstOrgcd b" - + " where b.code ='" + orgcd + "'" - + " and b.codecsv like '%' || a.orgcd || ',%'" - + " and not (a.orgcd like 'R%' or a.orgcd like 'O%')"; + public List findByProperty(String propertyName, Object value); - String fname = staffForm.getFirstName(); - String lname = staffForm.getLastName(); + public List findByProviderNo(Object providerNo); - if (fname != null && fname.length() > 0) { - fname = StringEscapeUtils.escapeSql(fname); - fname = fname.toLowerCase(); - queryString = queryString + AND + "lower(a.providerFName) like '%" + fname + "%'"; - } - if (lname != null && lname.length() > 0) { - lname = StringEscapeUtils.escapeSql(lname); - lname = lname.toLowerCase(); - queryString = queryString + AND + "lower(a.providerLName) like '%" + lname + "%'"; - } + public List findByRoleName(Object roleName); - return this.getHibernateTemplate().find(queryString); + public List findByOrgcd(Object orgcd, boolean activeOnly); - } catch (RuntimeException re) { - logger.error("Search staff failed", re); - throw re; - } - } + public List searchByCriteria(StaffForm staffForm); - public List findByActiveyn(Object activeyn) { - return findByProperty(ACTIVEYN, activeyn); - } + public List findByActiveyn(Object activeyn); - public List findAll() { - Session session = getSession(); - logger.debug("finding all Secuserrole instances"); - try { - String queryString = "from Secuserrole"; - Query queryObject = session.createQuery(queryString); - return queryObject.list(); - } catch (RuntimeException re) { - logger.error("find all failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } + public List findAll(); - public Secuserrole merge(Secuserrole detachedInstance) { - logger.debug("merging Secuserrole instance"); - Session session = getSession(); - try { - detachedInstance.setLastUpdateDate(new Date()); - Secuserrole result = (Secuserrole) session.merge( - detachedInstance); - logger.debug("merge successful"); - return result; - } catch (RuntimeException re) { - logger.error("merge failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } + public Secuserrole merge(Secuserrole detachedInstance); - public void attachDirty(Secuserrole instance) { - logger.debug("attaching dirty Secuserrole instance"); - Session session = getSession(); - try { - instance.setLastUpdateDate(new Date()); - session.saveOrUpdate(instance); - logger.debug("attach successful"); - } catch (RuntimeException re) { - logger.error("attach failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } + public void attachDirty(Secuserrole instance); - public void attachClean(Secuserrole instance) { - logger.debug("attaching clean Secuserrole instance"); - Session session = getSession(); - try { - session.lock(instance, LockMode.NONE); - logger.debug("attach successful"); - } catch (RuntimeException re) { - logger.error("attach failed", re); - throw re; - } finally { - this.releaseSession(session); - } - } + public void attachClean(Secuserrole instance); } diff --git a/src/main/java/com/quatro/dao/security/SecuserroleDaoImpl.java b/src/main/java/com/quatro/dao/security/SecuserroleDaoImpl.java new file mode 100644 index 0000000000..c5d50e185a --- /dev/null +++ b/src/main/java/com/quatro/dao/security/SecuserroleDaoImpl.java @@ -0,0 +1,423 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ + +package com.quatro.dao.security; + +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.logging.log4j.Logger; +import org.hibernate.LockMode; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Example; +import org.oscarehr.PMmodule.web.formbean.StaffForm; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; + +import com.quatro.model.security.Secuserrole; +import org.springframework.transaction.annotation.Transactional; +/** + * A data access object (DAO) providing persistence and search support for + * Secuserrole entities. Transaction control of the save(), update() and + * delete() operations can directly support Spring container-managed + * transactions or they can be augmented to handle user-managed Spring + * transactions. Each of these methods provides additional information for how + * to configure it for the desired type of transaction control. + * + * @see com.quatro.model.security.Secuserrole + * @author MyEclipse Persistence Tools + */ +@Transactional +public class SecuserroleDaoImpl extends HibernateDaoSupport implements SecuserroleDao { + private static final Logger logger = MiscUtils.getLogger(); + // property constants + public static final String PROVIDER_NO = "providerNo"; + public static final String ROLE_NAME = "roleName"; + public static final String ORGCD = "orgcd"; + public static final String ACTIVEYN = "activeyn"; + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + @Override + public void saveAll(List list) { + logger.debug("saving ALL Secuserrole instances"); + // Session session = getSession(); + Session session = currentSession();; + try { + for (int i = 0; i < list.size(); i++) { + Secuserrole obj = (Secuserrole) list.get(i); + obj.setLastUpdateDate(new Date()); + int rowcount = update(obj); + + if (rowcount <= 0) { + session.save(obj); + } + + } + // this.getHibernateTemplate().saveOrUpdateAll(list); + logger.debug("save ALL successful"); + } catch (RuntimeException re) { + logger.error("save ALL failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public void save(Secuserrole transientInstance) { + logger.debug("saving Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + transientInstance.setLastUpdateDate(new Date()); + session.saveOrUpdate(transientInstance); + logger.debug("save successful"); + } catch (RuntimeException re) { + logger.error("save failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public void updateRoleName(Integer id, String roleName) { + Secuserrole sur = this.getHibernateTemplate().get(Secuserrole.class, id); + if (sur != null) { + sur.setRoleName(roleName); + sur.setLastUpdateDate(new Date()); + this.getHibernateTemplate().update(sur); + } + } + + @Override + public void delete(Secuserrole persistentInstance) { + logger.debug("deleting Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + session.delete(persistentInstance); + logger.debug("delete successful"); + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public int deleteByOrgcd(String orgcd) { + logger.debug("deleting Secuserrole by orgcd"); + try { + + return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.orgcd =?", orgcd); + + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public int deleteByProviderNo(String providerNo) { + logger.debug("deleting Secuserrole by providerNo"); + try { + + return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.providerNo =?", + providerNo); + + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public int deleteById(Integer id) { + logger.debug("deleting Secuserrole by ID"); + try { + + return getHibernateTemplate().bulkUpdate("delete Secuserrole as model where model.id =?", id); + + } catch (RuntimeException re) { + logger.error("delete failed", re); + throw re; + } + } + + @Override + public int update(Secuserrole instance) { + logger.debug("Update Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + String queryString = "update Secuserrole as model set model.activeyn ='" + instance.getActiveyn() + + "' , lastUpdateDate=now() " + + " where model.providerNo ='" + instance.getProviderNo() + "'" + + " and model.roleName ='" + instance.getRoleName() + "'" + + " and model.orgcd ='" + instance.getOrgcd() + "'"; + + Query queryObject = session.createQuery(queryString); + + return queryObject.executeUpdate(); + + } catch (RuntimeException re) { + logger.error("Update failed", re); + throw re; + } + } + + @Override + public Secuserrole findById(java.lang.Integer id) { + logger.debug("getting Secuserrole instance with id: " + id); + // Session session = getSession(); + Session session = currentSession();; + try { + Secuserrole instance = (Secuserrole) session.get( + "com.quatro.model.security.Secuserrole", id); + return instance; + } catch (RuntimeException re) { + logger.error("get failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public List findByExample(Secuserrole instance) { + // Session session = getSession(); + Session session = currentSession();; + logger.debug("finding Secuserrole instance by example"); + try { + List results = session.createCriteria( + "com.quatro.model.security.Secuserrole").add( + Example.create(instance)) + .list(); + logger.debug("find by example successful, result size: " + + results.size()); + return results; + } catch (RuntimeException re) { + logger.error("find by example failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public List findByProperty(String propertyName, Object value) { + logger.debug("finding Secuserrole instance with property: " + propertyName + + ", value: " + value); + // Session session = getSession(); + Session session = currentSession();; + try { + String queryString = "from Secuserrole as model where model." + + propertyName + "= ?"; + Query queryObject = session.createQuery(queryString); + queryObject.setParameter(0, value); + return queryObject.list(); + } catch (RuntimeException re) { + logger.error("find by property name failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public List findByProviderNo(Object providerNo) { + return findByProperty(PROVIDER_NO, providerNo); + } + + @Override + public List findByRoleName(Object roleName) { + return findByProperty(ROLE_NAME, roleName); + } + + @Override + public List findByOrgcd(Object orgcd, boolean activeOnly) { + // return findByProperty(ORGCD, orgcd); + /* + * SQL: + * select * from secUserRole s, + * (select codecsv from lst_orgcd where code = 'P200011') b + * where b.codecsv like '%' || s.orgcd || ',%' + * and not (s.orgcd like 'R%' or s.orgcd like 'O%') + * + */ + logger.debug("Find staff instance ."); + try { + + String queryString = "select a from Secuserrole a, LstOrgcd b, SecProvider p" + + " where a.providerNo=p.providerNo and b.code ='" + orgcd + "'"; + if (activeOnly) + queryString += " and p.status='1'"; + + queryString = queryString + + " and b.codecsv like '%' || a.orgcd || ',%'" + + " and not (a.orgcd like 'R%' or a.orgcd like 'O%')"; + + return this.getHibernateTemplate().find(queryString); + + } catch (RuntimeException re) { + logger.error("Find staff failed", re); + throw re; + } + + } + + @Override + public List searchByCriteria(StaffForm staffForm) { + + logger.debug("Search staff instance ."); + try { + + String AND = " and "; + // String OR = " or "; + + String orgcd = staffForm.getOrgcd(); + + String queryString = "select a from Secuserrole a, LstOrgcd b" + + " where b.code ='" + orgcd + "'" + + " and b.codecsv like '%' || a.orgcd || ',%'" + + " and not (a.orgcd like 'R%' or a.orgcd like 'O%')"; + + String fname = staffForm.getFirstName(); + String lname = staffForm.getLastName(); + + if (fname != null && fname.length() > 0) { + fname = StringEscapeUtils.escapeSql(fname); + fname = fname.toLowerCase(); + queryString = queryString + AND + "lower(a.providerFName) like '%" + fname + "%'"; + } + if (lname != null && lname.length() > 0) { + lname = StringEscapeUtils.escapeSql(lname); + lname = lname.toLowerCase(); + queryString = queryString + AND + "lower(a.providerLName) like '%" + lname + "%'"; + } + + return this.getHibernateTemplate().find(queryString); + + } catch (RuntimeException re) { + logger.error("Search staff failed", re); + throw re; + } + } + + @Override + public List findByActiveyn(Object activeyn) { + return findByProperty(ACTIVEYN, activeyn); + } + + @Override + public List findAll() { + // Session session = getSession(); + Session session = currentSession();; + logger.debug("finding all Secuserrole instances"); + try { + String queryString = "from Secuserrole"; + Query queryObject = session.createQuery(queryString); + return queryObject.list(); + } catch (RuntimeException re) { + logger.error("find all failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public Secuserrole merge(Secuserrole detachedInstance) { + logger.debug("merging Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + detachedInstance.setLastUpdateDate(new Date()); + Secuserrole result = (Secuserrole) session.merge( + detachedInstance); + logger.debug("merge successful"); + return result; + } catch (RuntimeException re) { + logger.error("merge failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public void attachDirty(Secuserrole instance) { + logger.debug("attaching dirty Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + instance.setLastUpdateDate(new Date()); + session.saveOrUpdate(instance); + logger.debug("attach successful"); + } catch (RuntimeException re) { + logger.error("attach failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } + + @Override + public void attachClean(Secuserrole instance) { + logger.debug("attaching clean Secuserrole instance"); + // Session session = getSession(); + Session session = currentSession();; + try { + session.lock(instance, LockMode.NONE); + logger.debug("attach successful"); + } catch (RuntimeException re) { + logger.error("attach failed", re); + throw re; + } + // finally { + // this.releaseSession(session); + // } + } +} diff --git a/src/main/java/com/quatro/dao/security/UserAccessDao.java b/src/main/java/com/quatro/dao/security/UserAccessDao.java index 9cb4e289eb..dfcff3a243 100644 --- a/src/main/java/com/quatro/dao/security/UserAccessDao.java +++ b/src/main/java/com/quatro/dao/security/UserAccessDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,43 +18,18 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.dao.security; import java.util.List; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; -public class UserAccessDao extends HibernateDaoSupport { - public List GetUserAccessList(String providerNo, Integer shelterId) - { - String sSQL=""; - if (shelterId != null && shelterId.intValue()>0) { - String s = "'%S" + shelterId.toString() + ",%'"; - sSQL = "from UserAccessValue s where s.providerNo= ? " + - " and s.orgCdcsv like " + s + " order by s.functionCd, s.privilege desc, s.orgCd"; - } - else - { - sSQL = "from UserAccessValue s where s.providerNo= ? " + - " order by s.functionCd, s.privilege desc, s.orgCd"; - } - return getHibernateTemplate().find(sSQL ,providerNo); - } - - public List GetUserOrgAccessList(String providerNo, Integer shelterId) - { - String sSQL=""; - if (shelterId != null && shelterId.intValue() > 0) { - sSQL="select distinct o.codecsv from UserAccessValue s, LstOrgcd o " + - "where s.providerNo= ? and s.privilege>='r' and s.orgCd=o.code " + - " and o.codecsv like '%S" + shelterId.toString() + ",%'" + - " order by o.codecsv"; - return getHibernateTemplate().find(sSQL ,providerNo); - } - else - { - sSQL="select distinct o.codecsv from UserAccessValue s, LstOrgcd o where s.providerNo= ? and s.privilege>='r' and s.orgCd=o.code order by o.codecsv"; - return getHibernateTemplate().find(sSQL ,providerNo); - } - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public interface UserAccessDao { + public List GetUserAccessList(String providerNo, Integer shelterId); + + public List GetUserOrgAccessList(String providerNo, Integer shelterId); + } diff --git a/src/main/java/com/quatro/dao/security/UserAccessDaoImpl.java b/src/main/java/com/quatro/dao/security/UserAccessDaoImpl.java new file mode 100644 index 0000000000..6f4b9ee14e --- /dev/null +++ b/src/main/java/com/quatro/dao/security/UserAccessDaoImpl.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ +package com.quatro.dao.security; + +import java.util.List; + +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class UserAccessDaoImpl extends HibernateDaoSupport implements UserAccessDao { + + @Override + public List GetUserAccessList(String providerNo, Integer shelterId) { + String sSQL = ""; + if (shelterId != null && shelterId.intValue() > 0) { + String s = "'%S" + shelterId.toString() + ",%'"; + sSQL = "from UserAccessValue s where s.providerNo= ? " + + " and s.orgCdcsv like " + s + " order by s.functionCd, s.privilege desc, s.orgCd"; + } else { + sSQL = "from UserAccessValue s where s.providerNo= ? " + + " order by s.functionCd, s.privilege desc, s.orgCd"; + } + return getHibernateTemplate().find(sSQL, providerNo); + } + + @Override + public List GetUserOrgAccessList(String providerNo, Integer shelterId) { + String sSQL = ""; + if (shelterId != null && shelterId.intValue() > 0) { + sSQL = "select distinct o.codecsv from UserAccessValue s, LstOrgcd o " + + "where s.providerNo= ? and s.privilege>='r' and s.orgCd=o.code " + + " and o.codecsv like '%S" + shelterId.toString() + ",%'" + + " order by o.codecsv"; + return getHibernateTemplate().find(sSQL, providerNo); + } else { + sSQL = "select distinct o.codecsv from UserAccessValue s, LstOrgcd o where s.providerNo= ? and s.privilege>='r' and s.orgCd=o.code order by o.codecsv"; + return getHibernateTemplate().find(sSQL, providerNo); + } + } +} diff --git a/src/main/java/com/quatro/service/LookupManager.java b/src/main/java/com/quatro/service/LookupManager.java index 3bd6b6132d..a86b14cdbd 100644 --- a/src/main/java/com/quatro/service/LookupManager.java +++ b/src/main/java/com/quatro/service/LookupManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,62 +18,24 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.service; import java.sql.SQLException; import java.util.List; - -import com.quatro.dao.LookupDao; import com.quatro.model.LookupCodeValue; import com.quatro.model.LookupTableDefValue; -public class LookupManager { - private LookupDao lookupDao=null; - - public List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc) { - return lookupDao.LoadCodeList(tableId, activeOnly, code, codeDesc); - } - - public List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc) { - return lookupDao.LoadCodeList(tableId, activeOnly,parentCode, code, codeDesc); - } - - public LookupTableDefValue GetLookupTableDef(String tableId){ - return lookupDao.GetLookupTableDef(tableId); - } - - public LookupCodeValue GetLookupCode(String tableId, String code){ - return lookupDao.GetCode(tableId, code); - } - - public LookupDao getLookupDao() { - return lookupDao; - } - - public void setLookupDao(LookupDao lookupDao) { - this.lookupDao = lookupDao; - } - - public List LoadFieldDefList(String tableId) - { - return lookupDao.LoadFieldDefList(tableId); - } - public List GetCodeFieldValues(LookupTableDefValue tableDef, String code) - { - return lookupDao.GetCodeFieldValues(tableDef, code); - } - public List GetCodeFieldValues(LookupTableDefValue tableDef) - { - return lookupDao.GetCodeFieldValues(tableDef); - } - public String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException - { - return lookupDao.SaveCodeValue(isNew, tableDef, fieldDefList); - } - - public int getCountOfActiveClient(String orgCd) throws SQLException{ - return lookupDao.getCountOfActiveClient(orgCd); - } - +public interface LookupManager { + List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc); + List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc); + LookupTableDefValue GetLookupTableDef(String tableId); + LookupCodeValue GetLookupCode(String tableId, String code); + List LoadFieldDefList(String tableId); + List GetCodeFieldValues(LookupTableDefValue tableDef, String code); + List GetCodeFieldValues(LookupTableDefValue tableDef); + String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException; + int getCountOfActiveClient(String orgCd) throws SQLException; } diff --git a/src/main/java/com/quatro/service/LookupManagerImpl.java b/src/main/java/com/quatro/service/LookupManagerImpl.java new file mode 100644 index 0000000000..fc1a9606a9 --- /dev/null +++ b/src/main/java/com/quatro/service/LookupManagerImpl.java @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ +package com.quatro.service; + +import java.sql.SQLException; +import java.util.List; +import com.quatro.dao.LookupDao; +import com.quatro.model.LookupCodeValue; +import com.quatro.model.LookupTableDefValue; +import com.quatro.service.LookupManager; + +public class LookupManagerImpl implements LookupManager { + private LookupDao lookupDao=null; + + public List LoadCodeList(String tableId, boolean activeOnly, String code, String codeDesc) { + return lookupDao.LoadCodeList(tableId, activeOnly, code, codeDesc); + } + + public List LoadCodeList(String tableId, boolean activeOnly, String parentCode, String code, String codeDesc) { + return lookupDao.LoadCodeList(tableId, activeOnly,parentCode, code, codeDesc); + } + + public LookupTableDefValue GetLookupTableDef(String tableId){ + return lookupDao.GetLookupTableDef(tableId); + } + + public LookupCodeValue GetLookupCode(String tableId, String code){ + return lookupDao.GetCode(tableId, code); + } + + public List LoadFieldDefList(String tableId) { + return lookupDao.LoadFieldDefList(tableId); + } + + public List GetCodeFieldValues(LookupTableDefValue tableDef, String code) { + return lookupDao.GetCodeFieldValues(tableDef, code); + } + + public List GetCodeFieldValues(LookupTableDefValue tableDef) { + return lookupDao.GetCodeFieldValues(tableDef); + } + + public String SaveCodeValue(boolean isNew, LookupTableDefValue tableDef, List fieldDefList) throws SQLException { + return lookupDao.SaveCodeValue(isNew, tableDef, fieldDefList); + } + + public int getCountOfActiveClient(String orgCd) throws SQLException{ + return lookupDao.getCountOfActiveClient(orgCd); + } + + public LookupDao getLookupDao() { + return lookupDao; + } + + public void setLookupDao(LookupDao lookupDao) { + this.lookupDao = lookupDao; + } +} diff --git a/src/main/java/com/quatro/service/security/RolesManager.java b/src/main/java/com/quatro/service/security/RolesManager.java index 8115a4e338..f3189e909b 100644 --- a/src/main/java/com/quatro/service/security/RolesManager.java +++ b/src/main/java/com/quatro/service/security/RolesManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,102 +20,35 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - - package com.quatro.service.security; -import java.util.ArrayList; import java.util.List; -import org.springframework.transaction.annotation.Transactional; - -import com.quatro.dao.security.SecobjprivilegeDao; -import com.quatro.dao.security.SecroleDao; import com.quatro.model.security.Secobjprivilege; import com.quatro.model.security.Secrole; -@Transactional -public class RolesManager { - - private SecroleDao secroleDao; - private SecobjprivilegeDao secobjprivilegeDao; - - public void setSecroleDao(SecroleDao dao) { - this.secroleDao = dao; - } - - public List getRoles() { - return secroleDao.getRoles(); - } - - public Secrole getRole(String id) { - return secroleDao.getRole(Integer.parseInt(id)); - } - - public Secrole getRole(int id) { - return secroleDao.getRole(id); - } - - public Secrole getRoleByRolename(String roleName) { - return secroleDao.getRoleByName(roleName); - } - - public void save(Secrole secrole) { - secroleDao.save(secrole); - } +public interface RolesManager { - public void saveFunction(Secobjprivilege secobjprivilege) { - secobjprivilegeDao.save(secobjprivilege); - } + List getRoles(); - public void saveFunctions(Secrole secrole, List newLst, String roleName) { - if(secrole!=null) secroleDao.save(secrole); - List existLst = secobjprivilegeDao.getFunctions(roleName); + Secrole getRole(String id); - ArrayList lstForDelete = new ArrayList(); - for(int i = 0; i < existLst.size(); i++){ - boolean keepIt = false; - Secobjprivilege sur1 = (Secobjprivilege)existLst.get(i); - for(int j = 0; j < newLst.size(); j++){ - Secobjprivilege sur2 = (Secobjprivilege)newLst.get(j); - if(compare(sur1, sur2)){ - keepIt = true; - break; - } - } - if(!keepIt) lstForDelete.add(sur1); - } - for( int i = 0; i < lstForDelete.size(); i++){ - secobjprivilegeDao.delete((Secobjprivilege)lstForDelete.get(i)); - } + Secrole getRole(int id); - secobjprivilegeDao.saveAll(newLst); - } + Secrole getRoleByRolename(String roleName); - public boolean compare(Secobjprivilege sur1, Secobjprivilege sur2){ - boolean isSame = false; - if(sur1.getObjectname_code().equals(sur2.getObjectname_code()) && - sur1.getPrivilege_code().equals(sur2.getPrivilege_code()) && - sur1.getRoleusergroup().equals(sur2.getRoleusergroup())) - isSame = true; - return isSame; - } + void save(Secrole secrole); - public List getFunctions(String roleName) { - return secobjprivilegeDao.getFunctions(roleName); - } + void saveFunction(Secobjprivilege secobjprivilege); - public String getFunctionDesc(String function_code ) { - return secobjprivilegeDao.getFunctionDesc(function_code); - } + void saveFunctions(Secrole secrole, List newLst, String roleName); - public String getAccessDesc(String accessType_code ) { - return secobjprivilegeDao.getAccessDesc(accessType_code); - } + List getFunctions(String roleName); - public void setSecobjprivilegeDao(SecobjprivilegeDao secobjprivilegeDao) { - this.secobjprivilegeDao = secobjprivilegeDao; - } + String getFunctionDesc(String function_code); + String getAccessDesc(String accessType_code); } diff --git a/src/main/java/com/quatro/service/security/RolesManagerImpl.java b/src/main/java/com/quatro/service/security/RolesManagerImpl.java new file mode 100644 index 0000000000..7a1f5563dd --- /dev/null +++ b/src/main/java/com/quatro/service/security/RolesManagerImpl.java @@ -0,0 +1,123 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + +package com.quatro.service.security; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.transaction.annotation.Transactional; + +import com.quatro.dao.security.SecobjprivilegeDao; +import com.quatro.dao.security.SecroleDao; +import com.quatro.model.security.Secobjprivilege; +import com.quatro.model.security.Secrole; + +@Transactional +public class RolesManagerImpl implements RolesManager{ + + private SecroleDao secroleDao; + private SecobjprivilegeDao secobjprivilegeDao; + + public void setSecroleDao(SecroleDao dao) { + this.secroleDao = dao; + } + + public List getRoles() { + return secroleDao.getRoles(); + } + + public Secrole getRole(String id) { + return secroleDao.getRole(Integer.parseInt(id)); + } + + public Secrole getRole(int id) { + return secroleDao.getRole(id); + } + + public Secrole getRoleByRolename(String roleName) { + return secroleDao.getRoleByName(roleName); + } + + public void save(Secrole secrole) { + secroleDao.save(secrole); + } + + public void saveFunction(Secobjprivilege secobjprivilege) { + secobjprivilegeDao.save(secobjprivilege); + } + + public void saveFunctions(Secrole secrole, List newLst, String roleName) { + if(secrole!=null) secroleDao.save(secrole); + List existLst = secobjprivilegeDao.getFunctions(roleName); + + ArrayList lstForDelete = new ArrayList(); + for(int i = 0; i < existLst.size(); i++){ + boolean keepIt = false; + Secobjprivilege sur1 = (Secobjprivilege)existLst.get(i); + for(int j = 0; j < newLst.size(); j++){ + Secobjprivilege sur2 = (Secobjprivilege)newLst.get(j); + if(compare(sur1, sur2)){ + keepIt = true; + break; + } + } + if(!keepIt) lstForDelete.add(sur1); + } + for( int i = 0; i < lstForDelete.size(); i++){ + secobjprivilegeDao.delete((Secobjprivilege)lstForDelete.get(i)); + } + + secobjprivilegeDao.saveAll(newLst); + } + + public boolean compare(Secobjprivilege sur1, Secobjprivilege sur2){ + boolean isSame = false; + if(sur1.getObjectname_code().equals(sur2.getObjectname_code()) && + sur1.getPrivilege_code().equals(sur2.getPrivilege_code()) && + sur1.getRoleusergroup().equals(sur2.getRoleusergroup())) + isSame = true; + return isSame; + } + + public List getFunctions(String roleName) { + return secobjprivilegeDao.getFunctions(roleName); + } + + public String getFunctionDesc(String function_code ) { + return secobjprivilegeDao.getFunctionDesc(function_code); + } + + public String getAccessDesc(String accessType_code ) { + return secobjprivilegeDao.getAccessDesc(accessType_code); + } + + public void setSecobjprivilegeDao(SecobjprivilegeDao secobjprivilegeDao) { + this.secobjprivilegeDao = secobjprivilegeDao; + } + +} diff --git a/src/main/java/com/quatro/service/security/SecurityManager.java b/src/main/java/com/quatro/service/security/SecurityManager.java index 0784f0c754..3c9337472b 100644 --- a/src/main/java/com/quatro/service/security/SecurityManager.java +++ b/src/main/java/com/quatro/service/security/SecurityManager.java @@ -55,7 +55,7 @@ public void setUserOrgAccessList(List orgAccessList) { public boolean hasReadAccess(String objectName, String roleNames) { boolean result=false; - SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean("secobjprivilegeDao"); + SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean(SecobjprivilegeDao.class); List rl = new ArrayList(); for(String tmp:roleNames.split(",")) { @@ -82,7 +82,7 @@ public boolean hasWriteAccess(String objectName, String roleNames) { public boolean hasWriteAccess(String objectName, String roleNames, boolean required) { boolean result=false; - SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean("secobjprivilegeDao"); + SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean(SecobjprivilegeDao.class); List rl = new ArrayList(); for(String tmp:roleNames.split(",")) { @@ -108,7 +108,7 @@ public boolean hasWriteAccess(String objectName, String roleNames, boolean requi public boolean hasDeleteAccess(String objectName, String roleNames) { boolean result=false; - SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean("secobjprivilegeDao"); + SecobjprivilegeDao secobjprivilegeDao = (SecobjprivilegeDao)SpringUtils.getBean(SecobjprivilegeDao.class); List rl = new ArrayList(); for(String tmp:roleNames.split(",")) { diff --git a/src/main/java/com/quatro/service/security/UserAccessManager.java b/src/main/java/com/quatro/service/security/UserAccessManager.java index c2157e997e..d927dbcdb3 100644 --- a/src/main/java/com/quatro/service/security/UserAccessManager.java +++ b/src/main/java/com/quatro/service/security/UserAccessManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,8 +18,11 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ package com.quatro.service.security; + import java.util.ArrayList; import java.util.Hashtable; import java.util.List; @@ -28,64 +32,9 @@ import com.quatro.dao.security.UserAccessDao; import com.quatro.model.security.UserAccessValue; import com.quatro.service.LookupManager; -public class UserAccessManager -{ - private UserAccessDao _dao=null; - public SecurityManager getUserSecurityManager(String providerNo,Integer shelterId, LookupManager lkManager) - { - // _list is ordered by Function, privilege (desc) and the org - SecurityManager secManager = new SecurityManager(); - - Hashtable functionList = new Hashtable(); - List list = _dao.GetUserAccessList(providerNo,shelterId); - if (list.size()>0) { - int startIdx = 0; - List orgList = getAccessListForFunction(list,startIdx); - UserAccessValue uav = (UserAccessValue)list.get(startIdx); - functionList.put(uav.getFunctionCd(), orgList); - - while(orgList != null && startIdx + orgList.size() 0 && orgRoot!=null && orgRoot.equals(orgs.get(0))) - { - orgs.clear(); - } - secManager.setUserOrgAccessList(orgs); - return secManager; - } - private List getAccessListForFunction(List list, int startIdx) - { - if (startIdx >= list.size()) return null; - List orgList = new ArrayList(); - UserAccessValue uofv = (UserAccessValue) list.get(startIdx); - String functionCd = uofv.getFunctionCd(); - orgList.add(uofv); - startIdx ++; - while (startIdx < list.size()) { - uofv = (UserAccessValue) list.get(startIdx); - if (uofv.getFunctionCd().equals(functionCd)) { - orgList.add(uofv); - startIdx ++; - } - else - { - break; - } - } - return orgList; - } - public void setUserAccessDao(UserAccessDao dao) - { - _dao = dao; - } + +public interface UserAccessManager { + SecurityManager getUserSecurityManager(String providerNo, Integer shelterId, LookupManager lkManager); + List getAccessListForFunction(List list, int startIdx); + void setUserAccessDao(UserAccessDao dao); } diff --git a/src/main/java/com/quatro/service/security/UserAccessManagerImpl.java b/src/main/java/com/quatro/service/security/UserAccessManagerImpl.java new file mode 100644 index 0000000000..8a0acb24de --- /dev/null +++ b/src/main/java/com/quatro/service/security/UserAccessManagerImpl.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ +package com.quatro.service.security; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import oscar.OscarProperties; + +import com.quatro.dao.security.UserAccessDao; +import com.quatro.model.security.UserAccessValue; +import com.quatro.service.LookupManager; + +public class UserAccessManagerImpl implements UserAccessManager { + private UserAccessDao _dao = null; + + @Override + public SecurityManager getUserSecurityManager(String providerNo, Integer shelterId, LookupManager lkManager) { + // _list is ordered by Function, privilege (desc) and the org + SecurityManager secManager = new SecurityManager(); + + Hashtable functionList = new Hashtable(); + List list = _dao.GetUserAccessList(providerNo,shelterId); + if (list.size()>0) { + int startIdx = 0; + List orgList = getAccessListForFunction(list,startIdx); + UserAccessValue uav = (UserAccessValue)list.get(startIdx); + functionList.put(uav.getFunctionCd(), orgList); + + while(orgList != null && startIdx + orgList.size() 0 && orgRoot!=null && orgRoot.equals(orgs.get(0))) + { + orgs.clear(); + } + secManager.setUserOrgAccessList(orgs); + return secManager; + } + + @Override + public List getAccessListForFunction(List list, int startIdx) { + if (startIdx >= list.size()) return null; + List orgList = new ArrayList(); + UserAccessValue uofv = (UserAccessValue) list.get(startIdx); + String functionCd = uofv.getFunctionCd(); + orgList.add(uofv); + startIdx ++; + while (startIdx < list.size()) { + uofv = (UserAccessValue) list.get(startIdx); + if (uofv.getFunctionCd().equals(functionCd)) { + orgList.add(uofv); + startIdx ++; + } + else + { + break; + } + } + return orgList; + } + + @Override + public void setUserAccessDao(UserAccessDao dao) { + _dao = dao; + } +} diff --git a/src/main/java/org/caisi/core/web/DefaultEncounterIssueAction.java b/src/main/java/org/caisi/core/web/DefaultEncounterIssueAction.java index 3979de84bd..53c414a822 100644 --- a/src/main/java/org/caisi/core/web/DefaultEncounterIssueAction.java +++ b/src/main/java/org/caisi/core/web/DefaultEncounterIssueAction.java @@ -103,7 +103,7 @@ public ActionForward save(ActionMapping mapping,ActionForm form, HttpServletRequ if (issueNames == null || issueNames.length() == 0) { return mapping.findForward("list"); } - IssueDAO issueDao = (IssueDAO) SpringUtils.getBean("IssueDAO"); + IssueDAO issueDao = (IssueDAO) SpringUtils.getBean(IssueDAO.class); if (issueDao == null) { return mapping.findForward("list"); } @@ -174,7 +174,7 @@ public ActionForward remove(ActionMapping mapping,ActionForm form, HttpServletRe if (issueNames == null || issueNames.length() == 0) { return mapping.findForward("list"); } - IssueDAO issueDao = (IssueDAO) SpringUtils.getBean("IssueDAO"); + IssueDAO issueDao = (IssueDAO) SpringUtils.getBean(IssueDAO.class); if (issueDao == null) { return mapping.findForward("list"); } diff --git a/src/main/java/org/caisi/core/web/InfirmAction.java b/src/main/java/org/caisi/core/web/InfirmAction.java index 6d5c9c82ec..739588886b 100644 --- a/src/main/java/org/caisi/core/web/InfirmAction.java +++ b/src/main/java/org/caisi/core/web/InfirmAction.java @@ -53,9 +53,9 @@ public class InfirmAction extends DispatchAction { private static final Logger logger = MiscUtils.getLogger(); - private static InfirmBedProgramManager bpm = (InfirmBedProgramManager) SpringUtils.getBean("infirmBedProgramManager"); - private ProgramManager pm = (ProgramManager) SpringUtils.getBean("programManager"); - private AdmissionManager mgr = (AdmissionManager) SpringUtils.getBean("admissionManager"); + private static InfirmBedProgramManager bpm = (InfirmBedProgramManager) SpringUtils.getBean(InfirmBedProgramManager.class); + private ProgramManager pm = (ProgramManager) SpringUtils.getBean(ProgramManager.class); + private AdmissionManager mgr = (AdmissionManager) SpringUtils.getBean(AdmissionManager.class); public static void updateCurrentProgram(String programId, String providerNo) { diff --git a/src/main/java/org/caisi/dao/BedProgramDao.java b/src/main/java/org/caisi/dao/BedProgramDao.java index 40651a021d..61e4fefb5e 100644 --- a/src/main/java/org/caisi/dao/BedProgramDao.java +++ b/src/main/java/org/caisi/dao/BedProgramDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,72 +20,36 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.caisi.dao; - -import java.util.List; - -import org.hibernate.Hibernate; -import org.hibernate.SQLQuery; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class BedProgramDao extends HibernateDaoSupport { - private String bedType = "Geographical"; - - private List getProgramResultList(String q) { - return getHibernateTemplate().find(q); - } - - private List getProgramResultList(String q1, Object obj) { - return getHibernateTemplate().find(q1, obj); - } - - public List getAllBedProgram() { - String qr = "FROM Program p where p.type = ?"; - List rs = getProgramResultList(qr, bedType); - return rs; - } - - public List getAllProgram() { - String qr = "FROM Program p order by p.name"; - List rs = getProgramResultList(qr); - return rs; - } - - public List getAllProgramNameID() { - String qr = "select p.name, p.id from Program p"; - List rs = getProgramResultList(qr); - return rs; - } - - public List getAllProgramName() { - String qr = "select p.name from Program p"; - List rs = getProgramResultList(qr); - return rs; - } - - public List getProgramIdByName(String name) { - String q = "SELECT p.id FROM Program p WHERE p.name = ?"; - List rs = getProgramResultList(q, name); - return rs; - } - - public String[] getProgramInfo(int programId) { - String[] result = new String[3]; - - SQLQuery query = getSession().createSQLQuery("SELECT name,address,phone,fax from program where id=" + programId); - query.addScalar("name", Hibernate.STRING); - query.addScalar("address", Hibernate.STRING); - query.addScalar("phone", Hibernate.STRING); - query.addScalar("fax", Hibernate.STRING); - Object[] o = (Object[])query.uniqueResult(); - if (o != null) { - result[0] = new String(o[0] + "\n" + o[1]); - result[1] = (String)o[2]; - result[2] = (String)o[3]; - } - return result; - } - -} + package org.caisi.dao; + + import java.util.List; + + import org.hibernate.Hibernate; + import org.hibernate.SQLQuery; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + import org.hibernate.type.StandardBasicTypes; + import org.springframework.beans.factory.annotation.Autowired; + import org.hibernate.SessionFactory; + import org.hibernate.Session; + + public interface BedProgramDao{ + + + public List getAllBedProgram(); + + public List getAllProgram(); + + public List getAllProgramNameID(); + + public List getAllProgramName(); + + public List getProgramIdByName(String name); + + public String[] getProgramInfo(int programId); + + } + \ No newline at end of file diff --git a/src/main/java/org/caisi/dao/BedProgramDaoImpl.java b/src/main/java/org/caisi/dao/BedProgramDaoImpl.java new file mode 100644 index 0000000000..195be66531 --- /dev/null +++ b/src/main/java/org/caisi/dao/BedProgramDaoImpl.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.caisi.dao; + +import java.util.List; + +import org.hibernate.Hibernate; +import org.hibernate.HibernateException; +import org.hibernate.SQLQuery; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.hibernate.type.StandardBasicTypes; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; +import org.hibernate.Session; +public class BedProgramDaoImpl extends HibernateDaoSupport implements BedProgramDao{ + private String bedType = "Geographical"; + + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + private List getProgramResultList(String q) { + return getHibernateTemplate().find(q); + } + + private List getProgramResultList(String q1, Object obj) { + return getHibernateTemplate().find(q1, obj); + } + + public List getAllBedProgram() { + String qr = "FROM Program p where p.type = ?"; + List rs = getProgramResultList(qr, bedType); + return rs; + } + + public List getAllProgram() { + String qr = "FROM Program p order by p.name"; + List rs = getProgramResultList(qr); + return rs; + } + + public List getAllProgramNameID() { + String qr = "select p.name, p.id from Program p"; + List rs = getProgramResultList(qr); + return rs; + } + + public List getAllProgramName() { + String qr = "select p.name from Program p"; + List rs = getProgramResultList(qr); + return rs; + } + + public List getProgramIdByName(String name) { + String q = "SELECT p.id FROM Program p WHERE p.name = ?"; + List rs = getProgramResultList(q, name); + return rs; + } + + public String[] getProgramInfo(int programId) { + String[] result = new String[3]; + Session session = currentSession(); + SQLQuery query = session.createSQLQuery("SELECT name,address,phone,fax from program where id=" + programId); + query.addScalar("name", StandardBasicTypes.STRING); + query.addScalar("address", StandardBasicTypes.STRING); + query.addScalar("phone", StandardBasicTypes.STRING); + query.addScalar("fax", StandardBasicTypes.STRING); + Object[] o = (Object[])query.uniqueResult(); + if (o != null) { + result[0] = new String(o[0] + "\n" + o[1]); + result[1] = (String)o[2]; + result[2] = (String)o[3]; + } + return result; + } + +} diff --git a/src/main/java/org/caisi/dao/DefaultIssueDao.java b/src/main/java/org/caisi/dao/DefaultIssueDao.java index 3a4793e69a..c6029191d6 100644 --- a/src/main/java/org/caisi/dao/DefaultIssueDao.java +++ b/src/main/java/org/caisi/dao/DefaultIssueDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.caisi.dao; @@ -32,61 +35,15 @@ import org.caisi.model.DefaultIssue; import org.oscarehr.common.dao.AbstractDao; -public class DefaultIssueDao extends AbstractDao { +public interface DefaultIssueDao extends AbstractDao { + + public DefaultIssue findDefaultIssue(Integer id); + + public DefaultIssue getLastestDefaultIssue(); + + public List findAll(); + + public void saveDefaultIssue(DefaultIssue issue); - public DefaultIssueDao(){ - super(DefaultIssue.class); - } - - public DefaultIssue findDefaultIssue(Integer id) { - Query query = entityManager.createQuery("select x from DefaultIssue x where x.id = ?1"); - query.setParameter(1, id); - return getSingleResultOrNull(query); - } - - @SuppressWarnings("unchecked") - public DefaultIssue getLastestDefaultIssue() { - Query query = entityManager.createQuery("select x from DefaultIssue x order by x.assignedtime desc"); - query.setMaxResults(1); - List issueList = query.getResultList(); - if (issueList == null || issueList.size() == 0) { - return null; - } - return issueList.get(0); - } - - @SuppressWarnings("unchecked") - public List findAll() { - Query query = entityManager.createQuery("select x from DefaultIssue x order by x.assignedtime desc"); - return query.getResultList(); - } - - public void saveDefaultIssue(DefaultIssue issue) { - if (issue.getId() != null && issue.getId() > 0) { - merge(issue); - } else { - persist(issue); - } - } - - @SuppressWarnings("unchecked") - public String[] findAllDefaultIssueIds() { - Query query = entityManager.createQuery("select x.issueIds from DefaultIssue x order by x.assignedtime"); - query.setMaxResults(1); - List issueIdsList = query.getResultList(); - if (issueIdsList.size() == 0) { - return new String[0]; - } - Set issueIdsSet = new HashSet(); - for (String ids : issueIdsList) { - String[] idsArr = ids.split(","); - for (String id : idsArr) { - if (id.length() > 0) { - issueIdsSet.add(id); - } - } - } - - return issueIdsSet.toArray(new String[issueIdsSet.size()]); - } + public String[] findAllDefaultIssueIds(); } diff --git a/src/main/java/org/caisi/dao/DefaultIssueDaoImpl.java b/src/main/java/org/caisi/dao/DefaultIssueDaoImpl.java new file mode 100644 index 0000000000..18c29c033b --- /dev/null +++ b/src/main/java/org/caisi/dao/DefaultIssueDaoImpl.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.caisi.dao; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.persistence.Query; + +import org.caisi.model.DefaultIssue; +import org.oscarehr.common.dao.AbstractDaoImpl; + +public class DefaultIssueDaoImpl extends AbstractDaoImpl implements DefaultIssueDao{ + + public DefaultIssueDaoImpl(){ + super(DefaultIssue.class); + } + + public DefaultIssue findDefaultIssue(Integer id) { + Query query = entityManager.createQuery("select x from DefaultIssue x where x.id = ?1"); + query.setParameter(1, id); + return getSingleResultOrNull(query); + } + + @SuppressWarnings("unchecked") + public DefaultIssue getLastestDefaultIssue() { + Query query = entityManager.createQuery("select x from DefaultIssue x order by x.assignedtime desc"); + query.setMaxResults(1); + List issueList = query.getResultList(); + if (issueList == null || issueList.size() == 0) { + return null; + } + return issueList.get(0); + } + + @SuppressWarnings("unchecked") + public List findAll() { + Query query = entityManager.createQuery("select x from DefaultIssue x order by x.assignedtime desc"); + return query.getResultList(); + } + + public void saveDefaultIssue(DefaultIssue issue) { + if (issue.getId() != null && issue.getId() > 0) { + merge(issue); + } else { + persist(issue); + } + } + + @SuppressWarnings("unchecked") + public String[] findAllDefaultIssueIds() { + Query query = entityManager.createQuery("select x.issueIds from DefaultIssue x order by x.assignedtime"); + query.setMaxResults(1); + List issueIdsList = query.getResultList(); + if (issueIdsList.size() == 0) { + return new String[0]; + } + Set issueIdsSet = new HashSet(); + for (String ids : issueIdsList) { + String[] idsArr = ids.split(","); + for (String id : idsArr) { + if (id.length() > 0) { + issueIdsSet.add(id); + } + } + } + + return issueIdsSet.toArray(new String[issueIdsSet.size()]); + } +} diff --git a/src/main/java/org/caisi/dao/ProviderDAO.java b/src/main/java/org/caisi/dao/ProviderDAO.java index 64b5624cd7..a1751a6c12 100644 --- a/src/main/java/org/caisi/dao/ProviderDAO.java +++ b/src/main/java/org/caisi/dao/ProviderDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,33 +20,29 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.caisi.dao; - -import java.util.List; - -import org.oscarehr.common.model.Provider; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -/** - * This couldn't possibly work, it's not a spring managed bean according to the xml files. - * But oh well, some one imports this class and tries to have it injected so I'll - * leave the code here so it compiles. what ever... - */ -public class ProviderDAO extends HibernateDaoSupport { - - @SuppressWarnings("unchecked") - public List getProviders() { - return getHibernateTemplate().find("from Provider p order by p.lastName"); - } - - public Provider getProvider(String provider_no) { - return getHibernateTemplate().get(Provider.class, provider_no); - } - - public Provider getProviderByName(String lastName, String firstName) { - return (Provider)getHibernateTemplate().find("from Provider p where p.first_name = ? and p.last_name = ?", new Object[] {firstName, lastName}).get(0); - } - -} + package org.caisi.dao; + + import java.util.List; + + import org.oscarehr.common.model.Provider; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + /** + * This couldn't possibly work, it's not a spring managed bean according to the xml files. + * But oh well, some one imports this class and tries to have it injected so I'll + * leave the code here so it compiles. what ever... + */ + public interface ProviderDAO{ + + public List getProviders(); + + public Provider getProvider(String provider_no); + + public Provider getProviderByName(String lastName, String firstName); + + } + \ No newline at end of file diff --git a/src/main/java/org/caisi/dao/ProviderDAOImpl.java b/src/main/java/org/caisi/dao/ProviderDAOImpl.java new file mode 100644 index 0000000000..930a8c1354 --- /dev/null +++ b/src/main/java/org/caisi/dao/ProviderDAOImpl.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.caisi.dao; + +import java.util.List; + +import org.oscarehr.common.model.Provider; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +/** + * This couldn't possibly work, it's not a spring managed bean according to the xml files. + * But oh well, some one imports this class and tries to have it injected so I'll + * leave the code here so it compiles. what ever... + */ +public class ProviderDAOImpl extends HibernateDaoSupport implements ProviderDAO{ + + @SuppressWarnings("unchecked") + public List getProviders() { + return (List) getHibernateTemplate().find("from Provider p order by p.lastName"); + } + + public Provider getProvider(String provider_no) { + return getHibernateTemplate().get(Provider.class, provider_no); + } + + public Provider getProviderByName(String lastName, String firstName) { + return (Provider)getHibernateTemplate().find("from Provider p where p.first_name = ? and p.last_name = ?", new Object[] {firstName, lastName}).get(0); + } + +} diff --git a/src/main/java/org/caisi/service/DemographicManager.java b/src/main/java/org/caisi/service/DemographicManager.java new file mode 100644 index 0000000000..d66e9b20eb --- /dev/null +++ b/src/main/java/org/caisi/service/DemographicManager.java @@ -0,0 +1,11 @@ +package org.caisi.service; + +import org.oscarehr.common.model.Demographic; +import java.util.List; + +public interface DemographicManager { + Demographic getDemographic(String demographic_no); + List getDemographics(); + List getProgramIdByDemoNo(String demoNo); + List getDemoProgram(Integer demoNo); +} diff --git a/src/main/java/org/caisi/service/DemographicManagerImpl.java b/src/main/java/org/caisi/service/DemographicManagerImpl.java new file mode 100644 index 0000000000..8bb975b792 --- /dev/null +++ b/src/main/java/org/caisi/service/DemographicManagerImpl.java @@ -0,0 +1,36 @@ +package org.caisi.service; + +import org.oscarehr.common.dao.DemographicDao; +import org.oscarehr.common.model.Demographic; +import org.springframework.transaction.annotation.Transactional; +import java.util.List; + +@Transactional +public class DemographicManagerImpl implements DemographicManager { + + private DemographicDao demographicDao = null; + + public void setDemographicDao(DemographicDao demographicDao) { + this.demographicDao = demographicDao; + } + + @Override + public Demographic getDemographic(String demographic_no) { + return demographicDao.getDemographic(demographic_no); + } + + @Override + public List getDemographics() { + return demographicDao.getDemographics(); + } + + @Override + public List getProgramIdByDemoNo(String demoNo) { + return demographicDao.getProgramIdByDemoNo(Integer.parseInt(demoNo)); + } + + @Override + public List getDemoProgram(Integer demoNo) { + return demographicDao.getDemoProgram(demoNo); + } +} diff --git a/src/main/java/org/caisi/service/FacilityMessageManager.java b/src/main/java/org/caisi/service/FacilityMessageManager.java index 7819b60e58..952cfb7a5d 100644 --- a/src/main/java/org/caisi/service/FacilityMessageManager.java +++ b/src/main/java/org/caisi/service/FacilityMessageManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,65 +20,20 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.caisi.service; import java.util.List; - -import org.oscarehr.common.dao.FacilityMessageDao; import org.oscarehr.common.model.FacilityMessage; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class FacilityMessageManager { - - @Autowired - private FacilityMessageDao facilityMessageDao; - - public FacilityMessage getMessage(String messageId) { - return facilityMessageDao.find(Integer.valueOf(messageId)); - } - - public void saveFacilityMessage(FacilityMessage msg) { - if(msg.getId() == null || msg.getId().intValue() == 0) { - msg.setId(null); - facilityMessageDao.persist(msg); - } else { - facilityMessageDao.merge(msg); - } - } - - public List getMessages() { - return facilityMessageDao.getMessages(); - } - public List getMessagesByFacilityId(Integer facilityId) { - if (facilityId == null || facilityId.intValue() == 0) { - return null; - } - return facilityMessageDao.getMessagesByFacilityId(facilityId); - } - - public List getMessagesByFacilityIdOrNull(Integer facilityId) { - if (facilityId == null || facilityId.intValue() == 0) { - return null; - } - return facilityMessageDao.getMessagesByFacilityIdOrNull(facilityId); - } - - public List getMessagesByFacilityIdAndProgramId(Integer facilityId, Integer programId) { - if (facilityId == null || facilityId.intValue() == 0) { - return null; - } - return facilityMessageDao.getMessagesByFacilityIdAndProgramId(facilityId,programId); - } - - public List getMessagesByFacilityIdOrNullAndProgramIdOrNull(Integer facilityId, Integer programId) { - if (facilityId == null || facilityId.intValue() == 0) { - return null; - } - return facilityMessageDao.getMessagesByFacilityIdOrNullAndProgramIdOrNull(facilityId,programId); - } +public interface FacilityMessageManager { + FacilityMessage getMessage(String messageId); + void saveFacilityMessage(FacilityMessage msg); + List getMessages(); + List getMessagesByFacilityId(Integer facilityId); + List getMessagesByFacilityIdOrNull(Integer facilityId); + List getMessagesByFacilityIdAndProgramId(Integer facilityId, Integer programId); + List getMessagesByFacilityIdOrNullAndProgramIdOrNull(Integer facilityId, Integer programId); } diff --git a/src/main/java/org/caisi/service/FacilityMessageManagerImpl.java b/src/main/java/org/caisi/service/FacilityMessageManagerImpl.java new file mode 100644 index 0000000000..9cb6668770 --- /dev/null +++ b/src/main/java/org/caisi/service/FacilityMessageManagerImpl.java @@ -0,0 +1,84 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.caisi.service; + +import java.util.List; +import org.oscarehr.common.dao.FacilityMessageDao; +import org.oscarehr.common.model.FacilityMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class FacilityMessageManagerImpl implements FacilityMessageManager { + + @Autowired + private FacilityMessageDao facilityMessageDao; + + public FacilityMessage getMessage(String messageId) { + return facilityMessageDao.find(Integer.valueOf(messageId)); + } + + public void saveFacilityMessage(FacilityMessage msg) { + if(msg.getId() == null || msg.getId().intValue() == 0) { + msg.setId(null); + facilityMessageDao.persist(msg); + } else { + facilityMessageDao.merge(msg); + } + } + + public List getMessages() { + return facilityMessageDao.getMessages(); + } + + public List getMessagesByFacilityId(Integer facilityId) { + if (facilityId == null || facilityId.intValue() == 0) { + return null; + } + return facilityMessageDao.getMessagesByFacilityId(facilityId); + } + + public List getMessagesByFacilityIdOrNull(Integer facilityId) { + if (facilityId == null || facilityId.intValue() == 0) { + return null; + } + return facilityMessageDao.getMessagesByFacilityIdOrNull(facilityId); + } + + public List getMessagesByFacilityIdAndProgramId(Integer facilityId, Integer programId) { + if (facilityId == null || facilityId.intValue() == 0) { + return null; + } + return facilityMessageDao.getMessagesByFacilityIdAndProgramId(facilityId,programId); + } + + public List getMessagesByFacilityIdOrNullAndProgramIdOrNull(Integer facilityId, Integer programId) { + if (facilityId == null || facilityId.intValue() == 0) { + return null; + } + return facilityMessageDao.getMessagesByFacilityIdOrNullAndProgramIdOrNull(facilityId,programId); + } +} diff --git a/src/main/java/org/caisi/service/InfirmBedProgramManager.java b/src/main/java/org/caisi/service/InfirmBedProgramManager.java index 2a280850cd..9267f1f0d7 100644 --- a/src/main/java/org/caisi/service/InfirmBedProgramManager.java +++ b/src/main/java/org/caisi/service/InfirmBedProgramManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.caisi.service; import java.util.ArrayList; @@ -43,187 +45,24 @@ import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; -@Transactional -public class InfirmBedProgramManager { - private BedProgramDao bedProgramDao; - private DemographicDao demographicDao; - private ProgramProviderDAO programProviderDAOT; - private ProviderDefaultProgramDao providerDefaultProgramDao ; - - private ProgramDao programDao; - - @Required - public void setProviderDefaultProgramDao(ProviderDefaultProgramDao providerDefaultProgramDao) { - this.providerDefaultProgramDao = providerDefaultProgramDao; - } - - @Required - public void setBedProgramDao(BedProgramDao dao) { - this.bedProgramDao = dao; - } - - @Required - public void setProgramDao(ProgramDao dao) { - this.programDao = dao; - } - - @Required - public void setDemographicDao(DemographicDao dao) { - this.demographicDao = dao; - } - - public List getPrgramNameID() { - List rs = bedProgramDao.getAllProgramNameID(); - - return rs; - } - - public List getPrgramName() { - List rs = bedProgramDao.getAllProgramName(); - return rs; - } - - public List getProgramBeans() { - Iterator iter = bedProgramDao.getAllProgram().iterator(); - ArrayList pList = new ArrayList(); - while (iter.hasNext()) { - Program p = (Program)iter.next(); - if (p != null) { - //logger.debug("programName="+p.getName()+"::"+"programId="+p.getId().toString()); - pList.add(new LabelValueBean(p.getName(), p.getId().toString())); - } - } - return pList; - } - - public List getProgramBeans(String providerNo, Integer facilityId) { - if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); - Iterator iter = programProviderDAOT.getProgramProvidersByProvider(providerNo).iterator(); - ArrayList pList = new ArrayList(); - while (iter.hasNext()) { - ProgramProvider p = (ProgramProvider)iter.next(); - if (p != null && p.getProgramId() != null && p.getProgramId().longValue() > 0) { - //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); - Program program = programDao.getProgram(new Integer(p.getProgramId().intValue())); - - if (facilityId!=null && program.getFacilityId()!=facilityId.intValue()) continue; - - if (program != null && program.isActive()) pList.add(new LabelValueBean(program.getName(), program.getId().toString())); - } - } - return pList; - } - - public List getProgramBeansByFacilityId(Integer facilityId) { - if (facilityId <= 0) return new ArrayList(); - Iterator iter = providerDefaultProgramDao.findProgramsByFacilityId(facilityId).iterator(); - ArrayList pList = new ArrayList(); - while (iter.hasNext()) { - Program p = iter.next(); - if (p != null && p.getId() != null && p.getName() != null && p.getName().length() > 0) { - pList.add(new LabelValueBean(p.getName(), p.getId().toString())); - } - } - return pList; - } - - public List getProgramForApptViewBeans(String providerNo, Integer facilityId) { - if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); - Iterator iter = programProviderDAOT.getProgramProvidersByProvider(providerNo).iterator(); - ArrayList pList = new ArrayList(); - while (iter.hasNext()) { - ProgramProvider p = (ProgramProvider)iter.next(); - if (p != null && p.getProgramId() != null && p.getProgramId().longValue() > 0) { - //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); - Program program = programDao.getProgramForApptView(new Integer(p.getProgramId().intValue())); - if(program==null) continue; - if (facilityId!=null && program.getFacilityId()!=facilityId.intValue()) continue; - - if (program.isActive()) pList.add(new LabelValueBean(program.getName(), program.getId().toString())); - } - } - return pList; - } - - public List getDemographicByBedProgramIdBeans(int programId, Date dt, String archiveView) { - /*default time is Oscar default null time 0001-01-01.*/ - Date defdt = new GregorianCalendar(1, 0, 1).getTime(); - - Calendar cal = Calendar.getInstance(); - cal.setTime(dt); - cal.set(Calendar.HOUR_OF_DAY, 23); - cal.set(Calendar.MINUTE, 59); - cal.set(Calendar.SECOND, 59); - dt = cal.getTime(); - Iterator iter; - - if (archiveView != null && archiveView.equals("true")) iter = demographicDao.getArchiveDemographicByProgramOptimized(programId, dt, defdt).iterator(); - else iter = demographicDao.getActiveDemographicByProgram(programId, dt, defdt).iterator(); - - ArrayList demographicList = new ArrayList(); - Demographic de = null; - while (iter.hasNext()) { - de = iter.next(); - //logger.info("demoName="+de.getLastName()+","+de.getFirstName()+"::"+"demoID="+de.getDemographicNo().toString()); - demographicList.add(new LabelValueBean(de.getLastName() + ", " + de.getFirstName(), de.getDemographicNo().toString())); - - } - return demographicList; - } - - public int getDefaultProgramId() { - String defProgramName = "Annex"; - List rs = bedProgramDao.getProgramIdByName(defProgramName); - if (rs.isEmpty()) return 1; - else return ((Integer)rs.get(0)).intValue(); - - } - - public int getDefaultProgramId(String providerNo) { - int defProgramId = 0; - List rs = providerDefaultProgramDao.getProgramByProviderNo(providerNo); - if (rs.isEmpty()) { - //setDefaultProgramId(providerNo,defProgramId); - return defProgramId; - } - else return rs.get(0).getProgramId(); - - } - - public void setDefaultProgramId(String providerNo, int programId) { - providerDefaultProgramDao.setDefaultProgram(providerNo, programId); - } - - public Boolean getProviderSig(String providerNo) { - List list = providerDefaultProgramDao.getProgramByProviderNo(providerNo); - if (list.isEmpty()) { - ProviderDefaultProgram pdp = new ProviderDefaultProgram(); - pdp.setProgramId(new Integer(0)); - pdp.setProviderNo(providerNo); - pdp.setSign(false); - providerDefaultProgramDao.saveProviderDefaultProgram(pdp); - return(new Boolean(false)); - } - ProviderDefaultProgram pro = list.get(0); - return new Boolean(pro.isSign()); - - } - - public void toggleSig(String providerNo) { - providerDefaultProgramDao.toggleSig(providerNo); - - } - - public ProgramProviderDAO getProgramProviderDAOT() { - return programProviderDAOT; - } - - public void setProgramProviderDAOT(ProgramProviderDAO programProviderDAOT) { - this.programProviderDAOT = programProviderDAOT; - } - - public String[] getProgramInformation(int programId) { - return this.bedProgramDao.getProgramInfo(programId); - } - +public interface InfirmBedProgramManager { + void setProviderDefaultProgramDao(ProviderDefaultProgramDao providerDefaultProgramDao); + void setBedProgramDao(BedProgramDao dao); + void setProgramDao(ProgramDao dao); + void setDemographicDao(DemographicDao dao); + List getPrgramNameID(); + List getPrgramName(); + List getProgramBeans(); + List getProgramBeans(String providerNo, Integer facilityId); + List getProgramBeansByFacilityId(Integer facilityId); + List getProgramForApptViewBeans(String providerNo, Integer facilityId); + List getDemographicByBedProgramIdBeans(int programId, Date dt, String archiveView); + int getDefaultProgramId(); + int getDefaultProgramId(String providerNo); + void setDefaultProgramId(String providerNo, int programId); + Boolean getProviderSig(String providerNo); + void toggleSig(String providerNo); + ProgramProviderDAO getProgramProviderDAOT(); + void setProgramProviderDAOT(ProgramProviderDAO programProviderDAOT); + String[] getProgramInformation(int programId); } diff --git a/src/main/java/org/caisi/service/InfirmBedProgramManagerImpl.java b/src/main/java/org/caisi/service/InfirmBedProgramManagerImpl.java new file mode 100644 index 0000000000..b913d55794 --- /dev/null +++ b/src/main/java/org/caisi/service/InfirmBedProgramManagerImpl.java @@ -0,0 +1,232 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.caisi.service; + + import java.util.ArrayList; + import java.util.Calendar; + import java.util.Date; + import java.util.GregorianCalendar; + import java.util.Iterator; + import java.util.List; + + import org.apache.struts.util.LabelValueBean; + import org.caisi.dao.BedProgramDao; + import org.oscarehr.PMmodule.dao.ProgramDao; + import org.oscarehr.PMmodule.dao.ProgramProviderDAO; + import org.oscarehr.PMmodule.model.Program; + import org.oscarehr.PMmodule.model.ProgramProvider; + import org.oscarehr.common.dao.DemographicDao; + import org.oscarehr.common.dao.ProviderDefaultProgramDao; + import org.oscarehr.common.model.Demographic; + import org.oscarehr.common.model.ProviderDefaultProgram; + import org.springframework.beans.factory.annotation.Required; + import org.springframework.transaction.annotation.Transactional; + + @Transactional + public class InfirmBedProgramManagerImpl implements InfirmBedProgramManager{ + private BedProgramDao bedProgramDao; + private DemographicDao demographicDao; + private ProgramProviderDAO programProviderDAOT; + private ProviderDefaultProgramDao providerDefaultProgramDao ; + + private ProgramDao programDao; + + @Required + public void setProviderDefaultProgramDao(ProviderDefaultProgramDao providerDefaultProgramDao) { + this.providerDefaultProgramDao = providerDefaultProgramDao; + } + + @Required + public void setBedProgramDao(BedProgramDao dao) { + this.bedProgramDao = dao; + } + + @Required + public void setProgramDao(ProgramDao dao) { + this.programDao = dao; + } + + @Required + public void setDemographicDao(DemographicDao dao) { + this.demographicDao = dao; + } + + public List getPrgramNameID() { + List rs = bedProgramDao.getAllProgramNameID(); + + return rs; + } + + public List getPrgramName() { + List rs = bedProgramDao.getAllProgramName(); + return rs; + } + + public List getProgramBeans() { + Iterator iter = bedProgramDao.getAllProgram().iterator(); + ArrayList pList = new ArrayList(); + while (iter.hasNext()) { + Program p = (Program)iter.next(); + if (p != null) { + //logger.debug("programName="+p.getName()+"::"+"programId="+p.getId().toString()); + pList.add(new LabelValueBean(p.getName(), p.getId().toString())); + } + } + return pList; + } + + public List getProgramBeans(String providerNo, Integer facilityId) { + if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); + Iterator iter = programProviderDAOT.getProgramProvidersByProvider(providerNo).iterator(); + ArrayList pList = new ArrayList(); + while (iter.hasNext()) { + ProgramProvider p = (ProgramProvider)iter.next(); + if (p != null && p.getProgramId() != null && p.getProgramId().longValue() > 0) { + //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); + Program program = programDao.getProgram(new Integer(p.getProgramId().intValue())); + + if (facilityId!=null && program.getFacilityId()!=facilityId.intValue()) continue; + + if (program != null && program.isActive()) pList.add(new LabelValueBean(program.getName(), program.getId().toString())); + } + } + return pList; + } + + public List getProgramBeansByFacilityId(Integer facilityId) { + if (facilityId <= 0) return new ArrayList(); + Iterator iter = providerDefaultProgramDao.findProgramsByFacilityId(facilityId).iterator(); + ArrayList pList = new ArrayList(); + while (iter.hasNext()) { + Program p = iter.next(); + if (p != null && p.getId() != null && p.getName() != null && p.getName().length() > 0) { + pList.add(new LabelValueBean(p.getName(), p.getId().toString())); + } + } + return pList; + } + + public List getProgramForApptViewBeans(String providerNo, Integer facilityId) { + if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); + Iterator iter = programProviderDAOT.getProgramProvidersByProvider(providerNo).iterator(); + ArrayList pList = new ArrayList(); + while (iter.hasNext()) { + ProgramProvider p = (ProgramProvider)iter.next(); + if (p != null && p.getProgramId() != null && p.getProgramId().longValue() > 0) { + //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); + Program program = programDao.getProgramForApptView(new Integer(p.getProgramId().intValue())); + if(program==null) continue; + if (facilityId!=null && program.getFacilityId()!=facilityId.intValue()) continue; + + if (program.isActive()) pList.add(new LabelValueBean(program.getName(), program.getId().toString())); + } + } + return pList; + } + + public List getDemographicByBedProgramIdBeans(int programId, Date dt, String archiveView) { + /*default time is Oscar default null time 0001-01-01.*/ + Date defdt = new GregorianCalendar(1, 0, 1).getTime(); + + Calendar cal = Calendar.getInstance(); + cal.setTime(dt); + cal.set(Calendar.HOUR_OF_DAY, 23); + cal.set(Calendar.MINUTE, 59); + cal.set(Calendar.SECOND, 59); + dt = cal.getTime(); + Iterator iter; + + if (archiveView != null && archiveView.equals("true")) iter = demographicDao.getArchiveDemographicByProgramOptimized(programId, dt, defdt).iterator(); + else iter = demographicDao.getActiveDemographicByProgram(programId, dt, defdt).iterator(); + + ArrayList demographicList = new ArrayList(); + Demographic de = null; + while (iter.hasNext()) { + de = iter.next(); + //logger.info("demoName="+de.getLastName()+","+de.getFirstName()+"::"+"demoID="+de.getDemographicNo().toString()); + demographicList.add(new LabelValueBean(de.getLastName() + ", " + de.getFirstName(), de.getDemographicNo().toString())); + + } + return demographicList; + } + + public int getDefaultProgramId() { + String defProgramName = "Annex"; + List rs = bedProgramDao.getProgramIdByName(defProgramName); + if (rs.isEmpty()) return 1; + else return ((Integer)rs.get(0)).intValue(); + + } + + public int getDefaultProgramId(String providerNo) { + int defProgramId = 0; + List rs = providerDefaultProgramDao.getProgramByProviderNo(providerNo); + if (rs.isEmpty()) { + //setDefaultProgramId(providerNo,defProgramId); + return defProgramId; + } + else return rs.get(0).getProgramId(); + + } + + public void setDefaultProgramId(String providerNo, int programId) { + providerDefaultProgramDao.setDefaultProgram(providerNo, programId); + } + + public Boolean getProviderSig(String providerNo) { + List list = providerDefaultProgramDao.getProgramByProviderNo(providerNo); + if (list.isEmpty()) { + ProviderDefaultProgram pdp = new ProviderDefaultProgram(); + pdp.setProgramId(new Integer(0)); + pdp.setProviderNo(providerNo); + pdp.setSign(false); + providerDefaultProgramDao.saveProviderDefaultProgram(pdp); + return(new Boolean(false)); + } + ProviderDefaultProgram pro = list.get(0); + return new Boolean(pro.isSign()); + + } + + public void toggleSig(String providerNo) { + providerDefaultProgramDao.toggleSig(providerNo); + + } + + public ProgramProviderDAO getProgramProviderDAOT() { + return programProviderDAOT; + } + + public void setProgramProviderDAOT(ProgramProviderDAO programProviderDAOT) { + this.programProviderDAOT = programProviderDAOT; + } + + public String[] getProgramInformation(int programId) { + return this.bedProgramDao.getProgramInfo(programId); + } + + } \ No newline at end of file diff --git a/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManager.java b/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManager.java index 87a934b30d..6f164555fd 100644 --- a/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManager.java +++ b/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,69 +20,16 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.caisi.tickler.prepared; -import java.io.File; -import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.Logger; -import org.oscarehr.util.MiscUtils; - -public class PreparedTicklerManager { - - static Logger log=MiscUtils.getLogger(); - - private List ticklers; - - public PreparedTicklerManager() { - ticklers = new ArrayList(); - } - - /* loads up the runtime plugins */ - public void setPath(String path) { - ticklers.clear(); - File f = new File(path + "/WEB-INF/classes/org/caisi/tickler/prepared/runtime"); - if(f.isDirectory()) { - File[] files = f.listFiles(); - for(int x=0;x getTicklers() { - return ticklers; - } - - public PreparedTickler getTickler(String name) { - for(int x=0;x getTicklers(); + PreparedTickler getTickler(String name); } diff --git a/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManagerImpl.java b/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManagerImpl.java new file mode 100644 index 0000000000..3df2e00fb6 --- /dev/null +++ b/src/main/java/org/caisi/tickler/prepared/PreparedTicklerManagerImpl.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.caisi.tickler.prepared; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.util.MiscUtils; + +public class PreparedTicklerManagerImpl implements PreparedTicklerManager { + + static Logger log=MiscUtils.getLogger(); + + private List ticklers; + + public PreparedTicklerManagerImpl() { + ticklers = new ArrayList(); + } + + /* loads up the runtime plugins */ + public void setPath(String path) { + ticklers.clear(); + File f = new File(path + "/WEB-INF/classes/org/caisi/tickler/prepared/runtime"); + if(f.isDirectory()) { + File[] files = f.listFiles(); + for(int x=0;x getTicklers() { + return ticklers; + } + + public PreparedTickler getTickler(String name) { + for(int x=0;x facilities = facilityDao.findAll(true); for (Facility facility : facilities) { @@ -349,8 +366,6 @@ public void pushAllFacilities(LoggedInInfo loggedInInfo) { } } } - - private void pushAllDataForOneFacility(LoggedInInfo loggedInInfo, Facility facility) throws IOException { logger.info("Start pushing data for facility : " + facility.getId() + " : " + facility.getName()); @@ -361,150 +376,171 @@ private void pushAllDataForOneFacility(LoggedInInfo loggedInInfo, Facility facil String password = facility.getIntegratorPassword(); if (integratorBaseUrl == null || user == null || password == null) { - logger.warn("Integrator is enabled but information is incomplete. facilityId=" + facility.getId() + ", user=" + user + ", password=" + password + ", url=" + integratorBaseUrl); + logger.warn("Integrator is enabled but information is incomplete. facilityId=" + facility.getId() + + ", user=" + user + ", password=" + password + ", url=" + integratorBaseUrl); return; } - + FacilityWs facilityWs = CaisiIntegratorManager.getFacilityWs(loggedInInfo, facility); org.oscarehr.caisi_integrator.ws.CachedFacility cachedFacility = facilityWs.getMyFacility(); - + // sync the integrator logs and the most recent entry IntegratorFileLog lastFile = updateLogs(loggedInInfo, facility); - // start at the beginning of time (aka jan 1, 1970) so by default everything is pushed + // start at the beginning of time (aka jan 1, 1970) so by default everything is + // pushed Date lastDataUpdated = new Date(0); // set the date threshold. - if (lastFile != null && lastFile.getCurrentDate() != null){ + if (lastFile != null && lastFile.getCurrentDate() != null) { lastDataUpdated = lastFile.getCurrentDate(); } - + logger.info("Last data snapshot date " + lastDataUpdated); - // Sync Oscar and Integrator Consent tables via web services. This is required before pushing any patient data. - // This is important because a patient file is NOT pushed if the consent is revoked - and therefore will not be updated with Integrator. - if( CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE ) { + // Sync Oscar and Integrator Consent tables via web services. This is required + // before pushing any patient data. + // This is important because a patient file is NOT pushed if the consent is + // revoked - and therefore will not be updated with Integrator. + if (CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE) { this.pushPatientConsentTable(loggedInInfo, lastDataUpdated, facility); } - // this needs to be set now, before we do any sends, this will cause anything updated after now to be resent twice but it's better than items being missed that were updated after this started. + // this needs to be set now, before we do any sends, this will cause anything + // updated after now to be resent twice but it's better than items being missed + // that were updated after this started. Date currentUpdateDate = new Date(); - //setup this list once for this facility + // setup this list once for this facility List programs = programDao.getProgramsByFacilityId(facility.getId()); - + String documentDir = getOutputDirectory(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss"); String dateOnFile = formatter.format(currentUpdateDate); String filename = "IntegratorPush_" + facility.getId() + "_" + dateOnFile; - - // set to collect a manifest of documents (and maybe labs) during the push process. - // This manifest will be used to create a zipped package after the the initial serialization process is completed. + + // set to collect a manifest of documents (and maybe labs) during the push + // process. + // This manifest will be used to create a zipped package after the the initial + // serialization process is completed. Set documentPaths = new HashSet(); - + logger.info("This data snapshot will be timestamped with " + currentUpdateDate); - + try { - //create the first file - out = new ObjectOutputStream(new FileOutputStream(new File(documentDir + File.separator + filename + ".1.ser"))); - + // create the first file + out = new ObjectOutputStream( + new FileOutputStream(new File(documentDir + File.separator + filename + ".1.ser"))); + File documentMetaFile = new File(documentDir + File.separator + filename + "_documentMeta.txt"); documentMetaWriter = new PrintWriter(new FileWriter(documentMetaFile)); - + IntegratorFileHeader header = new IntegratorFileHeader(); header.setDate(currentUpdateDate); header.setLastDate(lastDataUpdated); - header.setDependsOn(lastFile!=null?lastFile.getChecksum():null); - header.setCachedFacilityId(cachedFacility!=null?cachedFacility.getIntegratorFacilityId():null); - header.setCachedFacilityName(cachedFacility!=null?cachedFacility.getName():null); + header.setDependsOn(lastFile != null ? lastFile.getChecksum() : null); + header.setCachedFacilityId(cachedFacility != null ? cachedFacility.getIntegratorFacilityId() : null); + header.setCachedFacilityName(cachedFacility != null ? cachedFacility.getName() : null); header.setUsername(facility.getIntegratorUser()); out.writeUnshared(header); - + pushMessages(out, facility, loggedInInfo); - pushFacility(out,facility, lastDataUpdated); - pushProviders(out,lastDataUpdated, facility); - pushPrograms(out,lastDataUpdated, facility); - + pushFacility(out, facility, lastDataUpdated); + pushProviders(out, lastDataUpdated, facility); + pushPrograms(out, lastDataUpdated, facility); + IOUtils.closeQuietly(out); - out = new ObjectOutputStream(new FileOutputStream(new File(documentDir + File.separator + filename + ".2.ser"))); - - int currentFileNumber = pushAllDemographics(documentDir + File.separator + filename, loggedInInfo, facility, lastDataUpdated, cachedFacility, programs, documentPaths); + out = new ObjectOutputStream( + new FileOutputStream(new File(documentDir + File.separator + filename + ".2.ser"))); + + int currentFileNumber = pushAllDemographics(documentDir + File.separator + filename, loggedInInfo, facility, + lastDataUpdated, cachedFacility, programs, documentPaths); IOUtils.closeQuietly(out); - out = new ObjectOutputStream(new FileOutputStream(new File(documentDir + File.separator + filename + "."+(++currentFileNumber)+".ser"))); - - IntegratorFileFooter footer =new IntegratorFileFooter(); + out = new ObjectOutputStream(new FileOutputStream( + new File(documentDir + File.separator + filename + "." + (++currentFileNumber) + ".ser"))); + + IntegratorFileFooter footer = new IntegratorFileFooter(); out.writeUnshared(footer); - - }catch(IOException e) { - logger.error("Error writing to integrator file. Cannot use the file needed to store the data. Aborting.", e); + + } catch (IOException e) { + logger.error("Error writing to integrator file. Cannot use the file needed to store the data. Aborting.", + e); return; } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(documentMetaWriter); } - - //creates a zip (.zipTemp) and returns the checksum for the log + + // creates a zip (.zipTemp) and returns the checksum for the log String checksum = null; try { - checksum = completeFile(documentDir,filename); - } catch(Exception e) { + checksum = completeFile(documentDir, filename); + } catch (Exception e) { throw new IOException(e); } - - //TODO is there any need to log or transmit a checksum for the documents? Technically the manifest should confirm them all? + + // TODO is there any need to log or transmit a checksum for the documents? + // Technically the manifest should confirm them all? try { completeDocumentFile(documentDir, filename, documentPaths); - } catch(Exception e) { + } catch (Exception e) { throw new IOException(e); } - - //save this log - integratorFileLogManager.saveNewFileData(filename + ".zip",checksum,lastDataUpdated,currentUpdateDate); - - //publish the file(s) + + // save this log + integratorFileLogManager.saveNewFileData(filename + ".zip", checksum, lastDataUpdated, currentUpdateDate); + + // publish the file(s) try { - Files.move(Paths.get(documentDir + File.separator + filename + ".zipTemp"), Paths.get(documentDir + File.separator + filename + ".zip"), StandardCopyOption.REPLACE_EXISTING); - - Path documentzip = Paths.get(documentDir + File.separator + filename + COMPRESSED_DOCUMENTS_APPENDAGE + ".zipTemp"); - if(Files.exists(documentzip)) { - Files.move(documentzip, Paths.get(documentDir + File.separator + filename + COMPRESSED_DOCUMENTS_APPENDAGE + ".zip"), StandardCopyOption.REPLACE_EXISTING); + Files.move(Paths.get(documentDir + File.separator + filename + ".zipTemp"), + Paths.get(documentDir + File.separator + filename + ".zip"), StandardCopyOption.REPLACE_EXISTING); + + Path documentzip = Paths + .get(documentDir + File.separator + filename + COMPRESSED_DOCUMENTS_APPENDAGE + ".zipTemp"); + if (Files.exists(documentzip)) { + Files.move(documentzip, + Paths.get(documentDir + File.separator + filename + COMPRESSED_DOCUMENTS_APPENDAGE + ".zip"), + StandardCopyOption.REPLACE_EXISTING); } - }catch(Exception e) { - logger.error("Error renaming file",e); + } catch (Exception e) { + logger.error("Error renaming file", e); } - - + logger.info("Finished pushing data for facility : " + facility.getId() + " : " + facility.getName()); - + // fetching new provider messages from the integrator fetchMessages(loggedInInfo, facility); } - + /** * Push all the inter-provider messages to the integrator. - * Converts Oscar messages into ProviderCommunication objects for use in the Integrator - * @throws IOException + * Converts Oscar messages into ProviderCommunication objects for use in the + * Integrator + * + * @throws IOException */ private void pushMessages(ObjectOutputStream out, Facility facility, LoggedInInfo loggedInInfo) throws IOException { - List cachedFacilities = CaisiIntegratorManager.getRemoteFacilities(loggedInInfo, facility); + List cachedFacilities = CaisiIntegratorManager + .getRemoteFacilities(loggedInInfo, facility); LoggedInInfo systemLoggedInInfo = new LoggedInInfo(); systemLoggedInInfo.setCurrentFacility(facility); systemLoggedInInfo.setLoggedInProvider(loggedInInfo.getLoggedInProvider()); Security security = new Security(); systemLoggedInInfo.setLoggedInSecurity(security); - - List providerCommunicationList = messengerIntegratorManager.getIntegratedMessages(systemLoggedInInfo, cachedFacilities, MessageList.STATUS_NEW); - if(providerCommunicationList.size() > 0) - { + + List providerCommunicationList = messengerIntegratorManager + .getIntegratedMessages(systemLoggedInInfo, cachedFacilities, MessageList.STATUS_NEW); + if (providerCommunicationList.size() > 0) { out.writeUnshared(providerCommunicationList); } } - + /** - * Get all the messages for all the active messaging providers in this facility. - * @throws UnsupportedEncodingException + * Get all the messages for all the active messaging providers in this facility. + * + * @throws UnsupportedEncodingException */ private void fetchMessages(LoggedInInfo loggedInInfo, Facility facility) throws UnsupportedEncodingException { LoggedInInfo systemLoggedInInfo = new LoggedInInfo(); @@ -513,12 +549,13 @@ private void fetchMessages(LoggedInInfo loggedInInfo, Facility facility) throws Security security = new Security(); systemLoggedInInfo.setLoggedInSecurity(security); systemLoggedInInfo.setCurrentFacility(facility); - + List providerCommunicationList = Collections.emptyList(); - List receivedMessages = Collections.emptyList(); + List receivedMessages = Collections.emptyList(); try { providerCommunicationList = CaisiIntegratorManager.getProviderCommunication(systemLoggedInInfo); - receivedMessages = messengerIntegratorManager.receiveIntegratedMessages(systemLoggedInInfo, providerCommunicationList); + receivedMessages = messengerIntegratorManager.receiveIntegratedMessages(systemLoggedInInfo, + providerCommunicationList); } catch (MalformedURLException e) { MiscUtils.getLogger().error("Error while retreiving messages for Oscar Messaging members", e); } @@ -527,33 +564,34 @@ private void fetchMessages(LoggedInInfo loggedInInfo, Facility facility) throws CaisiIntegratorManager.updateProviderCommunicationStatus(systemLoggedInInfo, receivedMessages); } catch (MalformedURLException e) { MiscUtils.getLogger().error("Error while updating message status " + receivedMessages, e); - } + } } - private void pushFacility(ObjectOutputStream out, Facility facility, Date lastDataUpdated) throws MalformedURLException, IOException { + private void pushFacility(ObjectOutputStream out, Facility facility, Date lastDataUpdated) + throws MalformedURLException, IOException { if (facility.getLastUpdated().after(lastDataUpdated)) { logger.debug("pushing facility record"); CachedFacility cachedFacility = new CachedFacility(); BeanUtils.copyProperties(facility, cachedFacility); - out.writeUnshared(cachedFacility); } else { logger.debug("skipping facility record, not updated since last push"); } } - private void pushPrograms(ObjectOutputStream out, Date lastDataUpdated, Facility facility) throws MalformedURLException, IOException { - List programIds = programDao.getRecordsAddedAndUpdatedSinceTime(facility.getId(),lastDataUpdated); - + private void pushPrograms(ObjectOutputStream out, Date lastDataUpdated, Facility facility) + throws MalformedURLException, IOException { + List programIds = programDao.getRecordsAddedAndUpdatedSinceTime(facility.getId(), lastDataUpdated); + ArrayList cachedPrograms = new ArrayList(); - + for (Integer programId : programIds) { Program program = programDao.getProgram(programId); - + logger.debug("pushing program : " + program.getId() + ':' + program.getName()); - + CachedProgram cachedProgram = new CachedProgram(); BeanUtils.copyProperties(program, cachedProgram); @@ -565,10 +603,11 @@ private void pushPrograms(ObjectOutputStream out, Date lastDataUpdated, Facility try { cachedProgram.setGender(Gender.valueOf(program.getManOrWoman().toUpperCase())); } catch (Exception e) { - + } - if (program.isTransgender()) cachedProgram.setGender(Gender.T); + if (program.isTransgender()) + cachedProgram.setGender(Gender.T); cachedProgram.setMaxAge(program.getAgeMax()); cachedProgram.setMinAge(program.getAgeMin()); @@ -577,34 +616,34 @@ private void pushPrograms(ObjectOutputStream out, Date lastDataUpdated, Facility cachedPrograms.add(cachedProgram); } - if(cachedPrograms.size()>0) { + if (cachedPrograms.size() > 0) { out.writeUnshared(cachedPrograms); } - + List allProgramIds = programDao.getRecordsByFacilityId(facility.getId()); - if(allProgramIds.size()>0) { - out.writeUnshared(new ProgramDeleteIdWrapper(allProgramIds) ); + if (allProgramIds.size() > 0) { + out.writeUnshared(new ProgramDeleteIdWrapper(allProgramIds)); } } - private void pushProviders(ObjectOutputStream out, Date lastDataUpdated, Facility facility) throws MalformedURLException, IOException { + private void pushProviders(ObjectOutputStream out, Date lastDataUpdated, Facility facility) + throws MalformedURLException, IOException { List providerIds = providerDao.getRecordsAddedAndUpdatedSinceTime(lastDataUpdated); providerIds.addAll(secUserRoleDao.getRecordsAddedAndUpdatedSinceTime(lastDataUpdated)); - + Set uniqueProviderIds = new HashSet(providerIds); - - + ArrayList providerTransfers = new ArrayList(); int i = 0; - + for (String providerId : uniqueProviderIds) { logger.debug("Adding provider " + providerId + " for " + facility.getName()); // copy provider basic data over Provider provider = providerDao.getProvider(providerId); - if (provider == null) continue; + if (provider == null) + continue; - ProviderTransfer providerTransfer = new ProviderTransfer(); providerTransfer.setRoles(new ArrayList()); CachedProvider cachedProvider = new CachedProvider(); @@ -621,253 +660,280 @@ private void pushProviders(ObjectOutputStream out, Date lastDataUpdated, Facilit List roles = secUserRoleDao.getUserRoles(providerId); for (SecUserRole role : roles) { Role integratorRole = IntegratorRoleUtils.getIntegratorRole2(role.getRoleName()); - if (integratorRole != null) providerTransfer.getRoles().add(integratorRole); + if (integratorRole != null) + providerTransfer.getRoles().add(integratorRole); } providerTransfers.add(providerTransfer); - - if((++i % 50) == 0) { + + if ((++i % 50) == 0) { out.writeUnshared(providerTransfers); providerTransfers.clear(); } - + } - - if(providerTransfers.size()>0) { + + if (providerTransfers.size() > 0) { out.writeUnshared(providerTransfers); } } - + private boolean isFullPush(Facility facility) { - UserProperty fullPushProp = userPropertyDao.getProp(UserProperty.INTEGRATOR_FULL_PUSH+facility.getId()); - + UserProperty fullPushProp = userPropertyDao.getProp(UserProperty.INTEGRATOR_FULL_PUSH + facility.getId()); + if (OscarProperties.getInstance().isPropertyActive("INTEGRATOR_FORCE_FULL")) { return true; } - + if (fullPushProp != null && fullPushProp.getValue().equals("1")) { - userPropertyDao.saveProp(UserProperty.INTEGRATOR_FULL_PUSH+facility.getId(), "0"); + userPropertyDao.saveProp(UserProperty.INTEGRATOR_FULL_PUSH + facility.getId(), "0"); return true; } - + return false; } - private boolean isPushDisabled() { UserProperty prop = userPropertyDao.getProp(IntegratorPushManager.DISABLE_INTEGRATOR_PUSH_PROP); - - if(prop != null && "true".equals(prop.getValue())) { + + if (prop != null && "true".equals(prop.getValue())) { return true; } return false; } - - private boolean checkPatientConsent( int demographicNo ) { - return patientConsentManager.hasPatientConsented( demographicNo, this.consentType ); + + private boolean checkPatientConsent(int demographicNo) { + return patientConsentManager.hasPatientConsented(demographicNo, this.consentType); } private List getDemographicIdsToPush(Facility facility, Date lastDataUpdated, List programs) { - + List fullFacilitydemographicIds = null; - if ( isFullPush(facility) || lastDataUpdated.getTime() == 0 ) { + if (isFullPush(facility) || lastDataUpdated.getTime() == 0) { logger.info("Integrator pushing ALL demographics"); - - // check if patient consent module is active and then sort out all patients that + + // check if patient consent module is active and then sort out all patients that // have given consent - if( CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE ) { + if (CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE) { logger.debug("Integrator patient consent is active. Checking demographic list."); return patientConsentManager.getAllDemographicsWithOptinConsentByType(null, this.consentType); } else { - return DemographicDao.getDemographicIdsAdmittedIntoFacility(facility.getId()); + return demographicDao.getDemographicIdsAdmittedIntoFacility(facility.getId()); } - + } else { - - fullFacilitydemographicIds = DemographicDao.getDemographicIdsAdmittedIntoFacility(facility.getId()); - + + fullFacilitydemographicIds = demographicDao.getDemographicIdsAdmittedIntoFacility(facility.getId()); + logger.info("Integrator pushing only changed demographics"); - - //Make a list of all ids that have a change in one of the subtypes...it's a bunch of queries - //but it's still a much much faster than looping through all demographics in a Facility, and - //running the push logic on all it's subtypes. - + + // Make a list of all ids that have a change in one of the subtypes...it's a + // bunch of queries + // but it's still a much much faster than looping through all demographics in a + // Facility, and + // running the push logic on all it's subtypes. + Set uniqueDemographicIdsWithSomethingNew = new HashSet(); uniqueDemographicIdsWithSomethingNew.addAll(demographicDao.getDemographicIdsAddedSince(lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(integratorConsentDao.findDemographicIdsByFacilitySince(facility.getId(),lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(caseManagementIssueDAO.getIssuesByProgramsSince(lastDataUpdated,programs)); - uniqueDemographicIdsWithSomethingNew.addAll(caseManagementNoteDAO.getNotesByFacilitySince(lastDataUpdated,programs)); - uniqueDemographicIdsWithSomethingNew.addAll(admissionDao.getAdmissionsByFacilitySince(facility.getId(), lastDataUpdated)); - - //i can't limit these ones by facility, so this may return more patients than will ever get sent. - uniqueDemographicIdsWithSomethingNew.addAll(this.preventionDao.findDemographicIdsAfterDatetime(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew + .addAll(integratorConsentDao.findDemographicIdsByFacilitySince(facility.getId(), lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew + .addAll(caseManagementIssueDAO.getIssuesByProgramsSince(lastDataUpdated, programs)); + uniqueDemographicIdsWithSomethingNew + .addAll(caseManagementNoteDAO.getNotesByFacilitySince(lastDataUpdated, programs)); + uniqueDemographicIdsWithSomethingNew + .addAll(admissionDao.getAdmissionsByFacilitySince(facility.getId(), lastDataUpdated)); + + // i can't limit these ones by facility, so this may return more patients than + // will ever get sent. + uniqueDemographicIdsWithSomethingNew + .addAll(this.preventionDao.findDemographicIdsAfterDatetime(lastDataUpdated)); uniqueDemographicIdsWithSomethingNew.addAll(drugDao.findDemographicIdsUpdatedAfterDate(lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(this.appointmentDao.getAllDemographicNoSince(lastDataUpdated, programs)); - uniqueDemographicIdsWithSomethingNew.addAll(measurementDao.findDemographicIdsUpdatedAfterDate(lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(this.dxresearchDao.getByDemographicNoSince( lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(this.billingONItemDao.getDemographicNoSince( lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(this.eFormDataDao.findemographicIdSinceLastDate( lastDataUpdated)); - uniqueDemographicIdsWithSomethingNew.addAll(this.allergyDao.findDemographicIdsUpdatedAfterDate(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew + .addAll(this.appointmentDao.getAllDemographicNoSince(lastDataUpdated, programs)); + uniqueDemographicIdsWithSomethingNew + .addAll(measurementDao.findDemographicIdsUpdatedAfterDate(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew.addAll(this.dxresearchDao.getByDemographicNoSince(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew.addAll(this.billingONItemDao.getDemographicNoSince(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew + .addAll(this.eFormDataDao.findemographicIdSinceLastDate(lastDataUpdated)); + uniqueDemographicIdsWithSomethingNew + .addAll(this.allergyDao.findDemographicIdsUpdatedAfterDate(lastDataUpdated)); uniqueDemographicIdsWithSomethingNew.addAll(EDocUtil.listDemographicIdsSince(lastDataUpdated)); - + try { uniqueDemographicIdsWithSomethingNew.addAll(FrmLabReq07Record.getDemogaphicIdsSince(lastDataUpdated)); - }catch(SQLException e) { - logger.warn("problem with getting latest labreq07s",e); + } catch (SQLException e) { + logger.warn("problem with getting latest labreq07s", e); } - + uniqueDemographicIdsWithSomethingNew.addAll(patientLabRoutingDao.findDemographicIdsSince(lastDataUpdated)); - - - //handle deletes - backup. - //so if a issue or something else that uses hard deletes gets deleted, the audit should have picked it up. - uniqueDemographicIdsWithSomethingNew.addAll(DemographicDao.getDemographicIdsAlteredSinceTime(lastDataUpdated)); + + // handle deletes - backup. + // so if a issue or something else that uses hard deletes gets deleted, the + // audit should have picked it up. + uniqueDemographicIdsWithSomethingNew + .addAll(demographicDao.getDemographicIdsAlteredSinceTime(lastDataUpdated)); Iterator demoIterator = uniqueDemographicIdsWithSomethingNew.iterator(); - - while(demoIterator.hasNext()){ //Verify that the demographic is in the Facility - Integer demo = demoIterator.next(); - if(! fullFacilitydemographicIds.contains(demo) ){ - demoIterator.remove(); - } - - else if( CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE && ! checkPatientConsent( demo ) ) { - logger.debug("Integrator patient consent is active. Checking demographic list of changed demographics"); - demoIterator.remove(); - } - } - - - return(new ArrayList(uniqueDemographicIdsWithSomethingNew)); - + + while (demoIterator.hasNext()) { // Verify that the demographic is in the Facility + Integer demo = demoIterator.next(); + if (!fullFacilitydemographicIds.contains(demo)) { + demoIterator.remove(); + } + + else if (CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE && !checkPatientConsent(demo)) { + logger.debug( + "Integrator patient consent is active. Checking demographic list of changed demographics"); + demoIterator.remove(); + } + } + + return (new ArrayList(uniqueDemographicIdsWithSomethingNew)); + } } - - protected int pushAllDemographics(String parentFilename, LoggedInInfo loggedInInfo, Facility facility,Date lastDataUpdated, - org.oscarehr.caisi_integrator.ws.CachedFacility cachedFacility, List programs, Set documentPaths) + protected int pushAllDemographics(String parentFilename, LoggedInInfo loggedInInfo, Facility facility, + Date lastDataUpdated, + org.oscarehr.caisi_integrator.ws.CachedFacility cachedFacility, List programs, + Set documentPaths) throws IOException { - - List demographicIds = getDemographicIdsToPush(facility,lastDataUpdated, programs); + + List demographicIds = getDemographicIdsToPush(facility, lastDataUpdated, programs); List programsInFacility = programDao.getProgramsByFacilityId(facility.getId()); List providerIdsInFacility = providerDao.getProviderIds(facility.getId()); - - + long startTime = System.currentTimeMillis(); int demographicPushCount = 0; - + String documentDir = getOutputDirectory(); int currentFileNumber = 2; - + boolean rid = integratorControlDao.readRemoveDemographicIdentity(facility.getId()); - - //we could parallelize this. basically we want X records per file. So we just assign each unit of work to be - //a set of demographicIds which will end up being a single file. so we need to know the file number and the ids for it + + // we could parallelize this. basically we want X records per file. So we just + // assign each unit of work to be + // a set of demographicIds which will end up being a single file. so we need to + // know the file number and the ids for it for (Integer demographicId : demographicIds) { - + demographicPushCount++; - BenchmarkTimer benchTimer = new BenchmarkTimer("pushing demo facilityId:" + facility.getId() + ", demographicId:" + demographicId + " " + demographicPushCount + " of " + demographicIds.size()); - String filename = "IntegratorPush_" + facility.getId() + "_" + demographicId + ".ser"; + BenchmarkTimer benchTimer = new BenchmarkTimer( + "pushing demo facilityId:" + facility.getId() + ", demographicId:" + demographicId + " " + + demographicPushCount + " of " + demographicIds.size()); + String filename = "IntegratorPush_" + facility.getId() + "_" + demographicId + ".ser"; ObjectOutputStream demoOut = null; - + /* - * This is a little hack that checks if a patient consent is new and/or has been edited - * If true, the date is rolled back so that ALL of this patient file is pushed to the Integrator. + * This is a little hack that checks if a patient consent is new and/or has been + * edited + * If true, the date is rolled back so that ALL of this patient file is pushed + * to the Integrator. * Otherwise the date threshold will remain at the last push date. * This only works in conjunction with the global patient consent module. */ Date dateThreshold = lastDataUpdated; - - if(CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE) { + + if (CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE) { dateThreshold = adjustDateThreshold(loggedInInfo, lastDataUpdated, demographicId); benchTimer.tag("adjustDateThreshhold"); } - + try { - - if((demographicPushCount % 500) == 0) { + + if ((demographicPushCount % 500) == 0) { IOUtils.closeQuietly(out); - out = new ObjectOutputStream(new FileOutputStream(new File(parentFilename + "." + (++currentFileNumber) + ".ser"))); - logger.info("starting a new file ("+currentFileNumber+")"); + out = new ObjectOutputStream( + new FileOutputStream(new File(parentFilename + "." + (++currentFileNumber) + ".ser"))); + logger.info("starting a new file (" + currentFileNumber + ")"); } - - demoOut = new ObjectOutputStream(new FileOutputStream(new File(documentDir + File.separator + filename))); - pushDemographic(demoOut,dateThreshold, facility, demographicId,rid); + demoOut = new ObjectOutputStream( + new FileOutputStream(new File(documentDir + File.separator + filename))); + + pushDemographic(demoOut, dateThreshold, facility, demographicId, rid); benchTimer.tag("pushDemographic"); - - // Use alternate method for patient consents if the Patient Consent Module is off. - if( ! CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE ) { - pushDemographicConsent(demoOut,dateThreshold, facility, demographicId); + + // Use alternate method for patient consents if the Patient Consent Module is + // off. + if (!CaisiIntegratorUpdateTask.ISACTIVE_PATIENT_CONSENT_MODULE) { + pushDemographicConsent(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushDemographicConsent"); } - - pushDemographicIssues(demoOut,dateThreshold, facility, programsInFacility, demographicId, cachedFacility); + + pushDemographicIssues(demoOut, dateThreshold, facility, programsInFacility, demographicId, + cachedFacility); benchTimer.tag("pushDemographicIssues"); - - pushDemographicPreventions(demoOut,dateThreshold, facility, providerIdsInFacility, demographicId); + + pushDemographicPreventions(demoOut, dateThreshold, facility, providerIdsInFacility, demographicId); benchTimer.tag("pushDemographicPreventions"); - - pushDemographicNotes(demoOut,dateThreshold, facility, demographicId, programsInFacility); + + pushDemographicNotes(demoOut, dateThreshold, facility, demographicId, programsInFacility); benchTimer.tag("pushDemographicNotes"); - - pushDemographicDrugs(demoOut,dateThreshold, facility, providerIdsInFacility, demographicId); + + pushDemographicDrugs(demoOut, dateThreshold, facility, providerIdsInFacility, demographicId); benchTimer.tag("pushDemographicDrugs"); - - pushAdmissions(demoOut,dateThreshold, facility, programsInFacility, demographicId); + + pushAdmissions(demoOut, dateThreshold, facility, programsInFacility, demographicId); benchTimer.tag("pushAdmissions"); - - pushAppointments(demoOut,dateThreshold, facility, demographicId); + + pushAppointments(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushAppointments"); - - pushMeasurements(demoOut,dateThreshold, facility, demographicId); + + pushMeasurements(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushMeasurements"); - - pushDxresearchs(demoOut,dateThreshold, facility, demographicId); + + pushDxresearchs(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushDxresearchs"); - - - if( OscarProperties.getInstance().isOntarioBillingRegion() ) { - pushBillingItems(demoOut,dateThreshold, facility, demographicId); + + if (OscarProperties.getInstance().isOntarioBillingRegion()) { + pushBillingItems(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushBillingItems"); } - pushEforms(demoOut,dateThreshold, facility, demographicId); + pushEforms(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushEforms"); - pushAllergies(demoOut,dateThreshold, facility, demographicId); + pushAllergies(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushAllergies"); - - pushDocuments(demoOut,loggedInInfo, dateThreshold, facility, demographicId, documentPaths); + + pushDocuments(demoOut, loggedInInfo, dateThreshold, facility, demographicId, documentPaths); benchTimer.tag("pushDocuments"); - - pushForms(demoOut,dateThreshold, facility, demographicId); + + pushForms(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushForms"); - - pushLabResults(demoOut,dateThreshold, facility, demographicId); + + pushLabResults(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushLabResults"); - - pushHL7LabResults(demoOut,dateThreshold, facility, demographicId); + + pushHL7LabResults(demoOut, dateThreshold, facility, demographicId); benchTimer.tag("pushHL7LabResults"); - - + logger.debug(benchTimer.report()); DbConnectionFilter.releaseAllThreadDbResources(); - + demoOut.flush(); - - } catch( IOException e) { - logger.error("Error creating patient file. Cannot create the file to send to integrator for this patient ("+demographicId+"), skipping.", e); + + } catch (IOException e) { + logger.error( + "Error creating patient file. Cannot create the file to send to integrator for this patient (" + + demographicId + "), skipping.", + e); cleanFile(filename); continue; } catch (IllegalArgumentException iae) { - // continue processing demographics if date values in current demographic are bad - // all other errors thrown by the above methods should indicate a failure in the service + // continue processing demographics if date values in current demographic are + // bad + // all other errors thrown by the above methods should indicate a failure in the + // service // connection at large -- continuing to process not possible // need some way of notification here. - logger.error("Error updating demographic "+demographicId+", continuing with Demographic batch", iae); + logger.error("Error updating demographic " + demographicId + ", continuing with Demographic batch", + iae); cleanFile(filename); continue; } catch (Exception e) { @@ -877,72 +943,73 @@ protected int pushAllDemographics(String parentFilename, LoggedInInfo loggedInIn } finally { IOUtils.closeQuietly(demoOut); } - - - //Now we add the completed demographic to the main file, and delete the demographic one. + + // Now we add the completed demographic to the main file, and delete the + // demographic one. ObjectInputStream ois = null; FileInputStream fis = null; - + try { File f = new File(documentDir + File.separator + filename); fis = new FileInputStream(f); ois = new ObjectInputStream(fis); - + Object obj = null; - - while(true) { + + while (true) { try { obj = ois.readUnshared(); - - }catch(EOFException eofEx) { + + } catch (EOFException eofEx) { break; } out.writeUnshared(obj); } - - + obj = null; fis.close(); ois.close(); - + fis = null; ois = null; - - }catch(ClassNotFoundException e) { - throw new RuntimeException("This should never happen",e); - }catch(IOException e) { + + } catch (ClassNotFoundException e) { + throw new RuntimeException("This should never happen", e); + } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(fis); IOUtils.closeQuietly(ois); } - //the exceptions above could corrupt the file, so we have to abandon by rethrowing an exception up instead of a continue - - //delete the file + // the exceptions above could corrupt the file, so we have to abandon by + // rethrowing an exception up instead of a continue + + // delete the file boolean deleted = new File(documentDir + File.separator + filename).delete(); - if(!deleted) { + if (!deleted) { logger.warn("unable to delete temp demographic file"); } } - + logger.debug("Total pushAllDemographics :" + (System.currentTimeMillis() - startTime)); return currentFileNumber; } - + private void cleanFile(String filename) { new File(filename).delete(); } - //TODO: DemographicExt are not sent - private void pushDemographic(ObjectOutputStream demoOut, Date lastDataUpdated, Facility facility, Integer demographicId, boolean rid) throws IOException { + // TODO: DemographicExt are not sent + private void pushDemographic(ObjectOutputStream demoOut, Date lastDataUpdated, Facility facility, + Integer demographicId, boolean rid) throws IOException { DemographicTransfer demographicTransfer = new DemographicTransfer(); // set demographic info Demographic demographic = demographicDao.getDemographicById(demographicId); - - //we can remove this once we know our demographic id list is good - if(demographic.getLastUpdateDate().before(lastDataUpdated)) return; - + + // we can remove this once we know our demographic id list is good + if (demographic.getLastUpdateDate().before(lastDataUpdated)) + return; String ignoreProperties[] = { "lastUpdateDate" }; BeanUtils.copyProperties(demographic, demographicTransfer, ignoreProperties); @@ -965,7 +1032,8 @@ private void pushDemographic(ObjectOutputStream demoOut, Date lastDataUpdated, F try { demographicTransfer.setGender(Gender.valueOf(demographic.getSex().toUpperCase())); } catch (Exception e) { - logger.warn("Error mapping gender on demographic " + demographic.getDemographicNo() + "(" + demographic.getSex() + ")"); + logger.warn("Error mapping gender on demographic " + demographic.getDemographicNo() + "(" + + demographic.getSex() + ")"); } // set image @@ -977,30 +1045,36 @@ private void pushDemographic(ObjectOutputStream demoOut, Date lastDataUpdated, F // set flag to remove demographic identity demographicTransfer.setRemoveId(rid); - + demoOut.writeUnshared(demographicTransfer); conformanceTestLog(facility, "Demographic", String.valueOf(demographicId)); } - + /** * This is an override to the pushDemographicConsent method. - * - * Demographic information will not be pushed if a patient has revoked or modified their - * consent through the Patient Consent Module for participation in the Integrator program, - * therefore the attached consents from the pushDemographicConsent table will not get pushed. * - * This method ensures that the all current consents from the Patient Consent Module () + * Demographic information will not be pushed if a patient has revoked or + * modified their + * consent through the Patient Consent Module for participation in the + * Integrator program, + * therefore the attached consents from the pushDemographicConsent table will + * not get pushed. + * + * This method ensures that the all current consents from the Patient Consent + * Module () */ - private void pushPatientConsentTable(LoggedInInfo loggedinInfo, Date lastDataUpdated, Facility facility ) { - List consents = patientConsentManager.getConsentsByTypeAndEditDate( loggedinInfo, this.consentType, lastDataUpdated ); - logger.debug("Updating last edited consent list after " + lastDataUpdated); + private void pushPatientConsentTable(LoggedInInfo loggedinInfo, Date lastDataUpdated, Facility facility) { + List consents = patientConsentManager.getConsentsByTypeAndEditDate(loggedinInfo, this.consentType, + lastDataUpdated); + logger.debug("Updating last edited consent list after " + lastDataUpdated); - if(consents != null) { - for( Consent consent : consents ) { + if (consents != null) { + for (Consent consent : consents) { try { CaisiIntegratorManager.pushConsent(loggedinInfo, facility, consent); - logger.debug("pushDemographicConsent:" + consent.getId() + "," + facility.getId() + "," + consent.getDemographicNo()); + logger.debug("pushDemographicConsent:" + consent.getId() + "," + facility.getId() + "," + + consent.getDemographicNo()); } catch (MalformedURLException e) { logger.error("Error while pushing consent via webservices. Consent ID: " + consent.getId(), e); continue; @@ -1008,65 +1082,75 @@ private void pushPatientConsentTable(LoggedInInfo loggedinInfo, Date lastDataUpd } } } - + /** - * This method will determine if the threshold should be rolled back to the beginning of time - * or remain at the current date for each demographic. + * This method will determine if the threshold should be rolled back to the + * beginning of time + * or remain at the current date for each demographic. + * * @param lastUpdatedData * @param facility * @param demographicId * @return */ private Date adjustDateThreshold(LoggedInInfo loggedinInfo, Date lastUpdatedData, Integer demographicId) { - if(isConsentNewOrEdited(loggedinInfo, lastUpdatedData, demographicId)) - { + if (isConsentNewOrEdited(loggedinInfo, lastUpdatedData, demographicId)) { return new Date(0); - } - else - { - return lastUpdatedData; + } else { + return lastUpdatedData; } } - + /** - * Returns true if the consent was edited after the given lastUpdatedData date AND if consent is granted. - * This only works on the global patient consent table. + * Returns true if the consent was edited after the given lastUpdatedData date + * AND if consent is granted. + * This only works on the global patient consent table. + * * @param lastUpdatedData * @param facility * @param demographicId */ private boolean isConsentNewOrEdited(LoggedInInfo loggedinInfo, Date lastUpdatedData, Integer demographicId) { - Consent consent = patientConsentManager.getConsentByDemographicAndConsentType(loggedinInfo, demographicId, this.consentType); + Consent consent = patientConsentManager.getConsentByDemographicAndConsentType(loggedinInfo, demographicId, + this.consentType); return lastUpdatedData.before(consent.getEditDate()) && consent.getPatientConsented(); } - private void pushDemographicConsent(ObjectOutputStream out, Date lastUpdatedData, Facility facility, Integer demographicId) throws IOException { + private void pushDemographicConsent(ObjectOutputStream out, Date lastUpdatedData, Facility facility, + Integer demographicId) throws IOException { // find the latest relevant consent that needs to be pushed. - List integratorConsentList = integratorConsentDao.findByFacilityAndDemographicSince(facility.getId(), demographicId, lastUpdatedData); - if(integratorConsentList != null) - { - for(IntegratorConsent integratorConsent : integratorConsentList) { - org.oscarehr.caisi_integrator.ws.transfer.SetConsentTransfer consentTransfer = CaisiIntegratorManager.makeSetConsentTransfer2(integratorConsent); + List integratorConsentList = integratorConsentDao + .findByFacilityAndDemographicSince(facility.getId(), demographicId, lastUpdatedData); + if (integratorConsentList != null) { + for (IntegratorConsent integratorConsent : integratorConsentList) { + org.oscarehr.caisi_integrator.ws.transfer.SetConsentTransfer consentTransfer = CaisiIntegratorManager + .makeSetConsentTransfer2(integratorConsent); out.writeUnshared(consentTransfer); } } } - private void pushDemographicIssues(ObjectOutputStream out, Date lastDataUpdated, Facility facility, List programsInFacility, Integer demographicId, org.oscarehr.caisi_integrator.ws.CachedFacility cachedFacility) throws IOException { + private void pushDemographicIssues(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + List programsInFacility, Integer demographicId, + org.oscarehr.caisi_integrator.ws.CachedFacility cachedFacility) throws IOException { logger.debug("pushing demographicIssues facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.issues.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.issues.disabled", "false"))) { return; } - List caseManagementIssues = caseManagementIssueDAO.getIssuesByDemographicSince(demographicId.toString(),lastDataUpdated); + List caseManagementIssues = caseManagementIssueDAO + .getIssuesByDemographicSince(demographicId.toString(), lastDataUpdated); StringBuilder sentIds = new StringBuilder(); - if (caseManagementIssues.size() == 0) return; - - + if (caseManagementIssues.size() == 0) + return; + for (CaseManagementIssue caseManagementIssue : caseManagementIssues) { // don't send issue if it is not in our facility. - //logger.debug("Facility:" + facility.getName() + " - caseManagementIssue = " + caseManagementIssue.toString()); - if (caseManagementIssue.getProgram_id() == null || !isProgramIdInProgramList(programsInFacility, caseManagementIssue.getProgram_id())) continue; + // logger.debug("Facility:" + facility.getName() + " - caseManagementIssue = " + + // caseManagementIssue.toString()); + if (caseManagementIssue.getProgram_id() == null + || !isProgramIdInProgramList(programsInFacility, caseManagementIssue.getProgram_id())) + continue; long issueId = caseManagementIssue.getIssue_id(); Issue issue = issueDao.getIssue(issueId); @@ -1074,29 +1158,23 @@ private void pushDemographicIssues(ObjectOutputStream out, Date lastDataUpdated, FacilityIdDemographicIssueCompositePk facilityDemographicIssuePrimaryKey = new FacilityIdDemographicIssueCompositePk(); facilityDemographicIssuePrimaryKey.setCaisiDemographicId(caseManagementIssue.getDemographic_no()); - if( Issue.CUSTOM_ISSUE.equalsIgnoreCase(issue.getType()) ) { - facilityDemographicIssuePrimaryKey.setCodeType(CodeType.CUSTOM_ISSUE); - } - else if( Issue.SYSTEM.equalsIgnoreCase(issue.getType()) ){ + if (Issue.CUSTOM_ISSUE.equalsIgnoreCase(issue.getType())) { + facilityDemographicIssuePrimaryKey.setCodeType(CodeType.CUSTOM_ISSUE); + } else if (Issue.SYSTEM.equalsIgnoreCase(issue.getType())) { facilityDemographicIssuePrimaryKey.setCodeType(CodeType.SYSTEM); - } - else if( Issue.ICD_9.equalsIgnoreCase(issue.getType()) ) { + } else if (Issue.ICD_9.equalsIgnoreCase(issue.getType())) { facilityDemographicIssuePrimaryKey.setCodeType(CodeType.ICD9); - } - else if( Issue.ICD_10.equalsIgnoreCase(issue.getType()) ) { + } else if (Issue.ICD_10.equalsIgnoreCase(issue.getType())) { facilityDemographicIssuePrimaryKey.setCodeType(CodeType.ICD10); - } - else if( Issue.SNOMED.equalsIgnoreCase(issue.getType()) ) { + } else if (Issue.SNOMED.equalsIgnoreCase(issue.getType())) { facilityDemographicIssuePrimaryKey.setCodeType(CodeType.SNOMED); - } - else if( Issue.SNOMED_CORE.equalsIgnoreCase(issue.getType()) ) { + } else if (Issue.SNOMED_CORE.equalsIgnoreCase(issue.getType())) { facilityDemographicIssuePrimaryKey.setCodeType(CodeType.SNOMED_CORE); - } - else { + } else { logger.warn("UNKNOWN ISSUE TYPE. " + issue.getType() + " ID:" + issue.getId() + " SKIPPING..."); continue; } - + facilityDemographicIssuePrimaryKey.setIssueCode(issue.getCode()); cachedDemographicIssue.setFacilityDemographicIssuePk(facilityDemographicIssuePrimaryKey); @@ -1109,23 +1187,24 @@ else if( Issue.SNOMED_CORE.equalsIgnoreCase(issue.getType()) ) { out.writeUnshared(issues); sentIds.append("," + caseManagementIssue.getId()); - + facilityDemographicIssuePrimaryKey = null; cachedDemographicIssue = null; issues = null; - + } - - if(cachedFacility != null) { + + if (cachedFacility != null) { List b = new ArrayList(); - for(org.oscarehr.caisi_integrator.ws.FacilityIdDemographicIssueCompositePk c: caseManagementIssueDAO.getIssueIdsForIntegrator(cachedFacility.getIntegratorFacilityId(),demographicId)) { + for (org.oscarehr.caisi_integrator.ws.FacilityIdDemographicIssueCompositePk c : caseManagementIssueDAO + .getIssueIdsForIntegrator(cachedFacility.getIntegratorFacilityId(), demographicId)) { FacilityIdDemographicIssueCompositePk n = new FacilityIdDemographicIssueCompositePk(); n.setCaisiDemographicId(c.getCaisiDemographicId()); n.setCodeType(CodeType.valueOf(c.getCodeType().value())); n.setIntegratorFacilityId(c.getIntegratorFacilityId()); n.setIssueCode(c.getIssueCode()); - + b.add(n); } DeleteCachedDemographicIssuesWrapper wrapper = new DeleteCachedDemographicIssuesWrapper(demographicId, b); @@ -1134,22 +1213,26 @@ else if( Issue.SNOMED_CORE.equalsIgnoreCase(issue.getType()) ) { conformanceTestLog(facility, "CaseManagementIssue", sentIds.toString()); } - private void pushAdmissions(ObjectOutputStream out,Date lastDataUpdated, Facility facility, List programsInFacility, Integer demographicId) throws IOException { + private void pushAdmissions(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + List programsInFacility, Integer demographicId) throws IOException { logger.debug("pushing admissions facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.admissions.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.admissions.disabled", "false"))) { return; } - - List admissions = admissionDao.getAdmissionsByFacilitySince(demographicId, facility.getId(),lastDataUpdated); + + List admissions = admissionDao.getAdmissionsByFacilitySince(demographicId, facility.getId(), + lastDataUpdated); StringBuilder sentIds = new StringBuilder(); - if (admissions.size() == 0) return; + if (admissions.size() == 0) + return; ArrayList cachedAdmissions = new ArrayList(); - + for (Admission admission : admissions) { logger.debug("Facility:" + facility.getName() + " - admissionId = " + admission.getId()); - if (!isProgramIdInProgramList(programsInFacility, admission.getProgramId())) continue; + if (!isProgramIdInProgramList(programsInFacility, admission.getProgramId())) + continue; CachedAdmission cachedAdmission = new CachedAdmission(); @@ -1163,33 +1246,37 @@ private void pushAdmissions(ObjectOutputStream out,Date lastDataUpdated, Facilit cachedAdmission.setCaisiProgramId(admission.getProgramId()); cachedAdmission.setDischargeDate(admission.getDischargeDate()); cachedAdmission.setDischargeNotes(admission.getDischargeNotes()); - //missing status from the whole transfer? - + // missing status from the whole transfer? + cachedAdmissions.clear(); cachedAdmissions.add(cachedAdmission); out.writeUnshared(cachedAdmissions); - + sentIds.append("," + admission.getId()); } - + conformanceTestLog(facility, "Admission", sentIds.toString()); } private boolean isProgramIdInProgramList(List programList, int programId) { for (Program p : programList) { - if (p.getId().intValue() == programId) return (true); + if (p.getId().intValue() == programId) + return (true); } return (false); } - private void pushDemographicPreventions(ObjectOutputStream demoOut,Date lastDataUpdated, Facility facility, List providerIdsInFacility, Integer demographicId) throws IOException, ParserConfigurationException, ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException { - logger.debug("pushing demographicPreventions facilityId:" + facility.getId() + ", demographicId:" + demographicId); + private void pushDemographicPreventions(ObjectOutputStream demoOut, Date lastDataUpdated, Facility facility, + List providerIdsInFacility, Integer demographicId) throws IOException, ParserConfigurationException, + ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException { + logger.debug( + "pushing demographicPreventions facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.preventions.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.preventions.disabled", "false"))) { return; } - + ArrayList preventionsToSend = new ArrayList(); StringBuilder sentIds = new StringBuilder(); @@ -1197,21 +1284,21 @@ private void pushDemographicPreventions(ObjectOutputStream demoOut,Date lastData // for each prevention, copy fields to an integrator prevention // need to copy ext info // add prevention to array list to send - List localPreventions = preventionDao.findNotDeletedByDemographicIdAfterDatetime(demographicId,lastDataUpdated); - + List localPreventions = preventionDao.findNotDeletedByDemographicIdAfterDatetime(demographicId, + lastDataUpdated); + for (Prevention localPrevention : localPreventions) { - if (!providerIdsInFacility.contains(localPrevention.getCreatorProviderNo())) continue; + if (!providerIdsInFacility.contains(localPrevention.getCreatorProviderNo())) + continue; CachedDemographicPrevention cachedDemographicPrevention = new CachedDemographicPrevention(); cachedDemographicPrevention.setCaisiDemographicId(demographicId); cachedDemographicPrevention.setCaisiProviderId(localPrevention.getProviderNo()); - FacilityIdIntegerCompositePk pk = new FacilityIdIntegerCompositePk(); pk.setCaisiItemId(localPrevention.getId()); cachedDemographicPrevention.setFacilityPreventionPk(pk); - cachedDemographicPrevention.setNextDate(localPrevention.getNextDate()); cachedDemographicPrevention.setPreventionDate(localPrevention.getPreventionDate()); @@ -1232,54 +1319,58 @@ private void pushDemographicPreventions(ObjectOutputStream demoOut,Date lastData preventionsToSend.add(cachedDemographicPrevention); demoOut.writeUnshared(preventionsToSend); - + cachedDemographicPrevention = null; pk = null; doc = null; - - + sentIds.append("," + localPrevention.getId()); } conformanceTestLog(facility, "Prevention", sentIds.toString()); - //let integrator know our current and active list of preventions for this patient. The integrator will delete all not found in this list in it's db. - DeleteCachedDemographicPreventionsWrapper wrapper = new DeleteCachedDemographicPreventionsWrapper(demographicId, preventionDao.findNonDeletedIdsByDemographic(demographicId)); + // let integrator know our current and active list of preventions for this + // patient. The integrator will delete all not found in this list in it's db. + DeleteCachedDemographicPreventionsWrapper wrapper = new DeleteCachedDemographicPreventionsWrapper(demographicId, + preventionDao.findNonDeletedIdsByDemographic(demographicId)); demoOut.writeUnshared(wrapper); - + wrapper = null; } - private void pushDocuments(ObjectOutputStream out,LoggedInInfo loggedInInfo, Date lastDataUpdated, Facility facility, Integer demographicId, Set documentPaths) throws IOException, ParseException { + private void pushDocuments(ObjectOutputStream out, LoggedInInfo loggedInInfo, Date lastDataUpdated, + Facility facility, Integer demographicId, Set documentPaths) throws IOException, ParseException { - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.documents.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.documents.disabled", "false"))) { logger.debug("Pushing documents is disabled: integrator.send.documents.disabled = false"); return; } - - logger.debug("pushing demographicDocuments edited after " + lastDataUpdated + " for facilityId:" + facility.getId() + ", demographicId:" + demographicId); - // Get ALL PRIVATE documents with a LAST DATE EDITED on or after the lastDataUpdated date for a specific DEMOGRAPHIC (no need to sort them). + logger.debug("pushing demographicDocuments edited after " + lastDataUpdated + " for facilityId:" + + facility.getId() + ", demographicId:" + demographicId); + + // Get ALL PRIVATE documents with a LAST DATE EDITED on or after the + // lastDataUpdated date for a specific DEMOGRAPHIC (no need to sort them). List privateDocs = EDocUtil.listAllDemographicDocsSince(loggedInInfo, demographicId, lastDataUpdated); - + StringBuilder sentIds = new StringBuilder(); for (EDoc eDoc : privateDocs) { - + Path documentPath = sendSingleDocument(out, eDoc, demographicId); - - if(documentPath == null) { + + if (documentPath == null) { continue; } // Add this confirmed file path to the manifest. - if(documentPaths != null) { + if (documentPaths != null) { documentPaths.add(documentPath); } - - documentMetaWriter.println( eDoc.getDocId() - + "," - + demographicId - + "," + + documentMetaWriter.println(eDoc.getDocId() + + "," + + demographicId + + "," + documentPath.getFileName()); sentIds.append("," + eDoc.getDocId()); @@ -1289,23 +1380,25 @@ private void pushDocuments(ObjectOutputStream out,LoggedInInfo loggedInInfo, Dat } - private Path sendSingleDocument(ObjectOutputStream out, EDoc eDoc, Integer demographicId) throws IOException, ParseException { - + private Path sendSingleDocument(ObjectOutputStream out, EDoc eDoc, Integer demographicId) + throws IOException, ParseException { + // ensure the document is actually in the file system - Path documentPath = Paths.get( OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + File.separator + eDoc.getFileName() ); - if(! Files.exists(documentPath) ) { - logger.warn("Unable to send document - the file does not exist or can't be read!! " - + OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + '/' + eDoc.getFileName()); + Path documentPath = Paths + .get(OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + File.separator + eDoc.getFileName()); + if (!Files.exists(documentPath)) { + logger.warn("Unable to send document - the file does not exist or can't be read!! " + + OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + '/' + eDoc.getFileName()); return null; } - + // send this document CachedDemographicDocument cachedDemographicDocument = new CachedDemographicDocument(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); facilityIdIntegerCompositePk.setCaisiItemId(Integer.parseInt(eDoc.getDocId())); cachedDemographicDocument.setFacilityIntegerPk(facilityIdIntegerCompositePk); - if(eDoc.getAppointmentNo() != null) { + if (eDoc.getAppointmentNo() != null) { cachedDemographicDocument.setAppointmentNo(eDoc.getAppointmentNo()); } cachedDemographicDocument.setCaisiDemographicId(demographicId); @@ -1315,7 +1408,8 @@ private Path sendSingleDocument(ObjectOutputStream out, EDoc eDoc, Integer demog cachedDemographicDocument.setDocType(eDoc.getType()); cachedDemographicDocument.setDocXml(eDoc.getHtml()); cachedDemographicDocument.setNumberOfPages(eDoc.getNumberOfPages()); - cachedDemographicDocument.setObservationDate( org.oscarehr.util.DateUtils.parseIsoDateAsCalendar(eDoc.getObservationDate()).getTime() ); + cachedDemographicDocument.setObservationDate( + org.oscarehr.util.DateUtils.parseIsoDateAsCalendar(eDoc.getObservationDate()).getTime()); cachedDemographicDocument.setProgramId(eDoc.getProgramId()); cachedDemographicDocument.setPublic1(Integer.parseInt(eDoc.getDocPublic())); cachedDemographicDocument.setResponsible(eDoc.getResponsibleId()); @@ -1326,108 +1420,121 @@ private Path sendSingleDocument(ObjectOutputStream out, EDoc eDoc, Integer demog cachedDemographicDocument.setUpdateDateTime(eDoc.getDateTimeStampAsDate()); cachedDemographicDocument.setDescription(eDoc.getDescription()); -// byte[] contents = EDocUtil.getFile(OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + '/' + eDoc.getFileName()); -// if(contents == null) { -// logger.warn("Unable to send document - the file does not exist or can't be read!! " + OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + '/' + eDoc.getFileName()); -// return; -// } + // byte[] contents = + // EDocUtil.getFile(OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + + // '/' + eDoc.getFileName()); + // if(contents == null) { + // logger.warn("Unable to send document - the file does not exist or can't be + // read!! " + OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + '/' + + // eDoc.getFileName()); + // return; + // } out.writeUnshared(cachedDemographicDocument); return documentPath; - + } - private void pushHL7LabResults(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushHL7LabResults(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + Integer demographicId) throws IOException { logger.debug("pushing pushHL7LabResults facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.labs.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.labs.disabled", "false"))) { return; } - + CommonLabResultData comLab = new CommonLabResultData(); - - //TODO:we need to check the patient lab routing table on it's own too..the case where a lab is updated, but the link is done later + + // TODO:we need to check the patient lab routing table on it's own too..the case + // where a lab is updated, but the link is done later OscarProperties op = OscarProperties.getInstance(); - String hl7text = op.getProperty("HL7TEXT_LABS","false"); - + String hl7text = op.getProperty("HL7TEXT_LABS", "false"); + List results = new ArrayList(); - - if("yes".equals(hl7text)) + + if ("yes".equals(hl7text)) results.addAll(comLab.getHl7ResultsSince(demographicId, lastDataUpdated)); - - for(LabIdAndType id:results) { - logger.debug("id="+id.getLabId() + ",type=" + id.getLabType()); + + for (LabIdAndType id : results) { + logger.debug("id=" + id.getLabId() + ",type=" + id.getLabType()); } - + StringBuilder sentIds = new StringBuilder(); - - if (results.size() == 0) return; - + if (results.size() == 0) + return; + for (LabIdAndType labIdAndType : results) { LabResultData lab = comLab.getLab(labIdAndType); - if(lab != null) { - CachedDemographicHL7LabResult cachedDemographicLabResult = makeCachedDemographicHL7LabResult(demographicId, lab); + if (lab != null) { + CachedDemographicHL7LabResult cachedDemographicLabResult = makeCachedDemographicHL7LabResult( + demographicId, lab); out.writeUnshared(cachedDemographicLabResult); sentIds.append("," + lab.getLabPatientId() + ":" + lab.labType + ":" + lab.segmentID); } else { - logger.warn("Lab missing!!! " + labIdAndType.getLabType() + ":"+ labIdAndType.getLabId()); + logger.warn("Lab missing!!! " + labIdAndType.getLabType() + ":" + labIdAndType.getLabId()); } } - + conformanceTestLog(facility, "LabResultData", sentIds.toString()); } - - private void pushLabResults(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException, ParserConfigurationException, UnsupportedEncodingException, ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException { + + private void pushLabResults(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws IOException, ParserConfigurationException, UnsupportedEncodingException, ClassCastException, + ClassNotFoundException, InstantiationException, IllegalAccessException { logger.debug("pushing pushLabResults facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.labs.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.labs.disabled", "false"))) { return; } - + CommonLabResultData comLab = new CommonLabResultData(); - - //TODO:we need to check the patient lab routing table on it's own too..the case where a lab is updated, but the link is done later + + // TODO:we need to check the patient lab routing table on it's own too..the case + // where a lab is updated, but the link is done later OscarProperties op = OscarProperties.getInstance(); - String cml = op.getProperty("CML_LABS","false"); - String mds = op.getProperty("MDS_LABS","false"); - String pathnet = op.getProperty("PATHNET_LABS","false"); - String epsilon = op.getProperty("Epsilon_LABS","false"); - + String cml = op.getProperty("CML_LABS", "false"); + String mds = op.getProperty("MDS_LABS", "false"); + String pathnet = op.getProperty("PATHNET_LABS", "false"); + String epsilon = op.getProperty("Epsilon_LABS", "false"); + List results = new ArrayList(); - if("yes".equals(epsilon) || "yes".equals(cml)) + if ("yes".equals(epsilon) || "yes".equals(cml)) results.addAll(comLab.getCmlAndEpsilonLabResultsSince(demographicId, lastDataUpdated)); - if("yes".equals(mds)) + if ("yes".equals(mds)) results.addAll(comLab.getMdsLabResultsSince(demographicId, lastDataUpdated)); - if("yes".equals(pathnet)) + if ("yes".equals(pathnet)) results.addAll(comLab.getPathnetResultsSince(demographicId, lastDataUpdated)); - - for(LabIdAndType id:results) { - logger.debug("id="+id.getLabId() + ",type=" + id.getLabType()); + + for (LabIdAndType id : results) { + logger.debug("id=" + id.getLabId() + ",type=" + id.getLabType()); } - + StringBuilder sentIds = new StringBuilder(); - - if (results.size() == 0) return; - + if (results.size() == 0) + return; + for (LabIdAndType labIdAndType : results) { LabResultData lab = comLab.getLab(labIdAndType); - if(lab != null) { - CachedDemographicLabResult cachedDemographicLabResult = makeCachedDemographicLabResult(demographicId, lab); + if (lab != null) { + CachedDemographicLabResult cachedDemographicLabResult = makeCachedDemographicLabResult(demographicId, + lab); out.writeUnshared(cachedDemographicLabResult); sentIds.append("," + lab.getLabPatientId() + ":" + lab.labType + ":" + lab.segmentID); } else { - logger.warn("Lab missing!!! " + labIdAndType.getLabType() + ":"+ labIdAndType.getLabId()); + logger.warn("Lab missing!!! " + labIdAndType.getLabType() + ":" + labIdAndType.getLabId()); } } - + conformanceTestLog(facility, "LabResultData", sentIds.toString()); } - private CachedDemographicLabResult makeCachedDemographicLabResult(Integer demographicId, LabResultData lab) throws ParserConfigurationException, UnsupportedEncodingException, ClassCastException, ClassNotFoundException, InstantiationException, IllegalAccessException { + private CachedDemographicLabResult makeCachedDemographicLabResult(Integer demographicId, LabResultData lab) + throws ParserConfigurationException, UnsupportedEncodingException, ClassCastException, + ClassNotFoundException, InstantiationException, IllegalAccessException { CachedDemographicLabResult cachedDemographicLabResult = new CachedDemographicLabResult(); FacilityIdLabResultCompositePk pk = new FacilityIdLabResultCompositePk(); @@ -1446,9 +1553,8 @@ private CachedDemographicLabResult makeCachedDemographicLabResult(Integer demogr return (cachedDemographicLabResult); } - - private CachedDemographicHL7LabResult makeCachedDemographicHL7LabResult(Integer demographicId, LabResultData lab) - { + + private CachedDemographicHL7LabResult makeCachedDemographicHL7LabResult(Integer demographicId, LabResultData lab) { CachedDemographicHL7LabResult cachedDemographicLabResult = new CachedDemographicHL7LabResult(); FacilityIdLabResultCompositePk pk = new FacilityIdLabResultCompositePk(); @@ -1460,11 +1566,10 @@ private CachedDemographicHL7LabResult makeCachedDemographicHL7LabResult(Integer cachedDemographicLabResult.setCaisiDemographicId(demographicId); cachedDemographicLabResult.setType(lab.labType); - Hl7TextMessageDao hl7TextMessageDao = SpringUtils.getBean(Hl7TextMessageDao.class); Hl7TextMessage tMsg = hl7TextMessageDao.find(Integer.parseInt(lab.getSegmentID())); - - if(tMsg == null) { + + if (tMsg == null) { return null; } cachedDemographicLabResult.setData(tMsg.getBase64EncodedeMessage()); @@ -1472,22 +1577,25 @@ private CachedDemographicHL7LabResult makeCachedDemographicHL7LabResult(Integer return (cachedDemographicLabResult); } - private void pushForms(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws SQLException, IOException, ParseException { + private void pushForms(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws SQLException, IOException, ParseException { logger.debug("pushing demographic forms facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.forms.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.forms.disabled", "false"))) { return; } - - if( OscarProperties.getInstance().isOntarioBillingRegion() ) { + + if (OscarProperties.getInstance().isOntarioBillingRegion()) { // LabReq2007 and up is only used in Ontario - pushLabReq2007(out, lastDataUpdated, facility, demographicId); + pushLabReq2007(out, lastDataUpdated, facility, demographicId); } } - private void pushLabReq2007(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws SQLException, IOException, ParseException { - List records = FrmLabReq07Record.getPrintRecordsSince(demographicId,lastDataUpdated); - if (records.size() == 0) return; + private void pushLabReq2007(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws SQLException, IOException, ParseException { + List records = FrmLabReq07Record.getPrintRecordsSince(demographicId, lastDataUpdated); + if (records.size() == 0) + return; StringBuilder sentIds = new StringBuilder(); @@ -1498,7 +1606,8 @@ private void pushLabReq2007(ObjectOutputStream out, Date lastDataUpdated, Facili Date date = sdf.parse(p.getProperty("formEdited")); // no change since last sync - if (date != null && date.before(lastDataUpdated)) continue; + if (date != null && date.before(lastDataUpdated)) + continue; CachedDemographicForm cachedDemographicForm = new CachedDemographicForm(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); @@ -1521,13 +1630,14 @@ private void pushLabReq2007(ObjectOutputStream out, Date lastDataUpdated, Facili conformanceTestLog(facility, "formLabReq07", sentIds.toString()); } - private void pushDemographicNotes(ObjectOutputStream demoOut, Date lastDataUpdated, Facility facility, Integer demographicId, List programs) throws IOException { + private void pushDemographicNotes(ObjectOutputStream demoOut, Date lastDataUpdated, Facility facility, + Integer demographicId, List programs) throws IOException { logger.debug("pushing demographicNotes facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.notes.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.notes.disabled", "false"))) { return; } - + HashSet programIds = new HashSet(); for (Program program : programs) programIds.add(program.getId()); @@ -1536,14 +1646,17 @@ private void pushDemographicNotes(ObjectOutputStream demoOut, Date lastDataUpdat StringBuilder sentIds = new StringBuilder(); ArrayList notesToSend = new ArrayList(); - - for (CaseManagementNote localNote : localNotes) { + + for (CaseManagementNote localNote : localNotes) { try { // if it's locked or if it's not in this facility ignore it. - if (localNote.isLocked() || (localNote.getProgram_no() != null && localNote.getProgram_no().length()>0 && !programIds.contains(Integer.parseInt(localNote.getProgram_no())))) continue; + if (localNote.isLocked() || (localNote.getProgram_no() != null && localNote.getProgram_no().length() > 0 + && !programIds.contains(Integer.parseInt(localNote.getProgram_no())))) + continue; // note hasn't changed since last sync - if (localNote.getUpdate_date() != null && localNote.getUpdate_date().before(lastDataUpdated)) continue; + if (localNote.getUpdate_date() != null && localNote.getUpdate_date().before(lastDataUpdated)) + continue; CachedDemographicNote noteToSend = makeRemoteNote(localNote); notesToSend.clear(); @@ -1551,7 +1664,7 @@ private void pushDemographicNotes(ObjectOutputStream demoOut, Date lastDataUpdat demoOut.writeUnshared(notesToSend); noteToSend = null; - + sentIds.append("," + localNote.getId()); } catch (NumberFormatException e) { logger.error("Unexpected error. ProgramNo=" + localNote.getProgram_no(), e); @@ -1572,7 +1685,8 @@ private void pushDemographicNotes(ObjectOutputStream demoOut, Date lastDataUpdat try { // if it's locked or if it's not in this facility ignore it. - if (localNote.isLocked() || !programIds.contains(Integer.parseInt(localNote.getProgram_no()))) continue; + if (localNote.isLocked() || !programIds.contains(Integer.parseInt(localNote.getProgram_no()))) + continue; CachedDemographicNote noteToSend = makeRemoteNote(localNote); notesToSend.clear(); @@ -1600,7 +1714,7 @@ private CachedDemographicNote makeRemoteNote(CaseManagementNote localNote) { note.setCachedDemographicNoteCompositePk(pk); note.setCaisiDemographicId(Integer.parseInt(localNote.getDemographic_no())); - if(localNote.getProgram_no() != null && localNote.getProgram_no().length()>0) { + if (localNote.getProgram_no() != null && localNote.getProgram_no().length() > 0) { note.setCaisiProgramId(Integer.parseInt(localNote.getProgram_no())); } note.setEncounterType(localNote.getEncounter_type()); @@ -1620,28 +1734,22 @@ private CachedDemographicNote makeRemoteNote(CaseManagementNote localNote) { issueCodeType = localIssue.getType(); NoteIssue noteIssue = new NoteIssue(); - if( Issue.CUSTOM_ISSUE.equalsIgnoreCase(issueCodeType) ) { + if (Issue.CUSTOM_ISSUE.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.CUSTOM_ISSUE); - } - else if( Issue.ICD_10.equalsIgnoreCase(issueCodeType) ) { + } else if (Issue.ICD_10.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.ICD10); - } - else if( Issue.ICD_9.equalsIgnoreCase(issueCodeType) ) { + } else if (Issue.ICD_9.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.ICD9); - } - else if( Issue.SNOMED.equalsIgnoreCase(issueCodeType) ) { + } else if (Issue.SNOMED.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.SNOMED); - } - else if( Issue.SNOMED_CORE.equalsIgnoreCase(issueCodeType) ) { + } else if (Issue.SNOMED_CORE.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.SNOMED_CORE); - } - else if( Issue.SYSTEM.equalsIgnoreCase(issueCodeType) ) { + } else if (Issue.SYSTEM.equalsIgnoreCase(issueCodeType)) { noteIssue.setCodeType(CodeType.SYSTEM); - } - else { + } else { continue; } - + noteIssue.setIssueCode(localIssue.getCode()); issues.add(noteIssue); } @@ -1649,21 +1757,24 @@ else if( Issue.SYSTEM.equalsIgnoreCase(issueCodeType) ) { return (note); } - private void pushDemographicDrugs(ObjectOutputStream out, Date lastDataUpdated, Facility facility, List providerIdsInFacility, Integer demographicId) throws IOException { + private void pushDemographicDrugs(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + List providerIdsInFacility, Integer demographicId) throws IOException { logger.debug("pushing demographicDrugss facilityId:" + facility.getId() + ", demographicId:" + demographicId); - - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.drugs.disabled", "false"))) { + + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.drugs.disabled", "false"))) { return; } - + StringBuilder sentIds = new StringBuilder(); List drugs = drugDao.findByDemographicIdUpdatedAfterDate(demographicId, lastDataUpdated); - if (drugs == null || drugs.size() == 0) return; + if (drugs == null || drugs.size() == 0) + return; if (drugs != null) { for (Drug drug : drugs) { - if (!providerIdsInFacility.contains(drug.getProviderNo())) continue; + if (!providerIdsInFacility.contains(drug.getProviderNo())) + continue; CachedDemographicDrug cachedDemographicDrug = new CachedDemographicDrug(); @@ -1699,7 +1810,8 @@ private void pushDemographicDrugs(ObjectOutputStream out, Date lastDataUpdated, cachedDemographicDrug.setRepeats(drug.getRepeat()); cachedDemographicDrug.setRoute(drug.getRoute()); cachedDemographicDrug.setRxDate(drug.getRxDate()); - if (drug.getScriptNo() != null) cachedDemographicDrug.setScriptNo(drug.getScriptNo()); + if (drug.getScriptNo() != null) + cachedDemographicDrug.setScriptNo(drug.getScriptNo()); cachedDemographicDrug.setSpecial(drug.getSpecial()); cachedDemographicDrug.setTakeMax(drug.getTakeMax()); cachedDemographicDrug.setTakeMin(drug.getTakeMin()); @@ -1713,22 +1825,24 @@ private void pushDemographicDrugs(ObjectOutputStream out, Date lastDataUpdated, } } - conformanceTestLog(facility, "Drug", sentIds.toString()); } - private void pushAllergies(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { - logger.debug("pushing demographicAllergies facilityId:" + facility.getId() + ", demographicId:" + demographicId); + private void pushAllergies(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws IOException { + logger.debug( + "pushing demographicAllergies facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.allergies.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.allergies.disabled", "false"))) { return; } - - AllergyDao allergyDao = (AllergyDao) SpringUtils.getBean("allergyDao"); + + AllergyDao allergyDao = (AllergyDao) SpringUtils.getBean(AllergyDao.class); List allergies = allergyDao.findByDemographicIdUpdatedAfterDate(demographicId, lastDataUpdated); - if (allergies.size() == 0) return; + if (allergies.size() == 0) + return; ArrayList cachedAllergies = new ArrayList(); - + StringBuilder sentIds = new StringBuilder(); for (Allergy allergy : allergies) { @@ -1737,60 +1851,65 @@ private void pushAllergies(ObjectOutputStream out, Date lastDataUpdated, Facilit FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); facilityIdIntegerCompositePk.setCaisiItemId(allergy.getAllergyId()); cachedAllergy.setFacilityIdIntegerCompositePk(facilityIdIntegerCompositePk); - - if(allergy.getAgccs() != null){ - cachedAllergy.setAgccs(allergy.getAgccs()); + + if (allergy.getAgccs() != null) { + cachedAllergy.setAgccs(allergy.getAgccs()); } - if(allergy.getAgcsp() != null){ + if (allergy.getAgcsp() != null) { cachedAllergy.setAgcsp(allergy.getAgcsp()); } cachedAllergy.setAgeOfOnset(allergy.getAgeOfOnset()); cachedAllergy.setCaisiDemographicId(demographicId); cachedAllergy.setDescription(allergy.getDescription()); cachedAllergy.setEntryDate(allergy.getEntryDate()); - - if(allergy.getHiclSeqno() != null){ - cachedAllergy.setHiclSeqNo(allergy.getHiclSeqno()); + + if (allergy.getHiclSeqno() != null) { + cachedAllergy.setHiclSeqNo(allergy.getHiclSeqno()); } - if(allergy.getHicSeqno() !=null){ + if (allergy.getHicSeqno() != null) { cachedAllergy.setHicSeqNo(allergy.getHicSeqno()); } - + cachedAllergy.setLifeStage(allergy.getLifeStage()); cachedAllergy.setOnSetCode(allergy.getOnsetOfReaction()); - if (allergy.getDrugrefId() != null) cachedAllergy.setPickId(Integer.parseInt(allergy.getDrugrefId())); + if (allergy.getDrugrefId() != null) + cachedAllergy.setPickId(Integer.parseInt(allergy.getDrugrefId())); cachedAllergy.setReaction(allergy.getReaction()); cachedAllergy.setRegionalIdentifier(allergy.getRegionalIdentifier()); cachedAllergy.setSeverityCode(allergy.getSeverityOfReaction()); - if (allergy.getStartDate() != null) cachedAllergy.setStartDate(allergy.getStartDate()); + if (allergy.getStartDate() != null) + cachedAllergy.setStartDate(allergy.getStartDate()); cachedAllergy.setTypeCode(allergy.getTypeCode()); cachedAllergies.add(cachedAllergy); sentIds.append("," + allergy.getAllergyId()); } - - if(cachedAllergies.size() > 0) { + + if (cachedAllergies.size() > 0) { out.writeUnshared(cachedAllergies); } conformanceTestLog(facility, "Allergy", sentIds.toString()); } - private void pushAppointments(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushAppointments(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + Integer demographicId) throws IOException { logger.debug("pushing appointments facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.appointments.disabled", "false"))) { + if ("true" + .equals(OscarProperties.getInstance().getProperty("integrator.send.appointments.disabled", "false"))) { return; } - - List appointments = appointmentDao.getAllByDemographicNoSince(demographicId,lastDataUpdated); - if (appointments.size() == 0) return; + + List appointments = appointmentDao.getAllByDemographicNoSince(demographicId, lastDataUpdated); + if (appointments.size() == 0) + return; StringBuilder sentIds = new StringBuilder(); ArrayList cachedAppointments = new ArrayList(); - + for (Appointment appointment : appointments) { - + CachedAppointment cachedAppointment = new CachedAppointment(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); facilityIdIntegerCompositePk.setCaisiItemId(appointment.getId()); @@ -1817,25 +1936,27 @@ private void pushAppointments(ObjectOutputStream out, Date lastDataUpdated, Faci out.writeUnshared(cachedAppointments); sentIds.append("," + appointment.getId()); } - + conformanceTestLog(facility, "Appointment", sentIds.toString()); } - private void pushDxresearchs(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushDxresearchs(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws IOException { logger.debug("pushing dxresearchs facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.dx.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.dx.disabled", "false"))) { return; } - - List dxresearchs = dxresearchDao.getByDemographicNoSince(demographicId,lastDataUpdated); - if (dxresearchs.size() == 0) return; + + List dxresearchs = dxresearchDao.getByDemographicNoSince(demographicId, lastDataUpdated); + if (dxresearchs.size() == 0) + return; StringBuilder sentIds = new StringBuilder(); ArrayList cachedDxresearchs = new ArrayList(); - + for (Dxresearch dxresearch : dxresearchs) { - + CachedDxresearch cachedDxresearch = new CachedDxresearch(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); facilityIdIntegerCompositePk.setCaisiItemId(dxresearch.getId().intValue()); @@ -1848,33 +1969,36 @@ private void pushDxresearchs(ObjectOutputStream out, Date lastDataUpdated, Facil cachedDxresearch.setUpdateDate(dxresearch.getUpdateDate()); cachedDxresearch.setStatus(String.valueOf(dxresearch.getStatus())); - cachedDxresearchs.add(cachedDxresearch); + cachedDxresearchs.add(cachedDxresearch); sentIds.append("," + dxresearch.getId()); } - + out.writeUnshared(cachedDxresearchs); - - + conformanceTestLog(facility, "DxResearch", sentIds.toString()); } - private void pushBillingItems(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushBillingItems(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + Integer demographicId) throws IOException { logger.debug("pushing billingitems facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.billing.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.billing.disabled", "false"))) { return; } - - List billingCh1s = billingONItemDao.getCh1ByDemographicNoSince(demographicId, lastDataUpdated); - //don't think we need this based on my tests, but ideally, you'd want to check the timestamps of the billing items, and make sure you have a - //full list of billing headers..but I couldn't replicate editing a bill without the header being updated..so i'll just leave this - //as a note. - - if (billingCh1s.size() == 0) return; + + List billingCh1s = billingONItemDao.getCh1ByDemographicNoSince(demographicId, + lastDataUpdated); + // don't think we need this based on my tests, but ideally, you'd want to check + // the timestamps of the billing items, and make sure you have a + // full list of billing headers..but I couldn't replicate editing a bill without + // the header being updated..so i'll just leave this + // as a note. + + if (billingCh1s.size() == 0) + return; ArrayList cachedBillingOnItems = new ArrayList(); - - + for (BillingONCHeader1 billingCh1 : billingCh1s) { List billingItems = billingONItemDao.getBillingItemByCh1Id(billingCh1.getId()); for (BillingONItem billingItem : billingItems) { @@ -1902,20 +2026,22 @@ private void pushBillingItems(ObjectOutputStream out, Date lastDataUpdated, Faci } - private void pushEforms(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushEforms(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) + throws IOException { logger.debug("pushing eforms facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.eforms.disabled", "false"))) { + if ("true".equals(OscarProperties.getInstance().getProperty("integrator.send.eforms.disabled", "false"))) { return; } - - List eformDatas = eFormDataDao.findByDemographicIdSinceLastDate(demographicId,lastDataUpdated); - if (eformDatas.size() == 0) return; + + List eformDatas = eFormDataDao.findByDemographicIdSinceLastDate(demographicId, lastDataUpdated); + if (eformDatas.size() == 0) + return; StringBuilder sentIds = new StringBuilder(); List fdids = new ArrayList(); ArrayList cachedEformDatas = new ArrayList(); - + int i = 0; for (EFormData eformData : eformDatas) { @@ -1935,72 +2061,76 @@ private void pushEforms(ObjectOutputStream out, Date lastDataUpdated, Facility f cachedEformData.setFormProvider(eformData.getProviderNo()); cachedEformDatas.add(cachedEformData); - - if((++i % 50) == 0) { + + if ((++i % 50) == 0) { out.writeUnshared(cachedEformDatas); cachedEformDatas.clear(); } - - + sentIds.append("," + eformData.getId()); fdids.add(eformData.getId()); } - - if(cachedEformDatas.size()>0) { + + if (cachedEformDatas.size() > 0) { out.writeUnshared(cachedEformDatas); } conformanceTestLog(facility, "EFormData", sentIds.toString()); - if("false".equals(OscarProperties.getInstance().getProperty("integrator.send.eform_values.disabled", "true"))) { + if ("false" + .equals(OscarProperties.getInstance().getProperty("integrator.send.eform_values.disabled", "true"))) { List eFormValues = eFormValueDao.findByFormDataIdList(fdids); ArrayList cachedEformValues = new ArrayList(); - - if (eFormValues.size() == 0) return; - + + if (eFormValues.size() == 0) + return; + i = 0; for (EFormValue eFormValue : eFormValues) { CachedEformValue cachedEformValue = new CachedEformValue(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); facilityIdIntegerCompositePk.setCaisiItemId(eFormValue.getId()); cachedEformValue.setFacilityIdIntegerCompositePk(facilityIdIntegerCompositePk); - + cachedEformValue.setCaisiDemographicId(demographicId); cachedEformValue.setFormId(eFormValue.getFormId()); cachedEformValue.setFormDataId(eFormValue.getFormDataId()); cachedEformValue.setVarName(eFormValue.getVarName()); cachedEformValue.setVarValue(eFormValue.getVarValue()); - + cachedEformValues.add(cachedEformValue); - - if((++i % 50) == 0) { + + if ((++i % 50) == 0) { out.writeUnshared(cachedEformValues); cachedEformValues.clear(); } - + } - - if(cachedEformValues.size() > 0) { + + if (cachedEformValues.size() > 0) { out.writeUnshared(cachedEformValues); } } } - private void pushMeasurements(ObjectOutputStream out, Date lastDataUpdated, Facility facility, Integer demographicId) throws IOException { + private void pushMeasurements(ObjectOutputStream out, Date lastDataUpdated, Facility facility, + Integer demographicId) throws IOException { logger.debug("pushing measurements facilityId:" + facility.getId() + ", demographicId:" + demographicId); - if("true".equals(OscarProperties.getInstance().getProperty("integrator.send.measurements.disabled", "false"))) { + if ("true" + .equals(OscarProperties.getInstance().getProperty("integrator.send.measurements.disabled", "false"))) { return; } - - List measurements = measurementDao.findByDemographicIdUpdatedAfterDate(demographicId, lastDataUpdated); - if (measurements.size() == 0) return; + + List measurements = measurementDao.findByDemographicIdUpdatedAfterDate(demographicId, + lastDataUpdated); + if (measurements.size() == 0) + return; StringBuilder sentIds = new StringBuilder(); ArrayList cachedMeasurements = new ArrayList(); - - + for (Measurement measurement : measurements) { CachedMeasurement cachedMeasurement = new CachedMeasurement(); FacilityIdIntegerCompositePk facilityIdIntegerCompositePk = new FacilityIdIntegerCompositePk(); @@ -2022,54 +2152,58 @@ private void pushMeasurements(ObjectOutputStream out, Date lastDataUpdated, Faci sentIds.append("," + measurement.getId()); - if("false".equals(OscarProperties.getInstance().getProperty("integrator.send.measurementExts.disabled", "true"))) { - List measurementExts = measurementsExtDao.getMeasurementsExtByMeasurementId(measurement.getId()); + if ("false".equals( + OscarProperties.getInstance().getProperty("integrator.send.measurementExts.disabled", "true"))) { + List measurementExts = measurementsExtDao + .getMeasurementsExtByMeasurementId(measurement.getId()); for (MeasurementsExt measurementExt : measurementExts) { CachedMeasurementExt cachedMeasurementExt = new CachedMeasurementExt(); FacilityIdIntegerCompositePk fidIntegerCompositePk = new FacilityIdIntegerCompositePk(); fidIntegerCompositePk.setCaisiItemId(measurementExt.getId()); cachedMeasurementExt.setFacilityIdIntegerCompositePk(fidIntegerCompositePk); - + cachedMeasurementExt.setMeasurementId(measurementExt.getMeasurementId()); cachedMeasurementExt.setKeyval(measurementExt.getKeyVal()); cachedMeasurementExt.setVal(measurementExt.getVal()); - + ArrayList cachedMeasurementExts = new ArrayList(); cachedMeasurementExts.add(cachedMeasurementExt); out.writeUnshared(cachedMeasurementExts); } } - if("false".equals(OscarProperties.getInstance().getProperty("integrator.send.measurementTypes.disabled", "true"))) { + if ("false".equals( + OscarProperties.getInstance().getProperty("integrator.send.measurementTypes.disabled", "true"))) { List measurementTypes = measurementTypeDao.findByType(measurement.getType()); for (MeasurementType measurementType : measurementTypes) { CachedMeasurementType cachedMeasurementType = new CachedMeasurementType(); FacilityIdIntegerCompositePk fidIntegerCompositePk = new FacilityIdIntegerCompositePk(); fidIntegerCompositePk.setCaisiItemId(measurementType.getId()); cachedMeasurementType.setFacilityIdIntegerCompositePk(fidIntegerCompositePk); - + cachedMeasurementType.setType(measurementType.getType()); cachedMeasurementType.setTypeDescription(measurementType.getTypeDescription()); cachedMeasurementType.setMeasuringInstruction(measurementType.getMeasuringInstruction()); - + ArrayList cachedMeasurementTypes = new ArrayList(); cachedMeasurementTypes.add(cachedMeasurementType); out.writeUnshared(cachedMeasurementTypes); } } - if("false".equals(OscarProperties.getInstance().getProperty("integrator.send.measurementMaps.disabled", "true"))) { + if ("false".equals( + OscarProperties.getInstance().getProperty("integrator.send.measurementMaps.disabled", "true"))) { List measurementMaps = measurementMapDao.getMapsByIdent(measurement.getType()); for (MeasurementMap measurementMap : measurementMaps) { - + CachedMeasurementMap cachedMeasurementMap = new CachedMeasurementMap(); FacilityIdIntegerCompositePk fidIntegerCompositePk = new FacilityIdIntegerCompositePk(); fidIntegerCompositePk.setCaisiItemId(measurementMap.getId()); cachedMeasurementMap.setFacilityIdIntegerCompositePk(fidIntegerCompositePk); - + cachedMeasurementMap.setIdentCode(measurementMap.getIdentCode()); cachedMeasurementMap.setLoincCode(measurementMap.getLoincCode()); cachedMeasurementMap.setName(measurementMap.getName()); cachedMeasurementMap.setLabType(measurementMap.getLabType()); - + ArrayList cachedMeasurementMaps = new ArrayList(); cachedMeasurementMaps.add(cachedMeasurementMap); out.writeUnshared(cachedMeasurementMaps); @@ -2079,270 +2213,284 @@ private void pushMeasurements(ObjectOutputStream out, Date lastDataUpdated, Faci conformanceTestLog(facility, "Measurements", sentIds.toString()); } - - - /* - 1) demographicWs.getDemographicIdPushedAfterDateByRequestingFacility : - which gets the local demographicId's which have changed, it will traverse linked records so if a linked record changes, your local id is reported as changed. - 2) demographicWs.getDemographicsPushedAfterDate : - which is a raw listing of the direct records which have changed, i.e. (facilityId, oscarDemographicId). - */ - protected void findChangedRecordsFromIntegrator(LoggedInInfo loggedInInfo, Facility facility) throws MalformedURLException {//throws IOException, ShutdownException { + /* + * 1) demographicWs.getDemographicIdPushedAfterDateByRequestingFacility : + * which gets the local demographicId's which have changed, it will traverse + * linked records so if a linked record changes, your local id is reported as + * changed. + * + * 2) demographicWs.getDemographicsPushedAfterDate : + * which is a raw listing of the direct records which have changed, i.e. + * (facilityId, oscarDemographicId). + */ + protected void findChangedRecordsFromIntegrator(LoggedInInfo loggedInInfo, Facility facility) + throws MalformedURLException {// throws IOException, ShutdownException { logger.info("Start fetch data for facility : " + facility.getId() + " : " + facility.getName()); - boolean integratorLocalStore = OscarProperties.getInstance().getBooleanProperty("INTEGRATOR_LOCAL_STORE","yes"); - if(!integratorLocalStore){ + boolean integratorLocalStore = OscarProperties.getInstance().getBooleanProperty("INTEGRATOR_LOCAL_STORE", + "yes"); + if (!integratorLocalStore) { logger.info("local store not enabled"); return; } DemographicWs demographicService = CaisiIntegratorManager.getDemographicWs(loggedInInfo, facility); - + Calendar nextTime = Calendar.getInstance(); - + Date lastPushDate = new Date(0); - try{ - UserProperty lastPull = userPropertyDao.getProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR+"+"+facility.getId()); + try { + UserProperty lastPull = userPropertyDao + .getProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR + "+" + facility.getId()); lastPushDate.setTime(Long.parseLong(lastPull.getValue())); - }catch(Exception epull){ - MiscUtils.getLogger().error("lastPull Error:",epull); + } catch (Exception epull) { + MiscUtils.getLogger().error("lastPull Error:", epull); lastPushDate = new Date(0); } Calendar cal = Calendar.getInstance(); cal.setTime(lastPushDate); - + List demographicNos = demographicService.getDemographicIdPushedAfterDateByRequestingFacility(cal); - - if(demographicNos.isEmpty()){ + + if (demographicNos.isEmpty()) { logger.debug("No demographics updated on the integrator"); - }else{ - logger.debug("demos changed "+demographicNos.size()); + } else { + logger.debug("demos changed " + demographicNos.size()); } int demographicFetchCount = 0; - for(Integer demographicNo:demographicNos){ - logger.debug("Demographic "+demographicNo+" updated on the integrator, primary emr ? "); + for (Integer demographicNo : demographicNos) { + logger.debug("Demographic " + demographicNo + " updated on the integrator, primary emr ? "); DemographicExt demographicExt = demographicExtDao.getLatestDemographicExt(demographicNo, "primaryEMR"); - if (demographicExt != null && demographicExt.getValue().equals("1")){ + if (demographicExt != null && demographicExt.getValue().equals("1")) { demographicFetchCount++; - BenchmarkTimer benchTimer = new BenchmarkTimer("fetch and save for facilityId:" + facility.getId() + ", demographicId:" + demographicNo + " " + demographicFetchCount + " of " + demographicNos.size()); - IntegratorFallBackManager.saveLinkNotes(loggedInInfo,demographicNo); + BenchmarkTimer benchTimer = new BenchmarkTimer( + "fetch and save for facilityId:" + facility.getId() + ", demographicId:" + demographicNo + " " + + demographicFetchCount + " of " + demographicNos.size()); + IntegratorFallBackManager.saveLinkNotes(loggedInInfo, demographicNo); benchTimer.tag("saveLinkedNotes"); - IntegratorFallBackManager.saveRemoteForms(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveRemoteForms(loggedInInfo, demographicNo); benchTimer.tag("saveRemoteForms"); - - - - IntegratorFallBackManager.saveDemographicIssues(loggedInInfo,demographicNo); + + IntegratorFallBackManager.saveDemographicIssues(loggedInInfo, demographicNo); benchTimer.tag("saveDemographicIssues"); - IntegratorFallBackManager.saveDemographicPreventions(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveDemographicPreventions(loggedInInfo, demographicNo); benchTimer.tag("saveDemographicPreventions"); - IntegratorFallBackManager.saveDemographicDrugs(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveDemographicDrugs(loggedInInfo, demographicNo); benchTimer.tag("saveDemographicDrugs"); - IntegratorFallBackManager.saveAdmissions(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveAdmissions(loggedInInfo, demographicNo); benchTimer.tag("saveAdmissions"); - IntegratorFallBackManager.saveAppointments(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveAppointments(loggedInInfo, demographicNo); benchTimer.tag("saveAppointments"); - IntegratorFallBackManager.saveAllergies(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveAllergies(loggedInInfo, demographicNo); benchTimer.tag("saveAllergies"); - IntegratorFallBackManager.saveDocuments(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveDocuments(loggedInInfo, demographicNo); benchTimer.tag("saveDocuments"); - IntegratorFallBackManager.saveLabResults(loggedInInfo,demographicNo); + IntegratorFallBackManager.saveLabResults(loggedInInfo, demographicNo); benchTimer.tag("saveLabResults"); - - //These don't exist - //IntegratorFallBackManager.saveMeasurements(demographicNo); // Not being displayed yet - //IntegratorFallBackManager.saveDxresearchs(demographicNo); //Not being displayed yet - //IntegratorFallBackManager.saveBillingItems(demographicNo);//Not being displayed yet - //IntegratorFallBackManager.saveEforms(demographicNo);//Not being displayed yet + + // These don't exist + // IntegratorFallBackManager.saveMeasurements(demographicNo); // Not being + // displayed yet + // IntegratorFallBackManager.saveDxresearchs(demographicNo); //Not being + // displayed yet + // IntegratorFallBackManager.saveBillingItems(demographicNo);//Not being + // displayed yet + // IntegratorFallBackManager.saveEforms(demographicNo);//Not being displayed yet logger.debug(benchTimer.report()); } - userPropertyDao.saveProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR+"+"+facility.getId(), "" + nextTime.getTime().getTime()); + userPropertyDao.saveProp(UserProperty.INTEGRATOR_LAST_PULL_PRIMARY_EMR + "+" + facility.getId(), + "" + nextTime.getTime().getTime()); } logger.info("End fetch data for facility : " + facility.getId() + " : " + facility.getName()); } - - - /** - * This method should not be used except during conformance testing. It will log all sends to the integrator. This is superfluous because all data is sent, we already know it's "all sent" even with out the logs. + * This method should not be used except during conformance testing. It will log + * all sends to the integrator. This is superfluous because all data is sent, we + * already know it's "all sent" even with out the logs. */ private static void conformanceTestLog(Facility facility, String dataType, String ids) { if (ConformanceTestHelper.enableConformanceOnlyTestFeatures) { ids = StringUtils.trimToNull(ids); - if (ids != null) LogAction.addLogSynchronous(null, "Integrator Send", dataType, ids, facility.getIntegratorUrl()); + if (ids != null) + LogAction.addLogSynchronous(null, "Integrator Send", dataType, ids, facility.getIntegratorUrl()); } } - + /** - * This is a redirect method to determine compression by the server shell or by Java process. + * This is a redirect method to determine compression by the server shell or by + * Java process. */ - private final String completeDocumentFile(final String parentDir, final String parentFile, final Set documentPaths) { - + private final String completeDocumentFile(final String parentDir, final String parentFile, + final Set documentPaths) { + Path processFile = Paths.get(parentDir, COMPRESSION_SHELL_SCRIPT); String checksum = null; - - if(Files.exists(processFile)) - { + + if (Files.exists(processFile)) { checksum = completeDocumentFile(parentDir, parentFile); - } - else if(! documentPaths.isEmpty()) - { - //TODO consider splitting this thread so that the entire process is not held up with large document archives. + } else if (!documentPaths.isEmpty()) { + // TODO consider splitting this thread so that the entire process is not held up + // with large document archives. checksum = zipDocumentFiles(parentDir, parentFile, documentPaths); } - + return checksum; } /** - * This is an option to "off-load" some of the compression workload by invoking - * a script from the server shell. - * The script must be named build_doc_zip.sh and located + * This is an option to "off-load" some of the compression workload by invoking + * a script from the server shell. + * The script must be named build_doc_zip.sh and located * in the parent directory of this process. - * The script should also produce a checksum file for use in the logs. - * This may involve more intervention and security hardening from the Oscar support provider. + * The script should also produce a checksum file for use in the logs. + * This may involve more intervention and security hardening from the Oscar + * support provider. * * WARNING: this method has not been tested in production as of June 15, 2018 */ - private final String completeDocumentFile(final String parentDir, final String parentFile) { + private final String completeDocumentFile(final String parentDir, final String parentFile) { logger.info("creating document zip file"); String checksum = null; BufferedReader bufferedReader = null; try { File processFile = new File(parentDir + File.separator + COMPRESSION_SHELL_SCRIPT); - - // is this method secure? It loads and executes a shell script from the user accessible - // OscarDocuments directory. - ProcessBuilder processBuilder = new ProcessBuilder(processFile.getAbsolutePath(),parentFile).inheritIO(); - + + // is this method secure? It loads and executes a shell script from the user + // accessible + // OscarDocuments directory. + ProcessBuilder processBuilder = new ProcessBuilder(processFile.getAbsolutePath(), parentFile).inheritIO(); + Process process = processBuilder.start(); - + process.waitFor(); - - if(logger.isDebugEnabled()) { + + if (logger.isDebugEnabled()) { bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); - String data = bufferedReader.readLine(); - logger.debug(data); + String data = bufferedReader.readLine(); + logger.debug(data); } - - // The shell script will need to create a checksum file in the file system named [filename].md5 - // The MD5 hash shall be written to the first line. + + // The shell script will need to create a checksum file in the file system named + // [filename].md5 + // The MD5 hash shall be written to the first line. File checksumfile = new File(parentDir + File.separator + parentFile + ".md5"); - if(checksumfile.exists()) { + if (checksumfile.exists()) { bufferedReader = new BufferedReader(new FileReader(checksumfile)); checksum = bufferedReader.readLine(); logger.debug("Found MD5 for document zip file " + processFile.getAbsolutePath()); } - - }catch(Exception e) { - logger.error("Error",e); + + } catch (Exception e) { + logger.error("Error", e); } finally { - IOUtils.closeQuietly(bufferedReader); + IOUtils.closeQuietly(bufferedReader); } - + logger.info("done creating document zip file"); - + return checksum; } - private String completeFile(String parentDir,final String parentFile) throws NoSuchAlgorithmException, IOException { - - String[] files = new File(parentDir).list(new FilenameFilter(){ - public boolean accept(File dir, String name) { - if(name.startsWith(parentFile) && !name.equals(parentFile + COMPRESSED_DOCUMENTS_APPENDAGE + ".zip")) { - return true; - } - if(name.indexOf("documentMeta.txt") != -1) { - return true; - } - return false; - } + private String completeFile(String parentDir, final String parentFile) + throws NoSuchAlgorithmException, IOException { + + String[] files = new File(parentDir).list(new FilenameFilter() { + public boolean accept(File dir, String name) { + if (name.startsWith(parentFile) && !name.equals(parentFile + COMPRESSED_DOCUMENTS_APPENDAGE + ".zip")) { + return true; + } + if (name.indexOf("documentMeta.txt") != -1) { + return true; + } + return false; + } }); logger.info("CREATING ZIP FILE NOW"); - createZipFile(parentDir,parentFile,files); - //delete those files since they are zipped - for(int x=0;x documentPaths) { - + private final String zipDocumentFiles(final String parentDir, final String parentFile, + final Set documentPaths) { + Path destination = Paths.get(parentDir, parentFile + COMPRESSED_DOCUMENTS_APPENDAGE + ".zipTemp"); logger.info("creating document zip file " + destination.toAbsolutePath().toString()); ZipOutputStream out = null; String checksum = null; - + try { out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destination.toFile()))); out.setMethod(ZipOutputStream.DEFLATED); - - for(Path documentPath : documentPaths) { + + for (Path documentPath : documentPaths) { addZipFile(documentPath.toAbsolutePath().toString(), out, documentPath.getFileName().toString()); } - + checksum = getFileChecksum(MessageDigest.getInstance("MD5"), destination.toFile()); - + } catch (IOException e) { logger.error("Error creating zip file for document manifest " + documentPaths, e); } catch (NoSuchAlgorithmException e) { @@ -2350,109 +2498,112 @@ private final String zipDocumentFiles(final String parentDir, final String paren } finally { IOUtils.closeQuietly(out); } - + return checksum; } - - private void addZipFile(final String source, final ZipOutputStream destination, final String filename) throws IOException { + + private void addZipFile(final String source, final ZipOutputStream destination, final String filename) + throws IOException { byte data[] = new byte[1024]; - //out.putNextEntry(new ZipEntry(files[x].getName())); + // out.putNextEntry(new ZipEntry(files[x].getName())); FileInputStream fi = new FileInputStream(source); BufferedInputStream origin = new BufferedInputStream(fi, 1024); - + ZipEntry entry = new ZipEntry(filename); destination.putNextEntry(entry); - int count; - while((count = origin.read(data, 0, 1024)) != -1) { - destination.write(data, 0, count); - } - origin.close(); + int count; + while ((count = origin.read(data, 0, 1024)) != -1) { + destination.write(data, 0, count); + } + origin.close(); } - - private static String getFileChecksum(MessageDigest digest, File file) throws IOException - { - //Get file input stream for reading the file content - FileInputStream fis = new FileInputStream(file); - - //Create byte array to read data in chunks - byte[] byteArray = new byte[1024]; - int bytesCount = 0; - - //Read file data and update in message digest - while ((bytesCount = fis.read(byteArray)) != -1) { - digest.update(byteArray, 0, bytesCount); - } - - //close the stream; We don't need it now. - fis.close(); - - //Get the hash's bytes - byte[] bytes = digest.digest(); - - //This bytes[] has bytes in decimal format; - //Convert it to hexadecimal format - StringBuilder sb = new StringBuilder(); - for(int i=0; i< bytes.length ;i++) - { - sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); - } - - //return complete hash - return sb.toString(); + + private static String getFileChecksum(MessageDigest digest, File file) throws IOException { + // Get file input stream for reading the file content + FileInputStream fis = new FileInputStream(file); + + // Create byte array to read data in chunks + byte[] byteArray = new byte[1024]; + int bytesCount = 0; + + // Read file data and update in message digest + while ((bytesCount = fis.read(byteArray)) != -1) { + digest.update(byteArray, 0, bytesCount); + } + + // close the stream; We don't need it now. + fis.close(); + + // Get the hash's bytes + byte[] bytes = digest.digest(); + + // This bytes[] has bytes in decimal format; + // Convert it to hexadecimal format + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < bytes.length; i++) { + sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)); + } + + // return complete hash + return sb.toString(); } /** * Defaults to DOCUMENT_DIR when INTEGRATOR_OUTPUT_DIR is not set. + * * @return */ public static String getOutputDirectory() { String integratorOutputDirectory = OscarProperties.getInstance().getProperty("INTEGRATOR_OUTPUT_DIR"); - if(StringUtils.isNotEmpty(integratorOutputDirectory)) { + if (StringUtils.isNotEmpty(integratorOutputDirectory)) { outputDirectory = integratorOutputDirectory; } - - if(outputDirectory.endsWith(File.separator)) { - outputDirectory = outputDirectory.substring(0, outputDirectory.length() -1); + + if (outputDirectory.endsWith(File.separator)) { + outputDirectory = outputDirectory.substring(0, outputDirectory.length() - 1); } - + return outputDirectory; } public static void setOutputDirectory(String outputDirectory) { CaisiIntegratorUpdateTask.outputDirectory = outputDirectory; } - + private final IntegratorFileLog updateLogs(final LoggedInInfo loggedInInfo, final Facility facility) { - - // get the date from the last log entry + + // get the date from the last log entry IntegratorFileLog lastFile = null; - List integratorFileLogList = integratorFileLogManager.getStatusNotCompleteOrError(loggedInInfo); + List integratorFileLogList = integratorFileLogManager + .getStatusNotCompleteOrError(loggedInInfo); FacilityWs facilityWs = null; - - if(! integratorFileLogList.isEmpty()) { + + if (!integratorFileLogList.isEmpty()) { lastFile = integratorFileLogList.get(0); } - + try { facilityWs = CaisiIntegratorManager.getFacilityWs(loggedInInfo, facility); } catch (MalformedURLException e) { logger.error("Connection error while syncing file logs", e); - } + } - // sort out the current status' in the integrator file log with the integrator log. - for(IntegratorFileLog integratorFileLog : integratorFileLogList) { + // sort out the current status' in the integrator file log with the integrator + // log. + for (IntegratorFileLog integratorFileLog : integratorFileLogList) { List importLogList = null; - - if(facilityWs != null) { - importLogList = facilityWs.getImportLogByFilenameAndChecksum(integratorFileLog.getFilename(), integratorFileLog.getChecksum()); + + if (facilityWs != null) { + importLogList = facilityWs.getImportLogByFilenameAndChecksum(integratorFileLog.getFilename(), + integratorFileLog.getChecksum()); } - - if(importLogList == null) { + + if (importLogList == null) { continue; } - - for(ImportLog importLog : importLogList) { + + for (ImportLog importLog : importLogList) { integratorFileLog.setIntegratorStatus(importLog.getStatus()); integratorFileLogManager.updateIntegratorFileLog(loggedInInfo, integratorFileLog); } @@ -2461,4 +2612,3 @@ private final IntegratorFileLog updateLogs(final LoggedInInfo loggedInInfo, fina return lastFile; } } - diff --git a/src/main/java/org/oscarehr/PMmodule/caisi_integrator/ConformanceTestHelper.java b/src/main/java/org/oscarehr/PMmodule/caisi_integrator/ConformanceTestHelper.java index d1024e5c8f..6f91ea595f 100644 --- a/src/main/java/org/oscarehr/PMmodule/caisi_integrator/ConformanceTestHelper.java +++ b/src/main/java/org/oscarehr/PMmodule/caisi_integrator/ConformanceTestHelper.java @@ -104,7 +104,7 @@ public static void copyLinkedDemographicsPropertiesToLocal(LoggedInInfo loggedIn logger.debug("remoteDemographic:"+ReflectionToStringBuilder.toString(demographicTransfer)); - DemographicDao demographicDao=(DemographicDao) SpringUtils.getBean("demographicDao"); + DemographicDao demographicDao=(DemographicDao) SpringUtils.getBean(DemographicDao.class); Demographic demographic=demographicDao.getDemographicById(localDemographicId); CaisiIntegratorManager.copyDemographicFieldsIfNotNull(demographicTransfer, demographic); @@ -132,7 +132,7 @@ public static boolean hasDifferentRemoteDemographics(LoggedInInfo loggedInInfo, logger.debug("remoteDemographic:"+ReflectionToStringBuilder.toString(demographicTransfer)); - DemographicDao demographicDao=(DemographicDao) SpringUtils.getBean("demographicDao"); + DemographicDao demographicDao=(DemographicDao) SpringUtils.getBean(DemographicDao.class); Demographic demographic=demographicDao.getDemographicById(localDemographicId); if (demographicTransfer.getBirthDate()!=null && !(DateUtils.getNumberOfDaysBetweenTwoDates(demographicTransfer.getBirthDate(),demographic.getBirthDay()) == 0)) ret = true; diff --git a/src/main/java/org/oscarehr/PMmodule/caisi_integrator/IntegratorLocalStoreUpdateJob.java b/src/main/java/org/oscarehr/PMmodule/caisi_integrator/IntegratorLocalStoreUpdateJob.java index 87ed014022..ad0623a247 100644 --- a/src/main/java/org/oscarehr/PMmodule/caisi_integrator/IntegratorLocalStoreUpdateJob.java +++ b/src/main/java/org/oscarehr/PMmodule/caisi_integrator/IntegratorLocalStoreUpdateJob.java @@ -50,7 +50,7 @@ public class IntegratorLocalStoreUpdateJob implements OscarRunnable { private static final Logger logger = MiscUtils.getLogger(); private FacilityDao facilityDao = SpringUtils.getBean(FacilityDao.class); - private UserPropertyDAO userPropertyDao = (UserPropertyDAO) SpringUtils.getBean("UserPropertyDAO"); + private UserPropertyDAO userPropertyDao = (UserPropertyDAO) SpringUtils.getBean(UserPropertyDAO.class); private DemographicExtDao demographicExtDao = SpringUtils.getBean(DemographicExtDao.class); diff --git a/src/main/java/org/oscarehr/PMmodule/dao/AgencyDao.java b/src/main/java/org/oscarehr/PMmodule/dao/AgencyDao.java index 0bd4a8281a..922b1bd50f 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/AgencyDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/AgencyDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.dao; import java.util.List; @@ -28,35 +30,12 @@ import org.apache.logging.log4j.Logger; import org.oscarehr.PMmodule.model.Agency; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class AgencyDao extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - public Agency getLocalAgency() { - Agency agency = null; - - List results = getHibernateTemplate().find("from Agency a"); - - if (!results.isEmpty()) { - agency = (Agency)results.get(0); - } - - return agency; - } - - public void saveAgency(Agency agency) { - if (agency == null) { - throw new IllegalArgumentException(); - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; - getHibernateTemplate().saveOrUpdate(agency); +public interface AgencyDao{ - if (log.isDebugEnabled()) { - log.debug("saveAgency : id = " + agency.getId()); - } + public Agency getLocalAgency(); - } + public void saveAgency(Agency agency); -} +} \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/AgencyDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/AgencyDaoImpl.java new file mode 100644 index 0000000000..2b0d6ff42e --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/AgencyDaoImpl.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.Agency; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class AgencyDaoImpl extends HibernateDaoSupport implements AgencyDao{ + + private Logger log=MiscUtils.getLogger(); + + public Agency getLocalAgency() { + Agency agency = null; + + List results = getHibernateTemplate().find("from Agency a"); + + if (!results.isEmpty()) { + agency = (Agency)results.get(0); + } + + return agency; + } + + public void saveAgency(Agency agency) { + if (agency == null) { + throw new IllegalArgumentException(); + } + + getHibernateTemplate().saveOrUpdate(agency); + + if (log.isDebugEnabled()) { + log.debug("saveAgency : id = " + agency.getId()); + } + + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAO.java index aa68058dc8..c06f839f3d 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,256 +20,49 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.logging.log4j.Logger; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.criterion.Expression; -import org.oscarehr.PMmodule.model.ClientReferral; -import org.oscarehr.PMmodule.model.Program; -import org.oscarehr.common.model.Admission; -import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ClientReferralDAO extends HibernateDaoSupport { - - private Logger log = MiscUtils.getLogger(); - - public List getReferrals() { - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from ClientReferral"); - - if (log.isDebugEnabled()) { - log.debug("getReferrals: # of results=" + results.size()); - } - - return results; - } - - @SuppressWarnings("unchecked") - public List getReferrals(Long clientId) { - - if (clientId == null || clientId.longValue() <= 0) { - throw new IllegalArgumentException(); - } - - List results = this.getHibernateTemplate().find("from ClientReferral cr where cr.ClientId = ?", clientId); - - if (log.isDebugEnabled()) { - log.debug("getReferrals: clientId=" + clientId + ",# of results=" + results.size()); - } - - // [ 1842692 ] RFQ Feature - temp change for pmm referral history report - results = displayResult(results); - // end of change - - return results; - } - - @SuppressWarnings("unchecked") - public List getReferralsByFacility(Long clientId, Integer facilityId) { - - if (clientId == null || clientId.longValue() <= 0) { - throw new IllegalArgumentException(); - } - if (facilityId == null || facilityId.intValue() < 0) { - throw new IllegalArgumentException(); - } - - String sSQL="from ClientReferral cr where cr.ClientId = ? " + - " and ( (cr.FacilityId=?) or (cr.ProgramId in (select s.id from Program s where s.facilityId=? or s.facilityId is null)))"; - List results = this.getHibernateTemplate().find(sSQL, new Object[] { clientId, facilityId, facilityId }); -// "from ClientReferral cr where cr.ClientId = ?", clientId); - - if (log.isDebugEnabled()) { - log.debug("getReferralsByFacility: clientId=" + clientId + ",# of results=" + results.size()); - } - results = displayResult(results); - return results; - } - - // [ 1842692 ] RFQ Feature - temp change for pmm referral history report - // - suggestion: to add a new field to the table client_referral (Referring program/agency) - public List displayResult(List lResult) { - List ret = new ArrayList (); - //ProgramDao pd = new ProgramDao(); - //AdmissionDao ad = new AdmissionDao(); - - for(ClientReferral element : lResult) { - ClientReferral cr = element; - - ClientReferral result = null; - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from ClientReferral r where r.ClientId = ? and r.Id < ? order by r.Id desc", new Object[] {cr.getClientId(), cr.getId()}); - - // temp - completionNotes/Referring program/agency, notes/External - String completionNotes = ""; - String notes = ""; - if (!results.isEmpty()) { - result = results.get(0); - completionNotes = result.getProgramName(); - notes = isExternalProgram(Integer.parseInt(result.getProgramId().toString())) ? "Yes" : "No"; - } else { - // get program from table admission - List lr = getAdmissions(Integer.parseInt(cr.getClientId().toString())); - Admission admission = lr.get(lr.size() - 1); - completionNotes = admission.getProgramName(); - notes = isExternalProgram(Integer.parseInt(admission.getProgramId().toString())) ? "Yes" : "No"; - } - - // set the values for added report fields - cr.setCompletionNotes(completionNotes); - cr.setNotes(notes); - - ret.add(cr); - } - - return ret; - } - - private boolean isExternalProgram(Integer programId) { - boolean result = false; - - if (programId == null || programId <= 0) { - throw new IllegalArgumentException(); - } - - String queryStr = "FROM Program p WHERE p.id = ? AND p.type = 'external'"; - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr, programId); - - if (!rs.isEmpty()) { - result = true; - } - - if (log.isDebugEnabled()) { - log.debug("isCommunityProgram: id=" + programId + " : " + result); - } - - return result; - } - - private List getAdmissions(Integer demographicNo) { - if (demographicNo == null || demographicNo <= 0) { - throw new IllegalArgumentException(); - } - - String queryStr = "FROM Admission a WHERE a.clientId=? ORDER BY a.admissionDate DESC"; - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr, new Object[] { demographicNo }); - return rs; - } - // end of change - - @SuppressWarnings("unchecked") - public List getActiveReferrals(Long clientId, Integer facilityId) { - if (clientId == null || clientId.longValue() <= 0) { - throw new IllegalArgumentException(); - } - - List results; - if(facilityId==null){ - results = this.getHibernateTemplate().find("from ClientReferral cr where cr.ClientId = ? and (cr.Status = '"+ClientReferral.STATUS_ACTIVE+"' or cr.Status = '"+ClientReferral.STATUS_PENDING+"' or cr.Status = '"+ClientReferral.STATUS_UNKNOWN+"')", clientId); - }else{ - ArrayList paramList = new ArrayList(); - String sSQL="from ClientReferral cr where cr.ClientId = ? and (cr.Status = '" + ClientReferral.STATUS_ACTIVE+"' or cr.Status = '" + - ClientReferral.STATUS_PENDING + "' or cr.Status = '" + ClientReferral.STATUS_UNKNOWN + "')" + - " and ( (cr.FacilityId=?) or (cr.ProgramId in (select s.id from Program s where s.facilityId=?)))"; - paramList.add(clientId); - paramList.add(facilityId); - paramList.add(facilityId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - results = getHibernateTemplate().find(sSQL, params); - } - - if (log.isDebugEnabled()) { - log.debug("getActiveReferrals: clientId=" + clientId + ",# of results=" + results.size()); - } - - return results; - } - - @SuppressWarnings("unchecked") - public List getActiveReferralsByClientAndProgram(Long clientId, Long programId) { - if (clientId == null || clientId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - List results; - - ArrayList paramList = new ArrayList(); - String sSQL="from ClientReferral cr where cr.ClientId = ? and cr.ProgramId=? and (cr.Status = '" + ClientReferral.STATUS_ACTIVE+"' or cr.Status = '" + - ClientReferral.STATUS_CURRENT + "') order by cr.ReferralDate DESC" ; - paramList.add(clientId); - paramList.add(programId); - - Object params[] = paramList.toArray(new Object[paramList.size()]); - results = getHibernateTemplate().find(sSQL, params); - - if (log.isDebugEnabled()) { - log.debug("getActiveReferralsByClientAndProgram: clientId=" + clientId + "programId " + programId +", # of results=" + results.size()); - } - - return results; - } - - public ClientReferral getClientReferral(Long id) { - if (id == null || id.longValue() <= 0) { - throw new IllegalArgumentException(); - } - - ClientReferral result = this.getHibernateTemplate().get(ClientReferral.class, id); - - if (log.isDebugEnabled()) { - log.debug("getClientReferral: id=" + id + ",found=" + (result != null)); - } - - return result; - } - - public void saveClientReferral(ClientReferral referral) { - if (referral == null) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().saveOrUpdate(referral); - - if (log.isDebugEnabled()) { - log.debug("saveClientReferral: id=" + referral.getId()); - } - - } - - @SuppressWarnings("unchecked") - public List search(ClientReferral referral) { - Session session = getSession(); - try { - Criteria criteria = session.createCriteria(ClientReferral.class); - - if (referral != null && referral.getProgramId().longValue() > 0) { - criteria.add(Expression.eq("ProgramId", referral.getProgramId())); - } - - return criteria.list(); - }finally { - this.releaseSession(session); - } - } - - public List getClientReferralsByProgram(int programId) { - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from ClientReferral cr where cr.ProgramId = ?", new Long(programId)); - - return results; - } - -} + package org.oscarehr.PMmodule.dao; + + import java.util.ArrayList; + import java.util.List; + + import org.apache.logging.log4j.Logger; + import org.hibernate.Criteria; + import org.hibernate.Session; + import org.hibernate.criterion.Expression; + import org.oscarehr.PMmodule.model.ClientReferral; + import org.oscarehr.PMmodule.model.Program; + import org.oscarehr.common.model.Admission; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + import org.springframework.beans.factory.annotation.Autowired; + import org.hibernate.SessionFactory; + + public interface ClientReferralDAO { + + public List getReferrals(); + + public List getReferrals(Long clientId); + + public List getReferralsByFacility(Long clientId, Integer facilityId); + + // [ 1842692 ] RFQ Feature - temp change for pmm referral history report + // - suggestion: to add a new field to the table client_referral (Referring program/agency) + public List displayResult(List lResult); + public List getActiveReferrals(Long clientId, Integer facilityId); + + public List getActiveReferralsByClientAndProgram(Long clientId, Long programId); + + public ClientReferral getClientReferral(Long id); + + public void saveClientReferral(ClientReferral referral); + + public List search(ClientReferral referral); + + public List getClientReferralsByProgram(int programId); + + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAOImpl.java new file mode 100644 index 0000000000..e74325a12b --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ClientReferralDAOImpl.java @@ -0,0 +1,287 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.criterion.Expression; +import org.oscarehr.PMmodule.model.ClientReferral; +import org.oscarehr.PMmodule.model.Program; +import org.oscarehr.common.model.Admission; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +public class ClientReferralDAOImpl extends HibernateDaoSupport implements ClientReferralDAO{ + + private Logger log = MiscUtils.getLogger(); + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + public List getReferrals() { + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate().find("from ClientReferral"); + + if (log.isDebugEnabled()) { + log.debug("getReferrals: # of results=" + results.size()); + } + + return results; + } + + @SuppressWarnings("unchecked") + public List getReferrals(Long clientId) { + + if (clientId == null || clientId.longValue() <= 0) { + throw new IllegalArgumentException(); + } + + List results = (List) this.getHibernateTemplate().find("from ClientReferral cr where cr.ClientId = ?", clientId); + + if (log.isDebugEnabled()) { + log.debug("getReferrals: clientId=" + clientId + ",# of results=" + results.size()); + } + + // [ 1842692 ] RFQ Feature - temp change for pmm referral history report + results = displayResult(results); + // end of change + + return results; + } + + @SuppressWarnings("unchecked") + public List getReferralsByFacility(Long clientId, Integer facilityId) { + + if (clientId == null || clientId.longValue() <= 0) { + throw new IllegalArgumentException(); + } + if (facilityId == null || facilityId.intValue() < 0) { + throw new IllegalArgumentException(); + } + + String sSQL="from ClientReferral cr where cr.ClientId = ? " + + " and ( (cr.FacilityId=?) or (cr.ProgramId in (select s.id from Program s where s.facilityId=? or s.facilityId is null)))"; + List results = (List) this.getHibernateTemplate().find(sSQL, new Object[] { clientId, facilityId, facilityId }); +// "from ClientReferral cr where cr.ClientId = ?", clientId); + + if (log.isDebugEnabled()) { + log.debug("getReferralsByFacility: clientId=" + clientId + ",# of results=" + results.size()); + } + results = displayResult(results); + return results; + } + + // [ 1842692 ] RFQ Feature - temp change for pmm referral history report + // - suggestion: to add a new field to the table client_referral (Referring program/agency) + public List displayResult(List lResult) { + List ret = new ArrayList (); + //ProgramDao pd = new ProgramDao(); + //AdmissionDao ad = new AdmissionDao(); + + for(ClientReferral element : lResult) { + ClientReferral cr = element; + + ClientReferral result = null; + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate().find("from ClientReferral r where r.ClientId = ? and r.Id < ? order by r.Id desc", new Object[] {cr.getClientId(), cr.getId()}); + + // temp - completionNotes/Referring program/agency, notes/External + String completionNotes = ""; + String notes = ""; + if (!results.isEmpty()) { + result = results.get(0); + completionNotes = result.getProgramName(); + notes = isExternalProgram(Integer.parseInt(result.getProgramId().toString())) ? "Yes" : "No"; + } else { + // get program from table admission + List lr = getAdmissions(Integer.parseInt(cr.getClientId().toString())); + Admission admission = lr.get(lr.size() - 1); + completionNotes = admission.getProgramName(); + notes = isExternalProgram(Integer.parseInt(admission.getProgramId().toString())) ? "Yes" : "No"; + } + + // set the values for added report fields + cr.setCompletionNotes(completionNotes); + cr.setNotes(notes); + + ret.add(cr); + } + + return ret; + } + + private boolean isExternalProgram(Integer programId) { + boolean result = false; + + if (programId == null || programId <= 0) { + throw new IllegalArgumentException(); + } + + String queryStr = "FROM Program p WHERE p.id = ? AND p.type = 'external'"; + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr, programId); + + if (!rs.isEmpty()) { + result = true; + } + + if (log.isDebugEnabled()) { + log.debug("isCommunityProgram: id=" + programId + " : " + result); + } + + return result; + } + + private List getAdmissions(Integer demographicNo) { + if (demographicNo == null || demographicNo <= 0) { + throw new IllegalArgumentException(); + } + + String queryStr = "FROM Admission a WHERE a.clientId=? ORDER BY a.admissionDate DESC"; + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr, new Object[] { demographicNo }); + return rs; + } + // end of change + + @SuppressWarnings("unchecked") + public List getActiveReferrals(Long clientId, Integer facilityId) { + if (clientId == null || clientId.longValue() <= 0) { + throw new IllegalArgumentException(); + } + + List results; + if(facilityId==null){ + results = (List) this.getHibernateTemplate().find("from ClientReferral cr where cr.ClientId = ? and (cr.Status = '"+ClientReferral.STATUS_ACTIVE+"' or cr.Status = '"+ClientReferral.STATUS_PENDING+"' or cr.Status = '"+ClientReferral.STATUS_UNKNOWN+"')", clientId); + }else{ + ArrayList paramList = new ArrayList(); + String sSQL="from ClientReferral cr where cr.ClientId = ? and (cr.Status = '" + ClientReferral.STATUS_ACTIVE+"' or cr.Status = '" + + ClientReferral.STATUS_PENDING + "' or cr.Status = '" + ClientReferral.STATUS_UNKNOWN + "')" + + " and ( (cr.FacilityId=?) or (cr.ProgramId in (select s.id from Program s where s.facilityId=?)))"; + paramList.add(clientId); + paramList.add(facilityId); + paramList.add(facilityId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + results = (List) getHibernateTemplate().find(sSQL, params); + } + + if (log.isDebugEnabled()) { + log.debug("getActiveReferrals: clientId=" + clientId + ",# of results=" + results.size()); + } + + return results; + } + + @SuppressWarnings("unchecked") + public List getActiveReferralsByClientAndProgram(Long clientId, Long programId) { + if (clientId == null || clientId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + List results; + + ArrayList paramList = new ArrayList(); + String sSQL="from ClientReferral cr where cr.ClientId = ? and cr.ProgramId=? and (cr.Status = '" + ClientReferral.STATUS_ACTIVE+"' or cr.Status = '" + + ClientReferral.STATUS_CURRENT + "') order by cr.ReferralDate DESC" ; + paramList.add(clientId); + paramList.add(programId); + + Object params[] = paramList.toArray(new Object[paramList.size()]); + results = (List) getHibernateTemplate().find(sSQL, params); + + if (log.isDebugEnabled()) { + log.debug("getActiveReferralsByClientAndProgram: clientId=" + clientId + "programId " + programId +", # of results=" + results.size()); + } + + return results; + } + + public ClientReferral getClientReferral(Long id) { + if (id == null || id.longValue() <= 0) { + throw new IllegalArgumentException(); + } + + ClientReferral result = this.getHibernateTemplate().get(ClientReferral.class, id); + + if (log.isDebugEnabled()) { + log.debug("getClientReferral: id=" + id + ",found=" + (result != null)); + } + + return result; + } + + public void saveClientReferral(ClientReferral referral) { + if (referral == null) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().saveOrUpdate(referral); + + if (log.isDebugEnabled()) { + log.debug("saveClientReferral: id=" + referral.getId()); + } + + } + + @SuppressWarnings("unchecked") + public List search(ClientReferral referral) { + //Session session = getSession(); + Session session = sessionFactory.getCurrentSession(); + try { + Criteria criteria = session.createCriteria(ClientReferral.class); + + if (referral != null && referral.getProgramId().longValue() > 0) { + criteria.add(Expression.eq("ProgramId", referral.getProgramId())); + } + + return criteria.list(); + }finally { + //this.releaseSession(session); + session.close(); + } + } + + public List getClientReferralsByProgram(int programId) { + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate().find("from ClientReferral cr where cr.ProgramId = ?", new Long(programId)); + + return results; + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDao.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDao.java index 3e9c38d27d..7bd37d92f2 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,90 +21,31 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import javax.persistence.Query; - -import org.oscarehr.PMmodule.model.Criteria; -import org.oscarehr.common.dao.AbstractDao; -import org.springframework.stereotype.Repository; - -@Repository -public class CriteriaDao extends AbstractDao { - - public CriteriaDao() { - super(Criteria.class); - } + package org.oscarehr.PMmodule.dao; - public List getCriteriaByTemplateId(Integer templateId) { - Query q = entityManager.createQuery("select c from Criteria c where c.templateId=?"); - q.setParameter(1, templateId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - public Criteria getCriteriaByTemplateIdVacancyIdTypeId(Integer templateId, Integer vacancyId, Integer typeId) { - if(templateId != null && vacancyId != null) { - Query q = entityManager.createQuery("select c from Criteria c where c.templateId=? and c.criteriaTypeId=? and c.vacancyId=?"); - q.setParameter(1, templateId); - q.setParameter(2, typeId); - q.setParameter(3, vacancyId); - return this.getSingleResultOrNull(q); - } else if(templateId == null && vacancyId != null) { - Query q = entityManager.createQuery("select c from Criteria c where c.templateId IS NULL and c.criteriaTypeId=? and c.vacancyId=?"); - q.setParameter(1, typeId); - q.setParameter(2, vacancyId); - return this.getSingleResultOrNull(q); - } else if(templateId != null && vacancyId == null) { - Query q = entityManager.createQuery("select c from Criteria c where c.templateId=? and c.criteriaTypeId=? and c.vacancyId is null"); - q.setParameter(1, templateId); - q.setParameter(2, typeId); - return this.getSingleResultOrNull(q); - } else { - return null; - } - - - } - - public List getCriteriasByVacancyId(Integer vacancyId) { - Query q = entityManager.createQuery("select c from Criteria c where c.vacancyId=?"); - q.setParameter(1, vacancyId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - public List getRefinedCriteriasByVacancyId(Integer vacancyId) { - Query q = entityManager.createQuery("select c from Criteria c where c.canBeAdhoc!=? and c.vacancyId=?"); - q.setParameter(1, 0);//canBeAdhoc=0 means don't appear in vacancy. - q.setParameter(2, vacancyId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - public List getRefinedCriteriasByTemplateId(Integer templateId) { - Query q = entityManager.createQuery("select c from Criteria c where c.canBeAdhoc!=? and c.templateId=?"); - q.setParameter(1, 0); //canBeAdhoc=0 means don't appear in vacancy. - q.setParameter(2, templateId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - -} + import java.util.List; + + import javax.persistence.Query; + + import org.oscarehr.PMmodule.model.Criteria; + import org.oscarehr.common.dao.AbstractDao; + import org.springframework.stereotype.Repository; + + public interface CriteriaDao extends AbstractDao { + public List getCriteriaByTemplateId(Integer templateId); + + public Criteria getCriteriaByTemplateIdVacancyIdTypeId(Integer templateId, Integer vacancyId, Integer typeId); + + public List getCriteriasByVacancyId(Integer vacancyId); + + public List getRefinedCriteriasByVacancyId(Integer vacancyId); + + public List getRefinedCriteriasByTemplateId(Integer templateId); + + + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDaoImpl.java new file mode 100644 index 0000000000..5db637e811 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaDaoImpl.java @@ -0,0 +1,112 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.Criteria; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class CriteriaDaoImpl extends AbstractDaoImpl implements CriteriaDao{ + + public CriteriaDaoImpl() { + super(Criteria.class); + } + + public List getCriteriaByTemplateId(Integer templateId) { + Query q = entityManager.createQuery("select c from Criteria c where c.templateId=?"); + q.setParameter(1, templateId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + public Criteria getCriteriaByTemplateIdVacancyIdTypeId(Integer templateId, Integer vacancyId, Integer typeId) { + if(templateId != null && vacancyId != null) { + Query q = entityManager.createQuery("select c from Criteria c where c.templateId=? and c.criteriaTypeId=? and c.vacancyId=?"); + q.setParameter(1, templateId); + q.setParameter(2, typeId); + q.setParameter(3, vacancyId); + return this.getSingleResultOrNull(q); + } else if(templateId == null && vacancyId != null) { + Query q = entityManager.createQuery("select c from Criteria c where c.templateId IS NULL and c.criteriaTypeId=? and c.vacancyId=?"); + q.setParameter(1, typeId); + q.setParameter(2, vacancyId); + return this.getSingleResultOrNull(q); + } else if(templateId != null && vacancyId == null) { + Query q = entityManager.createQuery("select c from Criteria c where c.templateId=? and c.criteriaTypeId=? and c.vacancyId is null"); + q.setParameter(1, templateId); + q.setParameter(2, typeId); + return this.getSingleResultOrNull(q); + } else { + return null; + } + + + } + + public List getCriteriasByVacancyId(Integer vacancyId) { + Query q = entityManager.createQuery("select c from Criteria c where c.vacancyId=?"); + q.setParameter(1, vacancyId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + public List getRefinedCriteriasByVacancyId(Integer vacancyId) { + Query q = entityManager.createQuery("select c from Criteria c where c.canBeAdhoc!=? and c.vacancyId=?"); + q.setParameter(1, 0);//canBeAdhoc=0 means don't appear in vacancy. + q.setParameter(2, vacancyId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + public List getRefinedCriteriasByTemplateId(Integer templateId) { + Query q = entityManager.createQuery("select c from Criteria c where c.canBeAdhoc!=? and c.templateId=?"); + q.setParameter(1, 0); //canBeAdhoc=0 means don't appear in vacancy. + q.setParameter(2, templateId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDao.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDao.java index 4c2c528259..03359fc888 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,35 +21,25 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import javax.persistence.Query; - -import org.oscarehr.PMmodule.model.CriteriaSelectionOption; -import org.oscarehr.common.dao.AbstractDao; -import org.springframework.stereotype.Repository; - -@Repository -public class CriteriaSelectionOptionDao extends AbstractDao { - - public CriteriaSelectionOptionDao() { - super(CriteriaSelectionOption.class); - } + package org.oscarehr.PMmodule.dao; - public List getCriteriaSelectedOptionsByCriteriaId(Integer criteriaId) { - Query query = entityManager.createQuery("select x from CriteriaSelectionOption x where x.criteriaId=?"); - query.setParameter(1, criteriaId); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } - + import java.util.List; + + import javax.persistence.Query; + + import org.oscarehr.PMmodule.model.CriteriaSelectionOption; + import org.oscarehr.common.dao.AbstractDaoImpl; + import org.oscarehr.common.dao.AbstractDao; + import org.springframework.stereotype.Repository; -} + public interface CriteriaSelectionOptionDao extends AbstractDao { + public List getCriteriaSelectedOptionsByCriteriaId(Integer criteriaId); + + } + + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDaoImpl.java new file mode 100644 index 0000000000..dd8c4f03ab --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaSelectionOptionDaoImpl.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.CriteriaSelectionOption; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class CriteriaSelectionOptionDaoImpl extends AbstractDaoImpl implements CriteriaSelectionOptionDao{ + + public CriteriaSelectionOptionDaoImpl() { + super(CriteriaSelectionOption.class); + } + + public List getCriteriaSelectedOptionsByCriteriaId(Integer criteriaId) { + Query query = entityManager.createQuery("select x from CriteriaSelectionOption x where x.criteriaId=?"); + query.setParameter(1, criteriaId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + +} + diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDao.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDao.java index b206383304..4ba9e810d5 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,64 +21,29 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import javax.persistence.Query; - -import org.oscarehr.PMmodule.model.CriteriaType; -import org.oscarehr.common.dao.AbstractDao; -import org.springframework.stereotype.Repository; - -@Repository -public class CriteriaTypeDao extends AbstractDao { + package org.oscarehr.PMmodule.dao; - public CriteriaTypeDao() { - super(CriteriaType.class); - } - - public List findAll() { - Query query = entityManager.createQuery("select x from CriteriaType x"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } + import java.util.List; + + import javax.persistence.Query; + + import org.oscarehr.PMmodule.model.CriteriaType; + import org.oscarehr.common.dao.AbstractDaoImpl; + import org.oscarehr.common.dao.AbstractDao; + import org.springframework.stereotype.Repository; + + public interface CriteriaTypeDao extends AbstractDao { - public CriteriaType findByName(String fieldName) { - Query query = entityManager.createQuery("select x from CriteriaType x where x.fieldName=?"); - query.setParameter(1, fieldName); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - if(results.size()>0) - return results.get(0); - - return null; - } - - public List getAllCriteriaTypes() { - Query query = entityManager.createQuery("select x from CriteriaType x where x.wlProgramId=? order by x.fieldType DESC"); - query.setParameter(1, 1); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } - - public List getAllCriteriaTypesByWlProgramId(Integer wlProgramId) { - Query query = entityManager.createQuery("select x from CriteriaType x where x.wlProgramId=? order by x.fieldType DESC"); - query.setParameter(1, wlProgramId); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } -} + public List findAll(); + + public CriteriaType findByName(String fieldName); + + public List getAllCriteriaTypes(); + + public List getAllCriteriaTypesByWlProgramId(Integer wlProgramId); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDaoImpl.java new file mode 100644 index 0000000000..ef20f40308 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeDaoImpl.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.CriteriaType; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class CriteriaTypeDaoImpl extends AbstractDaoImpl implements CriteriaTypeDao{ + + public CriteriaTypeDaoImpl() { + super(CriteriaType.class); + } + + public List findAll() { + Query query = entityManager.createQuery("select x from CriteriaType x"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + public CriteriaType findByName(String fieldName) { + Query query = entityManager.createQuery("select x from CriteriaType x where x.fieldName=?"); + query.setParameter(1, fieldName); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + if(results.size()>0) + return results.get(0); + + return null; + } + + public List getAllCriteriaTypes() { + Query query = entityManager.createQuery("select x from CriteriaType x where x.wlProgramId=? order by x.fieldType DESC"); + query.setParameter(1, 1); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + public List getAllCriteriaTypesByWlProgramId(Integer wlProgramId) { + Query query = entityManager.createQuery("select x from CriteriaType x where x.wlProgramId=? order by x.fieldType DESC"); + query.setParameter(1, wlProgramId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDao.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDao.java index fe8692c3d7..ee16ea9aea 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,56 +21,29 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import javax.persistence.Query; - -import org.oscarehr.PMmodule.model.CriteriaTypeOption; -import org.oscarehr.common.dao.AbstractDao; -import org.springframework.stereotype.Repository; - -@Repository -public class CriteriaTypeOptionDao extends AbstractDao { - - public CriteriaTypeOptionDao() { - super(CriteriaTypeOption.class); - } - - public List findAll() { - Query query = entityManager.createQuery("select x from CriteriaTypeOption x"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } - - public List getCriteriaTypeOptionByTypeId(Integer typeId) { - Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.criteriaTypeId=?"); - query.setParameter(1, typeId); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } - - public CriteriaTypeOption getByValue(String optionValue) { - Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.optionValue=?"); - query.setParameter(1, optionValue); - - return this.getSingleResultOrNull(query); - } - - public CriteriaTypeOption getByValueAndTypeId(String optionValue, Integer typeId) { - Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.optionValue=? and x.criteriaTypeId=?"); - query.setParameter(1, optionValue); - query.setParameter(2, typeId); - - return this.getSingleResultOrNull(query); - } -} + package org.oscarehr.PMmodule.dao; + + import java.util.List; + + import javax.persistence.Query; + + import org.oscarehr.PMmodule.model.CriteriaTypeOption; + import org.oscarehr.common.dao.AbstractDaoImpl; + import org.oscarehr.common.dao.AbstractDao; + import org.springframework.stereotype.Repository; + + public interface CriteriaTypeOptionDao extends AbstractDao { + + public List findAll(); + + public List getCriteriaTypeOptionByTypeId(Integer typeId); + + public CriteriaTypeOption getByValue(String optionValue); + + public CriteriaTypeOption getByValueAndTypeId(String optionValue, Integer typeId); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDaoImpl.java new file mode 100644 index 0000000000..6e662d11d7 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/CriteriaTypeOptionDaoImpl.java @@ -0,0 +1,78 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.CriteriaTypeOption; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class CriteriaTypeOptionDaoImpl extends AbstractDaoImpl implements CriteriaTypeOptionDao{ + + public CriteriaTypeOptionDaoImpl() { + super(CriteriaTypeOption.class); + } + + public List findAll() { + Query query = entityManager.createQuery("select x from CriteriaTypeOption x"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + public List getCriteriaTypeOptionByTypeId(Integer typeId) { + Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.criteriaTypeId=?"); + query.setParameter(1, typeId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + public CriteriaTypeOption getByValue(String optionValue) { + Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.optionValue=?"); + query.setParameter(1, optionValue); + + return this.getSingleResultOrNull(query); + } + + public CriteriaTypeOption getByValueAndTypeId(String optionValue, Integer typeId) { + Query query = entityManager.createQuery("select x from CriteriaTypeOption x where x.optionValue=? and x.criteriaTypeId=?"); + query.setParameter(1, optionValue); + query.setParameter(2, typeId); + + return this.getSingleResultOrNull(query); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAO.java index d49b807b26..a37234d711 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,49 +20,29 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import org.oscarehr.PMmodule.model.DefaultRoleAccess; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -@SuppressWarnings("unchecked") -public class DefaultRoleAccessDAO extends HibernateDaoSupport { - - public void deleteDefaultRoleAccess(Long id) { - this.getHibernateTemplate().delete(getDefaultRoleAccess(id)); - } - - public DefaultRoleAccess getDefaultRoleAccess(Long id) { - return this.getHibernateTemplate().get(DefaultRoleAccess.class, id); - } - - public List getDefaultRoleAccesses() { - return this.getHibernateTemplate().find("from DefaultRoleAccess dra ORDER BY role_id"); - } - - public List findAll() { - return this.getHibernateTemplate().find("from DefaultRoleAccess dra"); - } - - public void saveDefaultRoleAccess(DefaultRoleAccess dra) { - this.getHibernateTemplate().saveOrUpdate(dra); - } - - public DefaultRoleAccess find(Long roleId, Long accessTypeId) { - List results = this.getHibernateTemplate().find("from DefaultRoleAccess dra where dra.roleId=? and dra.accessTypeId=?", new Object[] {roleId, accessTypeId}); - - if (!results.isEmpty()) { - return (DefaultRoleAccess)results.get(0); - } - return null; - } - - public List findAllRolesAndAccessTypes(){ - return getHibernateTemplate().find("FROM DefaultRoleAccess a, AccessType b WHERE a.id = b.Id"); - } - -} + package org.oscarehr.PMmodule.dao; + + import java.util.List; + + import org.oscarehr.PMmodule.model.DefaultRoleAccess; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + public interface DefaultRoleAccessDAO{ + + public void deleteDefaultRoleAccess(Long id); + + public DefaultRoleAccess getDefaultRoleAccess(Long id); + + public List getDefaultRoleAccesses(); + public List findAll(); + public void saveDefaultRoleAccess(DefaultRoleAccess dra); + + public DefaultRoleAccess find(Long roleId, Long accessTypeId); + + public List findAllRolesAndAccessTypes(); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAOImpl.java new file mode 100644 index 0000000000..7b9934cd9d --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/DefaultRoleAccessDAOImpl.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import org.oscarehr.PMmodule.model.DefaultRoleAccess; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +@SuppressWarnings("unchecked") +public class DefaultRoleAccessDAOImpl extends HibernateDaoSupport implements DefaultRoleAccessDAO{ + + public void deleteDefaultRoleAccess(Long id) { + this.getHibernateTemplate().delete(getDefaultRoleAccess(id)); + } + + public DefaultRoleAccess getDefaultRoleAccess(Long id) { + return this.getHibernateTemplate().get(DefaultRoleAccess.class, id); + } + + public List getDefaultRoleAccesses() { + return (List) this.getHibernateTemplate().find("from DefaultRoleAccess dra ORDER BY role_id"); + } + + public List findAll() { + return (List) this.getHibernateTemplate().find("from DefaultRoleAccess dra"); + } + + public void saveDefaultRoleAccess(DefaultRoleAccess dra) { + this.getHibernateTemplate().saveOrUpdate(dra); + } + + public DefaultRoleAccess find(Long roleId, Long accessTypeId) { + List results = this.getHibernateTemplate().find("from DefaultRoleAccess dra where dra.roleId=? and dra.accessTypeId=?", new Object[] {roleId, accessTypeId}); + + if (!results.isEmpty()) { + return (DefaultRoleAccess)results.get(0); + } + return null; + } + + public List findAllRolesAndAccessTypes(){ + return (List) getHibernateTemplate().find("FROM DefaultRoleAccess a, AccessType b WHERE a.id = b.Id"); + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/FormsDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/FormsDAO.java index 7364cc3d60..672284ca46 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/FormsDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/FormsDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,85 +20,28 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import org.apache.logging.log4j.Logger; -import org.oscarehr.PMmodule.model.FormInfo; -import org.oscarehr.common.model.Provider; -import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class FormsDAO extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - public void saveForm(Object o) { - this.getHibernateTemplate().save(o); - - if(log.isDebugEnabled()) { - log.debug("saveForm:" + o); - } - } - - public Object getCurrentForm(String clientId, Class clazz) { - Object result = null; - - if(clientId == null || clazz == null) { - throw new IllegalArgumentException(); - } - - String className = clazz.getName(); - if(className.indexOf(".") != -1) { - className = className.substring(className.lastIndexOf(".")+1); - } - List results = this.getHibernateTemplate().find("from " + className + " f where f.DemographicNo=" + clientId); - if(results.size()>0) { - result = results.get(0); - } - - if(log.isDebugEnabled()) { - log.debug("getCurrentForm: clientId=" + clientId + ",class=" + clazz + ",found=" + (result!=null)); - } - - return result; - } - - public List getFormInfo(String clientId,Class clazz) { - if(clientId == null || clazz == null) { - throw new IllegalArgumentException(); - } - - List formInfos = new ArrayList(); - String className = clazz.getName(); - if(className.indexOf(".") != -1) { - className = className.substring(className.lastIndexOf(".")+1); - } - List results = this.getHibernateTemplate().find("select f.id,f.ProviderNo,f.FormEdited from " + className + " f where f.DemographicNo=? order by f.FormEdited DESC",Long.valueOf(clientId)); - for(Iterator iter=results.iterator();iter.hasNext();) { - FormInfo fi = new FormInfo(); - Object[] values = (Object[])iter.next(); - Long id = (Long)values[0]; - Long providerNo = (Long)values[1]; - Date dateEdited = (Date)values[2]; - Provider provider = this.getHibernateTemplate().get(Provider.class,String.valueOf(providerNo)); - fi.setFormId(id); - fi.setProviderNo(providerNo); - fi.setFormDate(dateEdited); - fi.setProviderName(provider.getFormattedName()); - formInfos.add(fi); - } - - if(log.isDebugEnabled()) { - log.debug("getFormInfo: clientId=" + clientId + ",class=" + clazz + ",# of results=" + formInfos.size()); - } - - return formInfos; - } -} + package org.oscarehr.PMmodule.dao; + + import java.util.ArrayList; + import java.util.Date; + import java.util.Iterator; + import java.util.List; + + import org.apache.logging.log4j.Logger; + import org.oscarehr.PMmodule.model.FormInfo; + import org.oscarehr.common.model.Provider; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + public interface FormsDAO{ + + public void saveForm(Object o); + public Object getCurrentForm(String clientId, Class clazz); + + public List getFormInfo(String clientId,Class clazz); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/FormsDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/FormsDAOImpl.java new file mode 100644 index 0000000000..4f6ab3eaab --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/FormsDAOImpl.java @@ -0,0 +1,106 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.FormInfo; +import org.oscarehr.common.model.Provider; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class FormsDAOImpl extends HibernateDaoSupport implements FormsDAO{ + + private Logger log=MiscUtils.getLogger(); + + public void saveForm(Object o) { + this.getHibernateTemplate().save(o); + + if(log.isDebugEnabled()) { + log.debug("saveForm:" + o); + } + } + + public Object getCurrentForm(String clientId, Class clazz) { + Object result = null; + + if(clientId == null || clazz == null) { + throw new IllegalArgumentException(); + } + + String className = clazz.getName(); + if(className.indexOf(".") != -1) { + className = className.substring(className.lastIndexOf(".")+1); + } + List results = this.getHibernateTemplate().find("from " + className + " f where f.DemographicNo=" + clientId); + if(results.size()>0) { + result = results.get(0); + } + + if(log.isDebugEnabled()) { + log.debug("getCurrentForm: clientId=" + clientId + ",class=" + clazz + ",found=" + (result!=null)); + } + + return result; + } + + public List getFormInfo(String clientId,Class clazz) { + if(clientId == null || clazz == null) { + throw new IllegalArgumentException(); + } + + List formInfos = new ArrayList(); + String className = clazz.getName(); + if(className.indexOf(".") != -1) { + className = className.substring(className.lastIndexOf(".")+1); + } + List results = this.getHibernateTemplate().find("select f.id,f.ProviderNo,f.FormEdited from " + className + " f where f.DemographicNo=? order by f.FormEdited DESC",Long.valueOf(clientId)); + for(Iterator iter=results.iterator();iter.hasNext();) { + FormInfo fi = new FormInfo(); + Object[] values = (Object[])iter.next(); + Long id = (Long)values[0]; + Long providerNo = (Long)values[1]; + Date dateEdited = (Date)values[2]; + Provider provider = this.getHibernateTemplate().get(Provider.class,String.valueOf(providerNo)); + fi.setFormId(id); + fi.setProviderNo(providerNo); + fi.setFormDate(dateEdited); + fi.setProviderName(provider.getFormattedName()); + formInfos.add(fi); + } + + if(log.isDebugEnabled()) { + log.debug("getFormInfo: clientId=" + clientId + ",class=" + clazz + ",# of results=" + formInfos.size()); + } + + return formInfos; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAO.java index deef0171d1..4f23a721e0 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.dao; import java.sql.Connection; @@ -51,427 +53,48 @@ import org.oscarehr.util.AccumulatorMap; import org.oscarehr.util.DbConnectionFilter; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; import oscar.util.SqlUtils; +public interface GenericIntakeDAO { -/** - * Hibernate implementation of GenericIntakeDAO interface - */ -public class GenericIntakeDAO extends HibernateDaoSupport { - - private static final Logger LOG = MiscUtils.getLogger(); - - @SuppressWarnings("unchecked") - public List getOcanIntakesAfterDate(Calendar after) { - return getHibernateTemplate().find("from Intake i, IntakeNode n, IntakeNodeLabel l where " + - "i.createdOn > ? and i.node.id = n.id and n.label.id = l.id and " + - "(l.label like '%OCAN Staff Assessment%' or l.label like '%OCAN Client Self Assessment%') order by i.createdOn desc", - new Object[] { after }); - } - - public Intake getLatestIntakeByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { - if (node == null || clientId == null) { - throw new IllegalArgumentException("Parameters node and clientId must be non-null"); - } - - List intakes = getIntakesByFacility(node, clientId, programId, facilityId); - Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; - LOG.info("get latest intake: " + intake); - - return intake; - } - - public Intake getLatestIntake(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { - if (node == null || clientId == null) { - throw new IllegalArgumentException("Parameters node and clientId must be non-null"); - } - - List intakes = getIntakes(node, clientId, programId, facilityId); - Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; - LOG.info("get latest intake: " + intake); - - return intake; - } - - @SuppressWarnings("unchecked") - public List getIntakeClientsByFacilityId(Integer facilityId) { - if(facilityId == null) { - throw new IllegalArgumentException("Parameter facilityId must be non-null"); - } - - List clientIds = getHibernateTemplate().find("select distinct i.clientId from Intake i where i.facilityId = ? order by i.clientId", - new Object[] { facilityId }); - - return clientIds; - } - - @SuppressWarnings("unchecked") - public List getIntakeFacilityIds() { - List facilityIds = getHibernateTemplate().find("select distinct i.facilityId from Intake i "); - - return facilityIds; - } - - public List getIntakes(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { - if (node == null || clientId == null) { - throw new IllegalArgumentException("Parameters node and clientId must be non-null"); - } - - List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", - new Object[] { node, clientId, facilityId }); - List intakes = convertToIntakes(results, programId); - - LOG.info("get intakes: " + intakes.size()); - - return intakes; - } - - /* - * 1. get nodes. - * foreach node, get intakes for that node - */ - public List getIntakesByType(Integer formType, Integer clientId, Integer programId, Integer facilityId) { - List intake_results = new ArrayList(); - if (formType == null || clientId == null) { - throw new IllegalArgumentException("Parameters node and clientId must be non-null"); - } - - List nodes = this.getIntakeNodesByType(formType); - - for(IntakeNode node:nodes) { - List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", - new Object[] { node, clientId, facilityId }); - List intakes = convertToIntakes(results, programId); - intake_results.addAll(intakes); - } - - - return intake_results; - } - - public List getIntakesByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { - if (node == null || clientId == null) { - throw new IllegalArgumentException("Parameters node and clientId must be non-null"); - } - - List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and i.facilityId =? order by i.createdOn desc", - new Object[] { node, clientId, facilityId }); - List intakes = convertToIntakes(results, programId); - - LOG.info("get intakes: " + intakes.size()); - - return intakes; - } - - public List getRegIntakes(List nodes, Integer clientId, Integer programId, Integer facilityId) { - if (nodes.isEmpty() || clientId == null) { - throw new IllegalArgumentException("Parameters nodes and clientId must be non-null"); - } - - List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", - new Object[] { nodes.get(0), clientId, facilityId }); - List intakes = convertToIntakes(results, programId); - - for (int i=1; i results = getHibernateTemplate().find("from Intake i where i.node = ? and i.id = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", - new Object[] { node, intakeId, facilityId }); - List intakes = convertToIntakes(results, programId); - LOG.info("get intakes: " + intakes.size()); - Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; - - return intake; - } - - public Integer getIntakeNodeIdByIntakeId(Integer intakeId) { - if (intakeId == null) { - throw new IllegalArgumentException("Parameters intakeId must be non-null"); - } - - List results = getHibernateTemplate().find("from Intake i where i.id = ? order by i.createdOn desc", - new Object[] { intakeId }); - List intakes = convertToIntakes(results, null); - LOG.info("get intakes: " + intakes.size()); - Integer intakeNodeId = !intakes.isEmpty() ? intakes.get(0).getNode().getId() : null; - - return intakeNodeId; - } - - public List getIntakeNodesIdByClientId(Integer clientId) { - return getIntakeNodesIdByClientId(clientId,null); - } - - public List getIntakeNodesIdByClientId(Integer clientId, Integer formType) { - if (clientId == null) { - throw new IllegalArgumentException("Parameters intakeId must be non-null"); - } - - List results = getHibernateTemplate().find("from Intake i where i.clientId = ? order by i.createdOn desc", - new Object[] { clientId }); - List intakes = convertToIntakes(results, null); - LOG.info("get intakes: " + intakes.size()); - - List intakeNodeIds = new ArrayList(); - for (Intake i : intakes) { - if(formType != null && i.getNode().getFormType() == formType) { - intakeNodeIds.add(i.getNode().getId()); - } - } - for (int i=1; i getIntakeIds2(Integer nodeId, Date startDate, Date endDate) throws SQLException { - if (nodeId == null || startDate == null || endDate == null) { - throw new IllegalArgumentException("Parameters nodeId, startDate and endDate must be non-null"); - } - - Connection c = DbConnectionFilter.getThreadLocalDbConnection(); - ArrayList results = new ArrayList(); - try { - PreparedStatement ps = c.prepareStatement("select intake_id from intake where intake_node_id=? and creation_date>? and creation_date getLatestIntakeIds(Integer nodeId, Date startDate, Date endDate) { - if (nodeId == null || startDate == null || endDate == null) { - throw new IllegalArgumentException("Parameters node, startDate and endDate must be non-null"); - } - - // endDate is "YYYY-MM-DD 00:00:00", it has to be "YYYY-MM-DD 23:59:59" - Calendar endCal = new GregorianCalendar(); - endCal.setTime(endDate); - endCal.add(Calendar.DAY_OF_YEAR, 1); - - Calendar startCal = new GregorianCalendar(); - startCal.setTime(startDate); - - // wrong, only got the oldest first record: List results = getHibernateTemplate().find("select i.id, max(i.createdOn) from Intake i where i.node.id = - // ? and i.createdOn between ? and ? group by i.clientId", new Object[] { nodeId, startDate, endDate }); - //List results = getHibernateTemplate() - // .find( - // "select i.id, max(i.createdOn) from Intake i where i.node.id = ? and i.createdOn between ? and ? and i.createdOn = (select max(ii.createdOn) from Intake ii where ii.clientId = i.clientId) group by i.clientId", - // new Object[] { nodeId, startCal.getTime(), endCal.getTime() }); - - List results = getHibernateTemplate() - .find( - "select i.id, i.createdOn from Intake i where i.node.id = ? and i.createdOn between ? and ? and i.createdOn = (select max(ii.createdOn) from Intake ii where ii.clientId = i.clientId group by ii.clientId)", - new Object[] { nodeId, startCal, endCal }); - - - SortedSet intakeIds = convertToIntegers(results); - - LOG.info("get latest intake ids: " + intakeIds.size()); - - return intakeIds; - } - - public SortedMap> getReportStatistics(Hashtable answerIds, Set intakeIds) { - if (intakeIds == null || answerIds == null) { - throw new IllegalArgumentException("Parameters intakeIds, answerIds must be non-null"); - } - - SortedMap> reportStatistics = new TreeMap>(); - - if (!intakeIds.isEmpty() && !answerIds.isEmpty()) { - List results = getHibernateTemplate().find( - "select ia.node.id, ia.value, count(ia.value) from IntakeAnswer ia where ia.node.id in (" + convertToString(answerIds.keySet()) - + ") and ia.intake.id in (" + convertToString(intakeIds) + ") group by ia.node.id, ia.value"); - convertToReportStatistics(results, intakeIds.size(), reportStatistics, answerIds); - } - LOG.info("get reportStatistics: " + reportStatistics.size()); - - return reportStatistics; - } - - /** - * This method will populate the totalIntakeCount and - */ - public GenericIntakeReportStatistics getReportStatistics2(List intakeIds, Set answerIds) throws SQLException { - - // this is a brute for simple algorithm, if the data set gets large we can group these into - // smaller groups like doing 10 results at a time or something, we can't do all results - // at the same time because the in clause doesn't have a dynamic length prepared statement - // parameter and we can't put ?,?,? ... for each item because there's a maximum query string - // length so we should limit it to at most blocks of 100's if we do that. - - GenericIntakeReportStatistics genericIntakeReportStatistics=new GenericIntakeReportStatistics(); - genericIntakeReportStatistics.totalIntakeCount = intakeIds.size(); - Object[] answerIdArray=answerIds.toArray(); - - for (Integer intakeId : intakeIds) { - Connection c = DbConnectionFilter.getThreadLocalDbConnection(); - try { - PreparedStatement ps = c.prepareStatement("select intake_node_id,val from intake_answer where intake_id=? and intake_answer_id in "+SqlUtils.constructInClauseForStatements(answerIdArray)); - ps.setInt(1, intakeId); - ResultSet rs = ps.executeQuery(); - if (rs.next()) { - genericIntakeReportStatistics.addResult(rs.getInt("intake_node_id"), oscar.Misc.getString(rs,"val")); - } - else { - LOG.error("Error, an intake has no answers? intakeId=" + intakeId); - } - } - finally { - c.close(); - } - } - - return(genericIntakeReportStatistics); - } - - public static class GenericIntakeReportStatistics { - public int totalIntakeCount = 0; - /** - * This is a map of > - */ - public HashMap> intakeNodeResults = new HashMap>(); - - public void addResult(int intakeNodeId, String answer) { - AccumulatorMap accumulatorMap = intakeNodeResults.get(intakeNodeId); - - if (accumulatorMap == null) { - accumulatorMap = new AccumulatorMap(); - intakeNodeResults.put(intakeNodeId, accumulatorMap); - } - - accumulatorMap.increment(answer); - } - } - - // Private - - private List convertToIntakes(List results, Integer programId) { - List intakes = new ArrayList(); - - if (results != null) { - for (Object o : results) { - Intake intake = (Intake) o; - - Demographic client = getHibernateTemplate().get(Demographic.class, intake.getClientId()); - intake.setClient(client); + List getOcanIntakesAfterDate(Calendar after); - Provider staff = getHibernateTemplate().get(Provider.class, intake.getStaffId()); - intake.setStaff(staff); + Intake getLatestIntakeByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId); - intake.setProgramId(programId); + Intake getLatestIntake(IntakeNode node, Integer clientId, Integer programId, Integer facilityId); - intakes.add(intake); - } - } + List getIntakeClientsByFacilityId(Integer facilityId); - return intakes; - } + List getIntakeFacilityIds(); - private SortedSet convertToIntegers(List results) { - SortedSet intakeIds = new TreeSet(); + List getIntakes(IntakeNode node, Integer clientId, Integer programId, Integer facilityId); - if (results != null) { - for (Object o : results) { - Object[] tuple = (Object[]) o; - Integer intakeId = (Integer) tuple[0]; + List getIntakesByType(Integer formType, Integer clientId, Integer programId, Integer facilityId); - intakeIds.add(intakeId); - } - } + List getIntakesByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId); - return intakeIds; - } + List getRegIntakes(List nodes, Integer clientId, Integer programId, Integer facilityId); - private String convertToString(Set ids) { - StringBuilder builder = new StringBuilder(); + Intake getIntakeById(IntakeNode node, Integer intakeId, Integer programId, Integer facilityId); - for (Iterator i = ids.iterator(); i.hasNext();) { - builder.append(i.next()); + Integer getIntakeNodeIdByIntakeId(Integer intakeId); - if (i.hasNext()) { - builder.append(","); - } - } + List getIntakeNodesIdByClientId(Integer clientId); - return builder.toString(); - } + List getIntakeNodesIdByClientId(Integer clientId, Integer formType); - private void convertToReportStatistics(List results, int size, SortedMap> reportStatistics, Hashtable resultHash) { - for (Object o : results) { - Object[] tuple = (Object[]) o; + Integer saveIntake(Intake intake); - Integer nodeId = (Integer) tuple[0]; - String value = (String) tuple[1]; - Integer count = Integer.valueOf(tuple[2].toString()); + void saveUpdateIntake(Intake intake); - if (!reportStatistics.containsKey(nodeId)) { - reportStatistics.put(nodeId, new TreeMap()); - } + List getIntakeIds2(Integer nodeId, Date startDate, Date endDate) throws SQLException; - SortedMap rpStNodeId = reportStatistics.get(nodeId); - if (rpStNodeId.containsKey(value)) { - count += rpStNodeId.get(value).getCount(); - rpStNodeId.remove(value); - } - rpStNodeId.put(value, new ReportStatistic(count, size)); - } - } + SortedSet getLatestIntakeIds(Integer nodeId, Date startDate, Date endDate); + SortedMap> getReportStatistics(Hashtable answerIds, Set intakeIds); + //GenericIntakeReportStatistics getReportStatistics2(List intakeIds, Set answerIds) throws SQLException; - public List getIntakeNodesByType(Integer formType) { - return this.getHibernateTemplate().find("From IntakeNode n where n.formType = ? and n.publish_by is not null", new Object[] {formType}); - } + List getIntakeNodesByType(Integer formType); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAOImpl.java new file mode 100644 index 0000000000..159d76c253 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeDAOImpl.java @@ -0,0 +1,480 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.Intake; +import org.oscarehr.PMmodule.model.IntakeNode; +import org.oscarehr.common.model.Demographic; +import org.oscarehr.common.model.Provider; +import org.oscarehr.common.model.ReportStatistic; +import org.oscarehr.util.AccumulatorMap; +import org.oscarehr.util.DbConnectionFilter; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +import oscar.util.SqlUtils; + +/** + * Hibernate implementation of GenericIntakeDAO interface + */ +public class GenericIntakeDAOImpl extends HibernateDaoSupport implements GenericIntakeDAO{ + + private static final Logger LOG = MiscUtils.getLogger(); + + @SuppressWarnings("unchecked") + public List getOcanIntakesAfterDate(Calendar after) { + return (List) getHibernateTemplate().find("from Intake i, IntakeNode n, IntakeNodeLabel l where " + + "i.createdOn > ? and i.node.id = n.id and n.label.id = l.id and " + + "(l.label like '%OCAN Staff Assessment%' or l.label like '%OCAN Client Self Assessment%') order by i.createdOn desc", + new Object[] { after }); + } + + public Intake getLatestIntakeByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { + if (node == null || clientId == null) { + throw new IllegalArgumentException("Parameters node and clientId must be non-null"); + } + + List intakes = getIntakesByFacility(node, clientId, programId, facilityId); + Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; + LOG.info("get latest intake: " + intake); + + return intake; + } + + public Intake getLatestIntake(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { + if (node == null || clientId == null) { + throw new IllegalArgumentException("Parameters node and clientId must be non-null"); + } + + List intakes = getIntakes(node, clientId, programId, facilityId); + Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; + LOG.info("get latest intake: " + intake); + + return intake; + } + + @SuppressWarnings("unchecked") + public List getIntakeClientsByFacilityId(Integer facilityId) { + if(facilityId == null) { + throw new IllegalArgumentException("Parameter facilityId must be non-null"); + } + + List clientIds = (List) getHibernateTemplate().find("select distinct i.clientId from Intake i where i.facilityId = ? order by i.clientId", + new Object[] { facilityId }); + + return clientIds; + } + + @SuppressWarnings("unchecked") + public List getIntakeFacilityIds() { + List facilityIds = (List) getHibernateTemplate().find("select distinct i.facilityId from Intake i "); + + return facilityIds; + } + + public List getIntakes(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { + if (node == null || clientId == null) { + throw new IllegalArgumentException("Parameters node and clientId must be non-null"); + } + + List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", + new Object[] { node, clientId, facilityId }); + List intakes = convertToIntakes(results, programId); + + LOG.info("get intakes: " + intakes.size()); + + return intakes; + } + + /* + * 1. get nodes. + * foreach node, get intakes for that node + */ + public List getIntakesByType(Integer formType, Integer clientId, Integer programId, Integer facilityId) { + List intake_results = new ArrayList(); + if (formType == null || clientId == null) { + throw new IllegalArgumentException("Parameters node and clientId must be non-null"); + } + + List nodes = this.getIntakeNodesByType(formType); + + for(IntakeNode node:nodes) { + List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", + new Object[] { node, clientId, facilityId }); + List intakes = convertToIntakes(results, programId); + intake_results.addAll(intakes); + } + + + return intake_results; + } + + public List getIntakesByFacility(IntakeNode node, Integer clientId, Integer programId, Integer facilityId) { + if (node == null || clientId == null) { + throw new IllegalArgumentException("Parameters node and clientId must be non-null"); + } + + List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and i.facilityId =? order by i.createdOn desc", + new Object[] { node, clientId, facilityId }); + List intakes = convertToIntakes(results, programId); + + LOG.info("get intakes: " + intakes.size()); + + return intakes; + } + + public List getRegIntakes(List nodes, Integer clientId, Integer programId, Integer facilityId) { + if (nodes.isEmpty() || clientId == null) { + throw new IllegalArgumentException("Parameters nodes and clientId must be non-null"); + } + + List results = getHibernateTemplate().find("from Intake i where i.node = ? and i.clientId = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", + new Object[] { nodes.get(0), clientId, facilityId }); + List intakes = convertToIntakes(results, programId); + + for (int i=1; i results = getHibernateTemplate().find("from Intake i where i.node = ? and i.id = ? and (i.facilityId=? or i.facilityId is null) order by i.createdOn desc", + new Object[] { node, intakeId, facilityId }); + List intakes = convertToIntakes(results, programId); + LOG.info("get intakes: " + intakes.size()); + Intake intake = !intakes.isEmpty() ? intakes.get(0) : null; + + return intake; + } + + public Integer getIntakeNodeIdByIntakeId(Integer intakeId) { + if (intakeId == null) { + throw new IllegalArgumentException("Parameters intakeId must be non-null"); + } + + List results = getHibernateTemplate().find("from Intake i where i.id = ? order by i.createdOn desc", + new Object[] { intakeId }); + List intakes = convertToIntakes(results, null); + LOG.info("get intakes: " + intakes.size()); + Integer intakeNodeId = !intakes.isEmpty() ? intakes.get(0).getNode().getId() : null; + + return intakeNodeId; + } + + public List getIntakeNodesIdByClientId(Integer clientId) { + return getIntakeNodesIdByClientId(clientId,null); + } + + public List getIntakeNodesIdByClientId(Integer clientId, Integer formType) { + if (clientId == null) { + throw new IllegalArgumentException("Parameters intakeId must be non-null"); + } + + List results = getHibernateTemplate().find("from Intake i where i.clientId = ? order by i.createdOn desc", + new Object[] { clientId }); + List intakes = convertToIntakes(results, null); + LOG.info("get intakes: " + intakes.size()); + + List intakeNodeIds = new ArrayList(); + for (Intake i : intakes) { + if(formType != null && i.getNode().getFormType() == formType) { + intakeNodeIds.add(i.getNode().getId()); + } + } + for (int i=1; i getIntakeIds2(Integer nodeId, Date startDate, Date endDate) throws SQLException { + if (nodeId == null || startDate == null || endDate == null) { + throw new IllegalArgumentException("Parameters nodeId, startDate and endDate must be non-null"); + } + + Connection c = DbConnectionFilter.getThreadLocalDbConnection(); + ArrayList results = new ArrayList(); + try { + PreparedStatement ps = c.prepareStatement("select intake_id from intake where intake_node_id=? and creation_date>? and creation_date getLatestIntakeIds(Integer nodeId, Date startDate, Date endDate) { + if (nodeId == null || startDate == null || endDate == null) { + throw new IllegalArgumentException("Parameters node, startDate and endDate must be non-null"); + } + + // endDate is "YYYY-MM-DD 00:00:00", it has to be "YYYY-MM-DD 23:59:59" + Calendar endCal = new GregorianCalendar(); + endCal.setTime(endDate); + endCal.add(Calendar.DAY_OF_YEAR, 1); + + Calendar startCal = new GregorianCalendar(); + startCal.setTime(startDate); + + // wrong, only got the oldest first record: List results = getHibernateTemplate().find("select i.id, max(i.createdOn) from Intake i where i.node.id = + // ? and i.createdOn between ? and ? group by i.clientId", new Object[] { nodeId, startDate, endDate }); + //List results = getHibernateTemplate() + // .find( + // "select i.id, max(i.createdOn) from Intake i where i.node.id = ? and i.createdOn between ? and ? and i.createdOn = (select max(ii.createdOn) from Intake ii where ii.clientId = i.clientId) group by i.clientId", + // new Object[] { nodeId, startCal.getTime(), endCal.getTime() }); + + List results = getHibernateTemplate() + .find( + "select i.id, i.createdOn from Intake i where i.node.id = ? and i.createdOn between ? and ? and i.createdOn = (select max(ii.createdOn) from Intake ii where ii.clientId = i.clientId group by ii.clientId)", + new Object[] { nodeId, startCal, endCal }); + + + SortedSet intakeIds = convertToIntegers(results); + + LOG.info("get latest intake ids: " + intakeIds.size()); + + return intakeIds; + } + + public SortedMap> getReportStatistics(Hashtable answerIds, Set intakeIds) { + if (intakeIds == null || answerIds == null) { + throw new IllegalArgumentException("Parameters intakeIds, answerIds must be non-null"); + } + + SortedMap> reportStatistics = new TreeMap>(); + + if (!intakeIds.isEmpty() && !answerIds.isEmpty()) { + List results = getHibernateTemplate().find( + "select ia.node.id, ia.value, count(ia.value) from IntakeAnswer ia where ia.node.id in (" + convertToString(answerIds.keySet()) + + ") and ia.intake.id in (" + convertToString(intakeIds) + ") group by ia.node.id, ia.value"); + convertToReportStatistics(results, intakeIds.size(), reportStatistics, answerIds); + } + LOG.info("get reportStatistics: " + reportStatistics.size()); + + return reportStatistics; + } + + /** + * This method will populate the totalIntakeCount and + */ + public GenericIntakeReportStatistics getReportStatistics2(List intakeIds, Set answerIds) throws SQLException { + + // this is a brute for simple algorithm, if the data set gets large we can group these into + // smaller groups like doing 10 results at a time or something, we can't do all results + // at the same time because the in clause doesn't have a dynamic length prepared statement + // parameter and we can't put ?,?,? ... for each item because there's a maximum query string + // length so we should limit it to at most blocks of 100's if we do that. + + GenericIntakeReportStatistics genericIntakeReportStatistics=new GenericIntakeReportStatistics(); + genericIntakeReportStatistics.totalIntakeCount = intakeIds.size(); + Object[] answerIdArray=answerIds.toArray(); + + for (Integer intakeId : intakeIds) { + Connection c = DbConnectionFilter.getThreadLocalDbConnection(); + try { + PreparedStatement ps = c.prepareStatement("select intake_node_id,val from intake_answer where intake_id=? and intake_answer_id in "+SqlUtils.constructInClauseForStatements(answerIdArray)); + ps.setInt(1, intakeId); + ResultSet rs = ps.executeQuery(); + if (rs.next()) { + genericIntakeReportStatistics.addResult(rs.getInt("intake_node_id"), oscar.Misc.getString(rs,"val")); + } + else { + LOG.error("Error, an intake has no answers? intakeId=" + intakeId); + } + } + finally { + c.close(); + } + } + + return(genericIntakeReportStatistics); + } + + public static class GenericIntakeReportStatistics { + public int totalIntakeCount = 0; + /** + * This is a map of > + */ + public HashMap> intakeNodeResults = new HashMap>(); + + public void addResult(int intakeNodeId, String answer) { + AccumulatorMap accumulatorMap = intakeNodeResults.get(intakeNodeId); + + if (accumulatorMap == null) { + accumulatorMap = new AccumulatorMap(); + intakeNodeResults.put(intakeNodeId, accumulatorMap); + } + + accumulatorMap.increment(answer); + } + } + + // Private + + private List convertToIntakes(List results, Integer programId) { + List intakes = new ArrayList(); + + if (results != null) { + for (Object o : results) { + Intake intake = (Intake) o; + + Demographic client = getHibernateTemplate().get(Demographic.class, intake.getClientId()); + intake.setClient(client); + + Provider staff = getHibernateTemplate().get(Provider.class, intake.getStaffId()); + intake.setStaff(staff); + + intake.setProgramId(programId); + + intakes.add(intake); + } + } + + return intakes; + } + + private SortedSet convertToIntegers(List results) { + SortedSet intakeIds = new TreeSet(); + + if (results != null) { + for (Object o : results) { + Object[] tuple = (Object[]) o; + Integer intakeId = (Integer) tuple[0]; + + intakeIds.add(intakeId); + } + } + + return intakeIds; + } + + private String convertToString(Set ids) { + StringBuilder builder = new StringBuilder(); + + for (Iterator i = ids.iterator(); i.hasNext();) { + builder.append(i.next()); + + if (i.hasNext()) { + builder.append(","); + } + } + + return builder.toString(); + } + + private void convertToReportStatistics(List results, int size, SortedMap> reportStatistics, Hashtable resultHash) { + for (Object o : results) { + Object[] tuple = (Object[]) o; + + Integer nodeId = (Integer) tuple[0]; + String value = (String) tuple[1]; + Integer count = Integer.valueOf(tuple[2].toString()); + + if (!reportStatistics.containsKey(nodeId)) { + reportStatistics.put(nodeId, new TreeMap()); + } + + SortedMap rpStNodeId = reportStatistics.get(nodeId); + if (rpStNodeId.containsKey(value)) { + count += rpStNodeId.get(value).getCount(); + rpStNodeId.remove(value); + } + rpStNodeId.put(value, new ReportStatistic(count, size)); + } + } + + + + public List getIntakeNodesByType(Integer formType) { + return (List) this.getHibernateTemplate().find("From IntakeNode n where n.formType = ? and n.publish_by is not null", new Object[] {formType}); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAO.java index 5f8a62ddde..a7c609104c 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,244 +20,76 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.logging.log4j.Logger; -import org.hibernate.ObjectNotFoundException; -import org.oscarehr.PMmodule.model.Agency; -import org.oscarehr.PMmodule.model.IntakeAnswerElement; -import org.oscarehr.PMmodule.model.IntakeNode; -import org.oscarehr.PMmodule.model.IntakeNodeJavascript; -import org.oscarehr.PMmodule.model.IntakeNodeLabel; -import org.oscarehr.PMmodule.model.IntakeNodeTemplate; -import org.oscarehr.util.DbConnectionFilter; -import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -/** - * Hibernate implementation of GenericIntakeNodeDAO interface - */ -public class GenericIntakeNodeDAO extends HibernateDaoSupport { - - private static final Logger LOG = MiscUtils.getLogger(); - - /** - * @see org.oscarehr.PMmodule.dao.GenericIntakeNodeDAO#getIntakeNode(java.lang.Integer) - */ - public IntakeNode getIntakeNode(Integer intakeNodeId) { - if (intakeNodeId == null || intakeNodeId < 1) { - throw new IllegalArgumentException( - "intakeNodeId must be non-null and greater than 0"); - } - - IntakeNode intakeNode = getHibernateTemplate().load( - IntakeNode.class, intakeNodeId); - getChildren(intakeNode); - - LOG.info("getIntakeNode : " + intakeNodeId); - - return intakeNode; - } - - /** - *Returns a list of Intake Nodes of type "intake". - */ - public List getIntakeNodes() { - // List l = - // getHibernateTemplate().find("from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.intake_node_type_id = iTemplate.intake_node_type_id and i.intake_node_template_id = iTemplate.intake_node_template_id"); - List l = getHibernateTemplate() - .find( - "select i from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.id = iTemplate.type and i.nodeTemplate = iTemplate.id"); - - // from IntakeNode i where i.type = 'intake'"); - return l; - } - - /** - *Returns a list of Intake Nodes of type "intake". - */ - public List getPublishedIntakeNodesByName(String name) { - // List l = - // getHibernateTemplate().find("from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.intake_node_type_id = iTemplate.intake_node_type_id and i.intake_node_template_id = iTemplate.intake_node_template_id"); - List l = getHibernateTemplate() - .find( - "select i from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate, IntakeNodeLabel iLabel where iType.type = 'intake' and iType.id = iTemplate.type and i.nodeTemplate = iTemplate.id and i.label = iLabel.id and i.publish_date != null and iLabel.label = ? order by i.form_version desc", - new Object[] { name }); - - // from IntakeNode i where i.type = 'intake'"); - return l; - } - - public List getIntakeNodeByEqToId(Integer iNodeEqToId) - throws SQLException { - if (iNodeEqToId == null) { - throw new IllegalArgumentException( - "Parameters iNodeEqToId must be non-null"); - } - - List nwIntakeNodes = new ArrayList(); - Set iNodeIds = getIntakeNodeIdByEqToId(iNodeEqToId); - for (Integer id : iNodeIds) { - nwIntakeNodes.add(getIntakeNode(id)); - } - return nwIntakeNodes; - } - - public Set getIntakeNodeIdByEqToId(Integer iNodeEqToId) - throws SQLException { - if (iNodeEqToId == null) { - throw new IllegalArgumentException( - "Parameters intakdNodeId must be non-null"); - } - Connection c = DbConnectionFilter.getThreadLocalDbConnection(); - Set results = new TreeSet(); - try { - PreparedStatement ps = c - .prepareStatement("select intake_node_id from intake_node where eq_to_id=?"); - ps.setInt(1, iNodeEqToId); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - results.add(rs.getInt(1)); - } - } finally { - c.close(); - } - return results; - } - - public Set getEqToIdByIntakeNodeId(Integer intakeNodeId) - throws SQLException { - if (intakeNodeId == null) { - throw new IllegalArgumentException( - "Parameters intakdNodeId must be non-null"); - } - Connection c = DbConnectionFilter.getThreadLocalDbConnection(); - Set results = new TreeSet(); - try { - PreparedStatement ps = c - .prepareStatement("select eq_to_id from intake_node where intake_node_id=?"); - ps.setInt(1, intakeNodeId); - ResultSet rs = ps.executeQuery(); - while (rs.next()) { - results.add(rs.getInt(1)); - } - } finally { - c.close(); - } - return results; - } - - public List getIntakeNodeByEqToId(Set iNodes) - { - if (iNodes == null) { - throw new IllegalArgumentException( - "Parameters iNodes must be non-null"); - } - - List nwIntakeNodes = new ArrayList(); - for (IntakeNode iN : iNodes) { - nwIntakeNodes.add(getIntakeNode(iN.getEq_to_id())); - } - return nwIntakeNodes; - } - - public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel) { - getHibernateTemplate().save(intakeNodeLabel); - } - - public void updateIntakeNode(IntakeNode intakeNode) { - getHibernateTemplate().update(intakeNode); - } - - public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel) { - getHibernateTemplate().update(intakeNodeLabel); - } - - public void updateAgencyIntakeQuick(Agency agency) { - getHibernateTemplate().update(agency); - } - - public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId) { - IntakeNodeLabel intakeNodeLabel = null; - if (intakeNodeLabelId == null || intakeNodeLabelId < 1) { - throw new IllegalArgumentException( - "intakeNodeLabelId must be non-null and greater than 0"); - } - //in case the node with intakenodelabel id doesn't exist - try { - intakeNodeLabel = getHibernateTemplate().get( - IntakeNodeLabel.class, intakeNodeLabelId); - } catch (ObjectNotFoundException onfe) { - LOG.warn("no node found for : " + intakeNodeLabelId); - } - return intakeNodeLabel; - } - - public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId) { - if (intakeNodeTemplateId == null || intakeNodeTemplateId < 1) { - throw new IllegalArgumentException( - "intakeNodeTemplateId must be non-null and greater than 0"); - } - IntakeNodeTemplate intakeNodeTemplate = getHibernateTemplate() - .get(IntakeNodeTemplate.class, intakeNodeTemplateId); - return intakeNodeTemplate; - } - - public void saveIntakeNode(IntakeNode intakeNode) { - getHibernateTemplate().save(intakeNode); - } - - public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate) { - getHibernateTemplate().save(intakeNodeTemplate); - } - - public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement) { - getHibernateTemplate().save(intakeAnswerElement); - } - - private void getChildren(IntakeNode intakeNode) { - HashSet nodeIds = new HashSet(); - nodeIds.add(intakeNode.getId()); - - getChildren(nodeIds, intakeNode.getChildren()); - } - - private void getChildren(Set nodeIds, List children) { - for (IntakeNode child : children) { - if (child == null) - continue; - Integer childId = child.getId(); - - if (nodeIds.contains(childId)) { - throw new IllegalStateException("intake node with id : " - + childId + " is an ancestor of itself"); - } else { - nodeIds.add(childId); - } - - // load children - getChildren(nodeIds, child.getChildren()); - } - } - - public void deleteIntakeNode(IntakeNode intakeNode) { - getHibernateTemplate().delete(intakeNode); - } - - public List getIntakeNodeJavascriptLocation(String questionId) { - List js = getHibernateTemplate().find("FROM IntakeNodeJavascript j where j.questionId=?",questionId); - return js; - } -} + package org.oscarehr.PMmodule.dao; + + import java.sql.Connection; + import java.sql.PreparedStatement; + import java.sql.ResultSet; + import java.sql.SQLException; + import java.util.ArrayList; + import java.util.HashSet; + import java.util.List; + import java.util.Set; + import java.util.TreeSet; + + import org.apache.logging.log4j.Logger; + import org.hibernate.ObjectNotFoundException; + import org.oscarehr.PMmodule.model.Agency; + import org.oscarehr.PMmodule.model.IntakeAnswerElement; + import org.oscarehr.PMmodule.model.IntakeNode; + import org.oscarehr.PMmodule.model.IntakeNodeJavascript; + import org.oscarehr.PMmodule.model.IntakeNodeLabel; + import org.oscarehr.PMmodule.model.IntakeNodeTemplate; + import org.oscarehr.util.DbConnectionFilter; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + /** + * Hibernate implementation of GenericIntakeNodeDAO interface + */ + public interface GenericIntakeNodeDAO{ + + public IntakeNode getIntakeNode(Integer intakeNodeId); + + /** + *Returns a list of Intake Nodes of type "intake". + */ + public List getIntakeNodes(); + /** + *Returns a list of Intake Nodes of type "intake". + */ + public List getPublishedIntakeNodesByName(String name); + + public List getIntakeNodeByEqToId(Integer iNodeEqToId) throws SQLException;; + + public Set getIntakeNodeIdByEqToId(Integer iNodeEqToId) throws SQLException;; + + public Set getEqToIdByIntakeNodeId(Integer intakeNodeId) throws SQLException;; + + public List getIntakeNodeByEqToId(Set iNodes); + + public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel); + + public void updateIntakeNode(IntakeNode intakeNode); + + public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel); + + public void updateAgencyIntakeQuick(Agency agency); + + public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId); + public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId); + + public void saveIntakeNode(IntakeNode intakeNode); + + public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate); + public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement); + + public void deleteIntakeNode(IntakeNode intakeNode); + + public List getIntakeNodeJavascriptLocation(String questionId); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAOImpl.java new file mode 100644 index 0000000000..a36c97fa59 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/GenericIntakeNodeDAOImpl.java @@ -0,0 +1,265 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.logging.log4j.Logger; +import org.hibernate.ObjectNotFoundException; +import org.oscarehr.PMmodule.model.Agency; +import org.oscarehr.PMmodule.model.IntakeAnswerElement; +import org.oscarehr.PMmodule.model.IntakeNode; +import org.oscarehr.PMmodule.model.IntakeNodeJavascript; +import org.oscarehr.PMmodule.model.IntakeNodeLabel; +import org.oscarehr.PMmodule.model.IntakeNodeTemplate; +import org.oscarehr.util.DbConnectionFilter; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +/** + * Hibernate implementation of GenericIntakeNodeDAO interface + */ +public class GenericIntakeNodeDAOImpl extends HibernateDaoSupport implements GenericIntakeNodeDAO{ + + private static final Logger LOG = MiscUtils.getLogger(); + + /** + * @see org.oscarehr.PMmodule.dao.GenericIntakeNodeDAO#getIntakeNode(java.lang.Integer) + */ + public IntakeNode getIntakeNode(Integer intakeNodeId) { + if (intakeNodeId == null || intakeNodeId < 1) { + throw new IllegalArgumentException( + "intakeNodeId must be non-null and greater than 0"); + } + + IntakeNode intakeNode = getHibernateTemplate().load( + IntakeNode.class, intakeNodeId); + getChildren(intakeNode); + + LOG.info("getIntakeNode : " + intakeNodeId); + + return intakeNode; + } + + /** + *Returns a list of Intake Nodes of type "intake". + */ + public List getIntakeNodes() { + // List l = + // getHibernateTemplate().find("from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.intake_node_type_id = iTemplate.intake_node_type_id and i.intake_node_template_id = iTemplate.intake_node_template_id"); + List l = (List) getHibernateTemplate() + .find( + "select i from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.id = iTemplate.type and i.nodeTemplate = iTemplate.id"); + + // from IntakeNode i where i.type = 'intake'"); + return l; + } + + /** + *Returns a list of Intake Nodes of type "intake". + */ + public List getPublishedIntakeNodesByName(String name) { + // List l = + // getHibernateTemplate().find("from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate where iType.type = 'intake' and iType.intake_node_type_id = iTemplate.intake_node_type_id and i.intake_node_template_id = iTemplate.intake_node_template_id"); + List l = (List) getHibernateTemplate() + .find( + "select i from IntakeNode i, IntakeNodeType iType, IntakeNodeTemplate iTemplate, IntakeNodeLabel iLabel where iType.type = 'intake' and iType.id = iTemplate.type and i.nodeTemplate = iTemplate.id and i.label = iLabel.id and i.publish_date != null and iLabel.label = ? order by i.form_version desc", + new Object[] { name }); + + // from IntakeNode i where i.type = 'intake'"); + return l; + } + + public List getIntakeNodeByEqToId(Integer iNodeEqToId) + throws SQLException { + if (iNodeEqToId == null) { + throw new IllegalArgumentException( + "Parameters iNodeEqToId must be non-null"); + } + + List nwIntakeNodes = new ArrayList(); + Set iNodeIds = getIntakeNodeIdByEqToId(iNodeEqToId); + for (Integer id : iNodeIds) { + nwIntakeNodes.add(getIntakeNode(id)); + } + return nwIntakeNodes; + } + + public Set getIntakeNodeIdByEqToId(Integer iNodeEqToId) + throws SQLException { + if (iNodeEqToId == null) { + throw new IllegalArgumentException( + "Parameters intakdNodeId must be non-null"); + } + Connection c = DbConnectionFilter.getThreadLocalDbConnection(); + Set results = new TreeSet(); + try { + PreparedStatement ps = c + .prepareStatement("select intake_node_id from intake_node where eq_to_id=?"); + ps.setInt(1, iNodeEqToId); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + results.add(rs.getInt(1)); + } + } finally { + c.close(); + } + return results; + } + + public Set getEqToIdByIntakeNodeId(Integer intakeNodeId) + throws SQLException { + if (intakeNodeId == null) { + throw new IllegalArgumentException( + "Parameters intakdNodeId must be non-null"); + } + Connection c = DbConnectionFilter.getThreadLocalDbConnection(); + Set results = new TreeSet(); + try { + PreparedStatement ps = c + .prepareStatement("select eq_to_id from intake_node where intake_node_id=?"); + ps.setInt(1, intakeNodeId); + ResultSet rs = ps.executeQuery(); + while (rs.next()) { + results.add(rs.getInt(1)); + } + } finally { + c.close(); + } + return results; + } + + public List getIntakeNodeByEqToId(Set iNodes) + { + if (iNodes == null) { + throw new IllegalArgumentException( + "Parameters iNodes must be non-null"); + } + + List nwIntakeNodes = new ArrayList(); + for (IntakeNode iN : iNodes) { + nwIntakeNodes.add(getIntakeNode(iN.getEq_to_id())); + } + return nwIntakeNodes; + } + + public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel) { + getHibernateTemplate().save(intakeNodeLabel); + } + + public void updateIntakeNode(IntakeNode intakeNode) { + getHibernateTemplate().update(intakeNode); + } + + public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel) { + getHibernateTemplate().update(intakeNodeLabel); + } + + public void updateAgencyIntakeQuick(Agency agency) { + getHibernateTemplate().update(agency); + } + + public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId) { + IntakeNodeLabel intakeNodeLabel = null; + if (intakeNodeLabelId == null || intakeNodeLabelId < 1) { + throw new IllegalArgumentException( + "intakeNodeLabelId must be non-null and greater than 0"); + } + //in case the node with intakenodelabel id doesn't exist + try { + intakeNodeLabel = getHibernateTemplate().get( + IntakeNodeLabel.class, intakeNodeLabelId); + } catch (ObjectNotFoundException onfe) { + LOG.warn("no node found for : " + intakeNodeLabelId); + } + return intakeNodeLabel; + } + + public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId) { + if (intakeNodeTemplateId == null || intakeNodeTemplateId < 1) { + throw new IllegalArgumentException( + "intakeNodeTemplateId must be non-null and greater than 0"); + } + IntakeNodeTemplate intakeNodeTemplate = getHibernateTemplate() + .get(IntakeNodeTemplate.class, intakeNodeTemplateId); + return intakeNodeTemplate; + } + + public void saveIntakeNode(IntakeNode intakeNode) { + getHibernateTemplate().save(intakeNode); + } + + public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate) { + getHibernateTemplate().save(intakeNodeTemplate); + } + + public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement) { + getHibernateTemplate().save(intakeAnswerElement); + } + + private void getChildren(IntakeNode intakeNode) { + HashSet nodeIds = new HashSet(); + nodeIds.add(intakeNode.getId()); + + getChildren(nodeIds, intakeNode.getChildren()); + } + + private void getChildren(Set nodeIds, List children) { + for (IntakeNode child : children) { + if (child == null) + continue; + Integer childId = child.getId(); + + if (nodeIds.contains(childId)) { + throw new IllegalStateException("intake node with id : " + + childId + " is an ancestor of itself"); + } else { + nodeIds.add(childId); + } + + // load children + getChildren(nodeIds, child.getChildren()); + } + } + + public void deleteIntakeNode(IntakeNode intakeNode) { + getHibernateTemplate().delete(intakeNode); + } + + public List getIntakeNodeJavascriptLocation(String questionId) { + List js = (List) getHibernateTemplate().find("FROM IntakeNodeJavascript j where j.questionId=?",questionId); + return js; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDao.java b/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDao.java index 703841ee99..5bd8084025 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,48 +18,24 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.List; - -import org.apache.logging.log4j.Logger; -import org.oscarehr.PMmodule.model.HealthSafety; -import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class HealthSafetyDao extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - public HealthSafety getHealthSafetyByDemographic(Long demographicNo) { - if (demographicNo == null || demographicNo.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - HealthSafety result = null; - - List list = this.getHibernateTemplate().find("from HealthSafety c where c.demographicNo=? order by c.updateDate desc", demographicNo); - if (!list.isEmpty()) result = (HealthSafety)list.get(0); - - if (log.isDebugEnabled()) { - log.debug("getHealthSafetyByDemographic:id=" + demographicNo + ",found=" + (result != null)); - } - - return result; - } - - public void saveHealthSafetyByDemographic(HealthSafety healthsafety) { - if (healthsafety == null) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().save(healthsafety); - - if (log.isDebugEnabled()) { - log.debug("saveHealthSafetyByDemographic:id=" + healthsafety.getId()); - } - } - -} + package org.oscarehr.PMmodule.dao; + + import java.util.List; + + import org.apache.logging.log4j.Logger; + import org.oscarehr.PMmodule.model.HealthSafety; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + public interface HealthSafetyDao { + + public HealthSafety getHealthSafetyByDemographic(Long demographicNo); + + public void saveHealthSafetyByDemographic(HealthSafety healthsafety); + + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDaoImpl.java new file mode 100644 index 0000000000..4a96d76270 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/HealthSafetyDaoImpl.java @@ -0,0 +1,67 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.HealthSafety; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class HealthSafetyDaoImpl extends HibernateDaoSupport implements HealthSafetyDao{ + + private Logger log=MiscUtils.getLogger(); + + public HealthSafety getHealthSafetyByDemographic(Long demographicNo) { + if (demographicNo == null || demographicNo.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + HealthSafety result = null; + + List list = this.getHibernateTemplate().find("from HealthSafety c where c.demographicNo=? order by c.updateDate desc", demographicNo); + if (!list.isEmpty()) result = (HealthSafety)list.get(0); + + if (log.isDebugEnabled()) { + log.debug("getHealthSafetyByDemographic:id=" + demographicNo + ",found=" + (result != null)); + } + + return result; + } + + public void saveHealthSafetyByDemographic(HealthSafety healthsafety) { + if (healthsafety == null) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().save(healthsafety); + + if (log.isDebugEnabled()) { + log.debug("saveHealthSafetyByDemographic:id=" + healthsafety.getId()); + } + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDao.java b/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDao.java index 1b77f041ba..dd224a3d33 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,73 +20,34 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.Date; -import java.util.List; - -import javax.persistence.Query; - -import org.oscarehr.PMmodule.model.OcanSubmissionLog; -import org.oscarehr.PMmodule.model.OcanSubmissionRecordLog; -import org.oscarehr.common.dao.AbstractDao; -import org.springframework.stereotype.Repository; - -@Repository -public class OcanSubmissionLogDao extends AbstractDao { + package org.oscarehr.PMmodule.dao; - public OcanSubmissionLogDao() { - super(OcanSubmissionLog.class); - } - - public void persistRecord(OcanSubmissionRecordLog rec) { - entityManager.persist(rec); - } - - - public List findBySubmissionDate(Date submissionDate) { - Query query = entityManager.createQuery("select l from OcanSubmissionLog l where date(l.submitDateTime)=? order by l.submitDateTime DESC"); - query.setParameter(1, submissionDate); - @SuppressWarnings("unchecked") - List results = query.getResultList(); - return results; - } - - public List findBySubmissionDateType(Date submissionDate, String type) { - Query query = entityManager.createQuery("select l from OcanSubmissionLog l where date(l.submitDateTime)=? and submissionType=? order by l.submitDateTime DESC"); - query.setParameter(1, submissionDate); - query.setParameter(2, type); - @SuppressWarnings("unchecked") - List results = query.getResultList(); - return results; - } - - public List findBySubmissionDateType(Date submissionStartDate, Date submissionEndDate, String type) { - Query query = entityManager.createQuery("select l from OcanSubmissionLog l where submitDateTime>=? and l.submitDateTime<=? and submissionType=? order by l.submitDateTime DESC"); - query.setParameter(1, submissionStartDate); - query.setParameter(2, submissionEndDate); - query.setParameter(3, type); - @SuppressWarnings("unchecked") - List results = query.getResultList(); - return results; - } - - public List findAllByType(String type) { - Query query = entityManager.createQuery("select l from OcanSubmissionLog l where l.submissionType=? order by l.submitDateTime DESC"); - query.setParameter(1, type); - @SuppressWarnings("unchecked") - List results = query.getResultList(); - return results; - } - - public List findFailedSubmissionsByType(String type) { - Query query = entityManager.createQuery("select l from OcanSubmissionLog l where l.submissionType=? and l.result=? order by l.submitDateTime DESC"); - query.setParameter(1, type); - query.setParameter(2, "false"); - @SuppressWarnings("unchecked") - List results = query.getResultList(); - return results; - } -} + import java.util.Date; + import java.util.List; + + import javax.persistence.Query; + + import org.oscarehr.PMmodule.model.OcanSubmissionLog; + import org.oscarehr.PMmodule.model.OcanSubmissionRecordLog; + import org.oscarehr.common.dao.AbstractDaoImpl; + import org.oscarehr.common.dao.AbstractDao; + import org.springframework.stereotype.Repository; + + public interface OcanSubmissionLogDao extends AbstractDao { + + public void persistRecord(OcanSubmissionRecordLog rec); + + public List findBySubmissionDate(Date submissionDate); + public List findBySubmissionDateType(Date submissionDate, String type); + + public List findBySubmissionDateType(Date submissionStartDate, Date submissionEndDate, String type); + + public List findAllByType(String type); + + public List findFailedSubmissionsByType(String type); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDaoImpl.java new file mode 100644 index 0000000000..1bb65ba572 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/OcanSubmissionLogDaoImpl.java @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.Date; +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.OcanSubmissionLog; +import org.oscarehr.PMmodule.model.OcanSubmissionRecordLog; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class OcanSubmissionLogDaoImpl extends AbstractDaoImpl implements OcanSubmissionLogDao{ + + public OcanSubmissionLogDaoImpl() { + super(OcanSubmissionLog.class); + } + + public void persistRecord(OcanSubmissionRecordLog rec) { + entityManager.persist(rec); + } + + + public List findBySubmissionDate(Date submissionDate) { + Query query = entityManager.createQuery("select l from OcanSubmissionLog l where date(l.submitDateTime)=? order by l.submitDateTime DESC"); + query.setParameter(1, submissionDate); + @SuppressWarnings("unchecked") + List results = query.getResultList(); + return results; + } + + public List findBySubmissionDateType(Date submissionDate, String type) { + Query query = entityManager.createQuery("select l from OcanSubmissionLog l where date(l.submitDateTime)=? and submissionType=? order by l.submitDateTime DESC"); + query.setParameter(1, submissionDate); + query.setParameter(2, type); + @SuppressWarnings("unchecked") + List results = query.getResultList(); + return results; + } + + public List findBySubmissionDateType(Date submissionStartDate, Date submissionEndDate, String type) { + Query query = entityManager.createQuery("select l from OcanSubmissionLog l where submitDateTime>=? and l.submitDateTime<=? and submissionType=? order by l.submitDateTime DESC"); + query.setParameter(1, submissionStartDate); + query.setParameter(2, submissionEndDate); + query.setParameter(3, type); + @SuppressWarnings("unchecked") + List results = query.getResultList(); + return results; + } + + public List findAllByType(String type) { + Query query = entityManager.createQuery("select l from OcanSubmissionLog l where l.submissionType=? order by l.submitDateTime DESC"); + query.setParameter(1, type); + @SuppressWarnings("unchecked") + List results = query.getResultList(); + return results; + } + + public List findFailedSubmissionsByType(String type) { + Query query = entityManager.createQuery("select l from OcanSubmissionLog l where l.submissionType=? and l.result=? order by l.submitDateTime DESC"); + query.setParameter(1, type); + query.setParameter(2, "false"); + @SuppressWarnings("unchecked") + List results = query.getResultList(); + return results; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAO.java index 41a8b2e123..fc76306d90 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -31,117 +34,23 @@ import org.oscarehr.PMmodule.model.ProgramAccess; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.QueueCache; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramAccessDAO extends HibernateDaoSupport { - - private static Logger log = MiscUtils.getLogger(); - - private static QueueCache> programAccessListByProgramIdCache=new QueueCache>(4, 100, DateUtils.MILLIS_PER_HOUR, null); - - @SuppressWarnings("unchecked") - public List getAccessListByProgramId(Long programId) { - List results=programAccessListByProgramIdCache.get(programId); - if (results==null) - { - String q = "select pp from ProgramAccess pp where pp.ProgramId=?"; - results=getHibernateTemplate().find(q, new Object[] {programId}); - if (results!=null) programAccessListByProgramIdCache.put(programId, results); - } - - return results; - } - - - public ProgramAccess getProgramAccess(Long id) { - - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - ProgramAccess result = this.getHibernateTemplate().get(ProgramAccess.class, id); - - if (log.isDebugEnabled()) { - log.debug("getProgramAccess: id=" + id + ",found=" + (result != null)); - } - return result; - } - - public ProgramAccess getProgramAccess(Long programId, Long accessTypeId) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - if (accessTypeId == null || accessTypeId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - String accessTypeIdString = accessTypeId.toString(); - ProgramAccess result = null; - List results = this.getHibernateTemplate().find("from ProgramAccess pa where pa.ProgramId = ? and pa.AccessTypeId = ?", new Object[] {programId, accessTypeIdString}); - if (results.size() > 0) { - result = (ProgramAccess)results.get(0); - } - - if (log.isDebugEnabled()) { - log.debug("getProgramAccess: programId=" + programId + ",accessTypeId=" + accessTypeId + ",found=" + (result != null)); - } - - return result; - } - - @SuppressWarnings("unchecked") - public List getProgramAccessListByType(Long programId, String accessType) { - String q = "from ProgramAccess pa where pa.ProgramId = ? and pa.AccessType.Name like ?"; - return this.getHibernateTemplate().find(q, new Object[] { programId, accessType }); - } - - public void saveProgramAccess(ProgramAccess pa) { - if (pa == null) { - throw new IllegalArgumentException(); - } - - getHibernateTemplate().saveOrUpdate(pa); - programAccessListByProgramIdCache.remove(pa.getProgramId()); - - if (log.isDebugEnabled()) { - log.debug("saveProgramAccess:" + pa.getId()); - } - } - - public void deleteProgramAccess(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; - ProgramAccess pa=getProgramAccess(id); - programAccessListByProgramIdCache.remove(pa.getProgramId()); - this.getHibernateTemplate().delete(pa); +public interface ProgramAccessDAO { - if (log.isDebugEnabled()) { - log.debug("deleteProgramAccess:" + id); - } + public List getAccessListByProgramId(Long programId); - } + public ProgramAccess getProgramAccess(Long id); - public List getAccessTypes() { - List results = this.getHibernateTemplate().find("from AccessType at"); + public ProgramAccess getProgramAccess(Long programId, Long accessTypeId); - if (log.isDebugEnabled()) { - log.debug("getAccessTypes: # of results=" + results.size()); - } - return results; - } + public List getProgramAccessListByType(Long programId, String accessType); - public AccessType getAccessType(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } + public void saveProgramAccess(ProgramAccess pa); - AccessType result = this.getHibernateTemplate().get(AccessType.class, id); + public void deleteProgramAccess(Long id); - if (log.isDebugEnabled()) { - log.debug("getAccessType: id=" + id + ",found=" + (result != null)); - } + public List getAccessTypes(); - return result; - } + public AccessType getAccessType(Long id); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAOImpl.java new file mode 100644 index 0000000000..6a36ebee0a --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramAccessDAOImpl.java @@ -0,0 +1,161 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import org.apache.commons.lang.time.DateUtils; +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.AccessType; +import org.oscarehr.PMmodule.model.ProgramAccess; +import org.oscarehr.util.MiscUtils; +import org.oscarehr.util.QueueCache; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class ProgramAccessDAOImpl extends HibernateDaoSupport implements ProgramAccessDAO { + + private static Logger log = MiscUtils.getLogger(); + + private static QueueCache> programAccessListByProgramIdCache = new QueueCache>( + 4, 100, DateUtils.MILLIS_PER_HOUR, null); + + @SuppressWarnings("unchecked") + @Override + public List getAccessListByProgramId(Long programId) { + List results = programAccessListByProgramIdCache.get(programId); + if (results == null) { + String q = "select pp from ProgramAccess pp where pp.ProgramId=?"; + results = (List) getHibernateTemplate().find(q, new Object[] { programId }); + if (results != null) + programAccessListByProgramIdCache.put(programId, results); + } + + return results; + } + + @Override + public ProgramAccess getProgramAccess(Long id) { + + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramAccess result = this.getHibernateTemplate().get(ProgramAccess.class, id); + + if (log.isDebugEnabled()) { + log.debug("getProgramAccess: id=" + id + ",found=" + (result != null)); + } + return result; + } + + @Override + public ProgramAccess getProgramAccess(Long programId, Long accessTypeId) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + if (accessTypeId == null || accessTypeId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + String accessTypeIdString = accessTypeId.toString(); + ProgramAccess result = null; + List results = this.getHibernateTemplate().find( + "from ProgramAccess pa where pa.ProgramId = ? and pa.AccessTypeId = ?", + new Object[] { programId, accessTypeIdString }); + if (results.size() > 0) { + result = (ProgramAccess) results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getProgramAccess: programId=" + programId + ",accessTypeId=" + accessTypeId + ",found=" + + (result != null)); + } + + return result; + } + + @SuppressWarnings("unchecked") + @Override + public List getProgramAccessListByType(Long programId, String accessType) { + String q = "from ProgramAccess pa where pa.ProgramId = ? and pa.AccessType.Name like ?"; + return (List) this.getHibernateTemplate().find(q, new Object[] { programId, accessType }); + } + + @Override + public void saveProgramAccess(ProgramAccess pa) { + if (pa == null) { + throw new IllegalArgumentException(); + } + + getHibernateTemplate().saveOrUpdate(pa); + programAccessListByProgramIdCache.remove(pa.getProgramId()); + + if (log.isDebugEnabled()) { + log.debug("saveProgramAccess:" + pa.getId()); + } + } + + @Override + public void deleteProgramAccess(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramAccess pa = getProgramAccess(id); + programAccessListByProgramIdCache.remove(pa.getProgramId()); + this.getHibernateTemplate().delete(pa); + + if (log.isDebugEnabled()) { + log.debug("deleteProgramAccess:" + id); + } + + } + + @Override + public List getAccessTypes() { + List results = (List) this.getHibernateTemplate().find("from AccessType at"); + + if (log.isDebugEnabled()) { + log.debug("getAccessTypes: # of results=" + results.size()); + } + return results; + } + + @Override + public AccessType getAccessType(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + AccessType result = this.getHibernateTemplate().get(AccessType.class, id); + + if (log.isDebugEnabled()) { + log.debug("getAccessType: id=" + id + ",found=" + (result != null)); + } + + return result; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAO.java index 54e9a7f93e..b35f8fb72c 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,118 +20,41 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.dao; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.oscarehr.PMmodule.model.ProgramClientRestriction; -import org.oscarehr.common.dao.DemographicDao; -import org.springframework.beans.factory.annotation.Required; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -/** - */ -public class ProgramClientRestrictionDAO extends HibernateDaoSupport { - private DemographicDao demographicDao; - private ProgramDao programDao; - private ProviderDao providerDao; - - public Collection find(int programId, int demographicNo) { - - List pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.programId = ? and pcr.demographicNo = ? order by pcr.startDate", new Object[]{programId, demographicNo}); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; - } - - public void save(ProgramClientRestriction restriction) { - getHibernateTemplate().saveOrUpdate(restriction); - } - - public ProgramClientRestriction find(int restrictionId) { - return setRelationships(getHibernateTemplate().get(ProgramClientRestriction.class, restrictionId)); - } - - public Collection findForProgram(int programId) { - Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.programId = ? order by pcr.demographicNo", programId); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; - } - - public Collection findDisabledForProgram(int programId) { - Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = false and pcr.programId = ? order by pcr.demographicNo", programId); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; - } - - public Collection findForClient(int demographicNo) { - Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.demographicNo = ? order by pcr.programId", demographicNo); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; - } - - public Collection findForClient(int demographicNo, int facilityId) { - ArrayList paramList = new ArrayList(); - String sSQL="from ProgramClientRestriction pcr where pcr.enabled = true and " + - "pcr.demographicNo = ? and pcr.programId in (select s.id from Program s where s.facilityId = ? or s.facilityId is null) " + - "order by pcr.programId"; - paramList.add(Integer.valueOf(demographicNo)); - paramList.add(facilityId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - Collection pcrs= getHibernateTemplate().find(sSQL, params); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; -/* - Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.demographicNo = ? order by pcr.programId", demographicNo); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; -*/ - } - - public Collection findDisabledForClient(int demographicNo) { - Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = false and pcr.demographicNo = ? order by pcr.programId", demographicNo); - for (ProgramClientRestriction pcr : pcrs) { - setRelationships(pcr); - } - return pcrs; - } - - private ProgramClientRestriction setRelationships(ProgramClientRestriction pcr) { - pcr.setClient(demographicDao.getDemographic("" + pcr.getDemographicNo())); - pcr.setProgram(programDao.getProgram(pcr.getProgramId())); - pcr.setProvider(providerDao.getProvider(pcr.getProviderNo())); - - return pcr; - } - - @Required - public void setDemographicDao(DemographicDao demographicDao) { - this.demographicDao = demographicDao; - } - - @Required - public void setProgramDao(ProgramDao programDao) { - this.programDao = programDao; - } - - @Required - public void setProviderDao(ProviderDao providerDao) { - this.providerDao = providerDao; - } - -} + package org.oscarehr.PMmodule.dao; + + import java.util.ArrayList; + import java.util.Collection; + import java.util.List; + + import org.oscarehr.PMmodule.model.ProgramClientRestriction; + import org.oscarehr.common.dao.DemographicDao; + import org.springframework.beans.factory.annotation.Required; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + + /** + */ + public interface ProgramClientRestrictionDAO { + + public Collection find(int programId, int demographicNo); + + public void save(ProgramClientRestriction restriction); + + public ProgramClientRestriction find(int restrictionId); + public Collection findForProgram(int programId); + + public Collection findDisabledForProgram(int programId); + public Collection findForClient(int demographicNo); + + public Collection findForClient(int demographicNo, int facilityId); + + public Collection findDisabledForClient(int demographicNo); + public void setDemographicDao(DemographicDao demographicDao); + public void setProgramDao(ProgramDao programDao); + public void setProviderDao(ProviderDao providerDao); + + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAOImpl.java new file mode 100644 index 0000000000..64873a7ef9 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientRestrictionDAOImpl.java @@ -0,0 +1,139 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.oscarehr.PMmodule.model.ProgramClientRestriction; +import org.oscarehr.common.dao.DemographicDao; +import org.springframework.beans.factory.annotation.Required; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +/** + */ +public class ProgramClientRestrictionDAOImpl extends HibernateDaoSupport implements ProgramClientRestrictionDAO{ + private DemographicDao demographicDao; + private ProgramDao programDao; + private ProviderDao providerDao; + + public Collection find(int programId, int demographicNo) { + + List pcrs = (List) getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.programId = ? and pcr.demographicNo = ? order by pcr.startDate", new Object[]{programId, demographicNo}); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; + } + + public void save(ProgramClientRestriction restriction) { + getHibernateTemplate().saveOrUpdate(restriction); + } + + public ProgramClientRestriction find(int restrictionId) { + return setRelationships(getHibernateTemplate().get(ProgramClientRestriction.class, restrictionId)); + } + + public Collection findForProgram(int programId) { + Collection pcrs = (Collection) getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.programId = ? order by pcr.demographicNo", programId); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; + } + + public Collection findDisabledForProgram(int programId) { + Collection pcrs = (Collection) getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = false and pcr.programId = ? order by pcr.demographicNo", programId); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; + } + + public Collection findForClient(int demographicNo) { + Collection pcrs = (Collection) getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.demographicNo = ? order by pcr.programId", demographicNo); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; + } + + public Collection findForClient(int demographicNo, int facilityId) { + ArrayList paramList = new ArrayList(); + String sSQL="from ProgramClientRestriction pcr where pcr.enabled = true and " + + "pcr.demographicNo = ? and pcr.programId in (select s.id from Program s where s.facilityId = ? or s.facilityId is null) " + + "order by pcr.programId"; + paramList.add(Integer.valueOf(demographicNo)); + paramList.add(facilityId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + Collection pcrs= (Collection) getHibernateTemplate().find(sSQL, params); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; +/* + Collection pcrs = getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = true and pcr.demographicNo = ? order by pcr.programId", demographicNo); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; +*/ + } + + public Collection findDisabledForClient(int demographicNo) { + Collection pcrs = (Collection) getHibernateTemplate().find("from ProgramClientRestriction pcr where pcr.enabled = false and pcr.demographicNo = ? order by pcr.programId", demographicNo); + for (ProgramClientRestriction pcr : pcrs) { + setRelationships(pcr); + } + return pcrs; + } + + private ProgramClientRestriction setRelationships(ProgramClientRestriction pcr) { + pcr.setClient(demographicDao.getDemographic("" + pcr.getDemographicNo())); + pcr.setProgram(programDao.getProgram(pcr.getProgramId())); + pcr.setProvider(providerDao.getProvider(pcr.getProviderNo())); + + return pcr; + } + + @Required + public void setDemographicDao(DemographicDao demographicDao) { + this.demographicDao = demographicDao; + } + + @Required + public void setProgramDao(ProgramDao programDao) { + this.programDao = programDao; + } + + @Required + public void setProviderDao(ProviderDao providerDao) { + this.providerDao = providerDao; + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAO.java index 89d11e2a7d..2f080e7833 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -31,77 +34,17 @@ import org.oscarehr.PMmodule.model.ProgramClientStatus; import org.oscarehr.common.model.Admission; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramClientStatusDAO extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - public List getProgramClientStatuses(Integer programId) { - return this.getHibernateTemplate().find("from ProgramClientStatus pcs where pcs.programId=?", programId); - } - - public void saveProgramClientStatus(ProgramClientStatus status) { - this.getHibernateTemplate().saveOrUpdate(status); - } - - public ProgramClientStatus getProgramClientStatus(String id) { - if (id == null || Integer.valueOf(id) < 0) { - throw new IllegalArgumentException(); - } - - ProgramClientStatus pcs = null; - pcs = this.getHibernateTemplate().get(ProgramClientStatus.class, new Integer(id)); - if (pcs != null) return pcs; - else return null; - } - - public void deleteProgramClientStatus(String id) { - this.getHibernateTemplate().delete(getProgramClientStatus(id)); - } - - public boolean clientStatusNameExists(Integer programId, String statusName) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - if (statusName == null || statusName.length() <= 0) { - throw new IllegalArgumentException(); - } - - Session session = getSession(); - List teams = new ArrayList(); - try { - Query query =session.createQuery("select pt.id from ProgramClientStatus pt where pt.programId = ? and pt.name = ?"); - query.setLong(0, programId.longValue()); - query.setString(1, statusName); - - teams = query.list(); - - if (log.isDebugEnabled()) { - log.debug("teamNameExists: programId = " + programId + ", statusName = " + statusName + ", result = " + !teams.isEmpty()); - } - }finally { - releaseSession(session); - } - return !teams.isEmpty(); - } - - public List getAllClientsInStatus(Integer programId, Integer statusId) { - if (programId == null || programId <= 0) { - throw new IllegalArgumentException(); - } - - if (statusId == null || statusId <= 0) { - throw new IllegalArgumentException(); - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; - List results = this.getHibernateTemplate().find("from Admission a where a.ProgramId = ? and a.TeamId = ? and a.AdmissionStatus='current'", new Object[] {programId, statusId}); +public interface ProgramClientStatusDAO{ + public List getProgramClientStatuses(Integer programId); + public void saveProgramClientStatus(ProgramClientStatus status); - if (log.isDebugEnabled()) { - log.debug("getAdmissionsInTeam: programId= " + programId + ",statusId=" + statusId + ",# results=" + results.size()); - } + public ProgramClientStatus getProgramClientStatus(String id); - return results; - } + public void deleteProgramClientStatus(String id); + public boolean clientStatusNameExists(Integer programId, String statusName); + public List getAllClientsInStatus(Integer programId, Integer statusId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAOImpl.java new file mode 100644 index 0000000000..e40db0418c --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramClientStatusDAOImpl.java @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Query; +import org.hibernate.Session; +import org.oscarehr.PMmodule.model.ProgramClientStatus; +import org.oscarehr.common.model.Admission; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +public class ProgramClientStatusDAOImpl extends HibernateDaoSupport implements ProgramClientStatusDAO{ + + private Logger log=MiscUtils.getLogger(); + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + public List getProgramClientStatuses(Integer programId) { + return (List) this.getHibernateTemplate().find("from ProgramClientStatus pcs where pcs.programId=?", programId); + } + + public void saveProgramClientStatus(ProgramClientStatus status) { + this.getHibernateTemplate().saveOrUpdate(status); + } + + public ProgramClientStatus getProgramClientStatus(String id) { + if (id == null || Integer.valueOf(id) < 0) { + throw new IllegalArgumentException(); + } + + ProgramClientStatus pcs = null; + pcs = this.getHibernateTemplate().get(ProgramClientStatus.class, new Integer(id)); + if (pcs != null) return pcs; + else return null; + } + + public void deleteProgramClientStatus(String id) { + this.getHibernateTemplate().delete(getProgramClientStatus(id)); + } + + public boolean clientStatusNameExists(Integer programId, String statusName) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + if (statusName == null || statusName.length() <= 0) { + throw new IllegalArgumentException(); + } + + // Session session = getSession(); + Session session = sessionFactory.getCurrentSession(); + List teams = new ArrayList(); + try { + Query query =session.createQuery("select pt.id from ProgramClientStatus pt where pt.programId = ? and pt.name = ?"); + query.setLong(0, programId.longValue()); + query.setString(1, statusName); + + teams = query.list(); + + if (log.isDebugEnabled()) { + log.debug("teamNameExists: programId = " + programId + ", statusName = " + statusName + ", result = " + !teams.isEmpty()); + } + }finally { + //releaseSession(session); + session.close(); + } + return !teams.isEmpty(); + } + + public List getAllClientsInStatus(Integer programId, Integer statusId) { + if (programId == null || programId <= 0) { + throw new IllegalArgumentException(); + } + + if (statusId == null || statusId <= 0) { + throw new IllegalArgumentException(); + } + + List results = (List) this.getHibernateTemplate().find("from Admission a where a.ProgramId = ? and a.TeamId = ? and a.AdmissionStatus='current'", new Object[] {programId, statusId}); + + if (log.isDebugEnabled()) { + log.debug("getAdmissionsInTeam: programId= " + programId + ",statusId=" + statusId + ",# results=" + results.size()); + } + + return results; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramDao.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramDao.java index bd76bda7b7..6b84884276 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -36,526 +39,77 @@ import org.hibernate.criterion.Restrictions; import org.oscarehr.PMmodule.model.Program; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; import oscar.OscarProperties; -public class ProgramDao extends HibernateDaoSupport { - - private static final Logger log=MiscUtils.getLogger(); - - public boolean isBedProgram(Integer programId) { - Program result=getProgram(programId); - if (result==null) return(false); - return(result.isBed()); - } - - public boolean isServiceProgram(Integer programId) { - Program result=getProgram(programId); - if (result==null) return(false); - return(result.isService()); - } - - public boolean isCommunityProgram(Integer programId) { - Program result=getProgram(programId); - if (result==null) return(false); - return(result.isCommunity()); - } - - public boolean isExternalProgram(Integer programId) { - Program result=getProgram(programId); - if (result==null) return(false); - return(result.isExternal()); - } - - public Program getProgram(Integer programId) { - if (programId == null || programId.intValue() <= 0) { - return null; - } - - Program program = getHibernateTemplate().get(Program.class, programId); - - return program; - } - - public Program getProgramForApptView(Integer programId) { - if (programId == null || programId <= 0) { - return null; - } - Program result = null; - String queryStr = "FROM Program p WHERE p.id = ? AND p.exclusiveView = 'appointment'"; - List rs = getHibernateTemplate().find(queryStr, programId); - - if (log.isDebugEnabled()) { - log.debug("isCommunityProgram: id=" + programId ); - } - if (!rs.isEmpty()) { - result = rs.get(0); - } - - return result; - } - - public String getProgramName(Integer programId) { - Program result=getProgram(programId); - if (result==null) return(null); - return(result.getName()); - } - - public Integer getProgramIdByProgramName(String programName) { - - if(programName == null) return null; - - @SuppressWarnings("unchecked") - List programs = getHibernateTemplate().find("FROM Program p WHERE p.name = ? ORDER BY p.id ", programName); - if(!programs.isEmpty()) { - return programs.get(0).getId(); - } else { - return null; - } - } - - - public List findAll() - { - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find("FROM Program p"); - return rs; - } - - /** - * This method doesn't work, it doesn't find all programs, it only finds all community programs. See findAll instead. - * @deprecated 2013-12-09 don't use this anymore it's misleading - */ - public List getAllPrograms() { - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find("FROM Program p WHERE p.type != ? ORDER BY p.name ", Program.COMMUNITY_TYPE); - - if (log.isDebugEnabled()) { - log.debug("getAllPrograms: # of programs: " + rs.size()); - } - - return rs; - } - - public List getAllActivePrograms() { - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find("FROM Program p WHERE p.programStatus = '"+Program.PROGRAM_STATUS_ACTIVE+"'"); - return rs; - } - - /** - * @deprecated 2013-12-09 don't use this anymore use getProgramByType, reason is parameters should never have been "Any" - */ - public List getAllPrograms(String programStatus, String type, int facilityId) - { - Session session = getSession(); - try { - @SuppressWarnings("unchecked") - Criteria c = session.createCriteria(Program.class); - if (!"Any".equals(programStatus)) { - c.add(Restrictions.eq("programStatus", programStatus)); - } - if (!"Any".equals(type)) { - c.add(Restrictions.eq("type", type)); - } - if (facilityId > 0) { - c.add(Restrictions.eq("facilityId", facilityId)); - } - return c.list(); - }finally { - releaseSession(session); - } - } - - /** - * This method doesn't work, it doesn't find all programs, it only finds all community programs. See findAll instead. - * @deprecated 2013-12-09 don't use this anymore it's misleading - */ - public List getPrograms() { - String queryStr = "FROM Program p WHERE p.type != '"+Program.COMMUNITY_TYPE+"' ORDER BY p.name"; - - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr); - - return rs; - } - - /** - * This method doesn't work, it doesn't find all programs, it only finds all community programs. See findAll instead. - * @deprecated 2013-12-09 don't use this anymore it's misleading - */ - public List getActivePrograms() { - String queryStr = "FROM Program p WHERE p.type <> '"+Program.COMMUNITY_TYPE+"' and p.programStatus = '"+Program.PROGRAM_STATUS_ACTIVE+"'"; - - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr); - - return rs; - } - - /** - * @param facilityId is allowed to be null - * @return a list of programs in the facility and any programs with no facility associated - */ - public List getProgramsByFacilityId(Integer facilityId) { - String queryStr = "FROM Program p WHERE (p.facilityId = "+facilityId+" or p.facilityId is null) ORDER BY p.name"; - - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr); - - return rs; - } - - public List getProgramsByFacilityIdAndFunctionalCentreId(Integer facilityId, String functionalCentreId) { - String queryStr = "FROM Program p WHERE p.facilityId = "+facilityId+" and p.functionalCentreId = '"+functionalCentreId+'\''; - - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr); - - return rs; - } - - /** - * @param facilityId is allowed to be null - * @return a list of community programs in the facility and any programs with no facility associated - */ - public List getCommunityProgramsByFacilityId(Integer facilityId) { - String queryStr = "FROM Program p WHERE (p.facilityId = "+facilityId+" or p.facilityId is null) AND p.type != '"+Program.COMMUNITY_TYPE+"' ORDER BY p.name"; - - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find(queryStr); - - return rs; - } - - - /** - * results are ordered by name - * @param facilityId can be null for all, but generally shouldn't be - * @param active can be null for both - */ - public List getProgramsByType(Integer facilityId, String type, Boolean active) { - StringBuilder sqlCommand=new StringBuilder("FROM Program p WHERE p.type = '"+type+"'"); - - if (facilityId!=null) sqlCommand.append(" and p.facilityId = "+ facilityId); - if (active!=null) sqlCommand.append(" and p.programStatus='"+(active?Program.PROGRAM_STATUS_ACTIVE:Program.PROGRAM_STATUS_INACTIVE)+"'"); - - sqlCommand.append(" ORDER BY p.name"); - - @SuppressWarnings("unchecked") - List list = getHibernateTemplate().find(sqlCommand.toString()); - return (list); - } - - public List getProgramByGenderType(String genderType) { - // yeah I know, it's not safe to insert random strings and it's also inefficient, but unless I fix all the hibernate calls I'm following convention of - // using the hibernate templates and just inserting random strings for now. - @SuppressWarnings("unchecked") - List rs = getHibernateTemplate().find("FROM Program p WHERE p.manOrWoman = '" + genderType + "'"); - return rs; - } - - public void saveProgram(Program program) { - if (program == null) { - throw new IllegalArgumentException(); - } - program.setLastUpdateDate(new Date()); - getHibernateTemplate().saveOrUpdate(program); - - if (log.isDebugEnabled()) { - log.debug("saveProgram: " + program.getId()); - } - } - - public void removeProgram(Integer programId) { - if (programId == null || programId <= 0) { - throw new IllegalArgumentException(); - } - try { - Object program = getHibernateTemplate().load(Program.class, programId); - - getHibernateTemplate().delete(program); - - if (log.isDebugEnabled()) { - log.debug("deleteProgram: " + programId); - } - } catch(Exception e) { - MiscUtils.getLogger().warn("Unable to delete program " + programId); - } - } - - public List search(Program program) { - if (program == null) { - throw new IllegalArgumentException(); - } - Session session = getSession(); - Criteria criteria = session.createCriteria(Program.class); - - if (program.getName() != null && program.getName().length() > 0) { - String programName = StringEscapeUtils.escapeSql(program.getName()); - String sql = ""; - sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4))" + " " + "OR (name like '" + "%" + programName + "%'))"; - criteria.add(Restrictions.sqlRestriction(sql)); - } - - if (program.getType() != null && program.getType().length() > 0) { - criteria.add(Expression.eq("type", program.getType())); - } - - if (program.getType() == null || program.getType().equals("") || !program.getType().equals("community")) { - criteria.add(Expression.ne("type", "community")); - } - - criteria.add(Expression.eq("programStatus", Program.PROGRAM_STATUS_ACTIVE)); - - if (program.getManOrWoman() != null && program.getManOrWoman().length() > 0) { - criteria.add(Expression.eq("manOrWoman", program.getManOrWoman())); - } - - if (program.isTransgender()) { - criteria.add(Expression.eq("transgender", true)); - } - - if (program.isFirstNation()) { - criteria.add(Expression.eq("firstNation", true)); - } - - if (program.isBedProgramAffiliated()) { - criteria.add(Expression.eq("bedProgramAffiliated", true)); - } - - if (program.isAlcohol()) { - criteria.add(Expression.eq("alcohol", true)); - } - - if (program.getAbstinenceSupport() != null && program.getAbstinenceSupport().length() > 0) { - criteria.add(Expression.eq("abstinenceSupport", program.getAbstinenceSupport())); - } - - if (program.isPhysicalHealth()) { - criteria.add(Expression.eq("physicalHealth", true)); - } - - if (program.isHousing()) { - criteria.add(Expression.eq("housing", true)); - } - - if (program.isMentalHealth()) { - criteria.add(Expression.eq("mentalHealth", true)); - } - criteria.addOrder(Order.asc("name")); - - List results = new ArrayList(); - try { - results = criteria.list(); - }finally { - this.releaseSession(session); - } - - if (log.isDebugEnabled()) { - log.debug("search: # results: " + results.size()); - } - - return results; - } - - public List searchByFacility(Program program, Integer facilityId) { - if (program == null) { - throw new IllegalArgumentException(); - } - if (facilityId == null) { - throw new IllegalArgumentException(); - } - - boolean isOracle = OscarProperties.getInstance().getDbType().equals("oracle"); - Session session = getSession(); - Criteria criteria = session.createCriteria(Program.class); - - if (program.getName() != null && program.getName().length() > 0) { - String programName = StringEscapeUtils.escapeSql(program.getName()); - String sql = ""; - if (isOracle) { - sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4)))"; - criteria.add(Restrictions.or(Restrictions.ilike("name", "%" + programName + "%"), Restrictions.sqlRestriction(sql))); - } - else - { - sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4))" + " " + "OR (name like '" + "%" + programName + "%'))"; - criteria.add(Restrictions.sqlRestriction(sql)); - } - } - - if (program.getType() != null && program.getType().length() > 0) { - criteria.add(Expression.eq("type", program.getType())); - } - - if (program.getType() == null || program.getType().equals("") || !program.getType().equals(Program.COMMUNITY_TYPE)) { - criteria.add(Expression.ne("type", Program.COMMUNITY_TYPE)); - } - - criteria.add(Expression.eq("programStatus", Program.PROGRAM_STATUS_ACTIVE)); - - if (program.getManOrWoman() != null && program.getManOrWoman().length() > 0) { - criteria.add(Expression.eq("manOrWoman", program.getManOrWoman())); - } - - if (program.isTransgender()) { - criteria.add(Expression.eq("transgender", true)); - } - - if (program.isFirstNation()) { - criteria.add(Expression.eq("firstNation", true)); - } - - if (program.isBedProgramAffiliated()) { - criteria.add(Expression.eq("bedProgramAffiliated", true)); - } - - if (program.isAlcohol()) { - criteria.add(Expression.eq("alcohol", true)); - } - - if (program.getAbstinenceSupport() != null && program.getAbstinenceSupport().length() > 0) { - criteria.add(Expression.eq("abstinenceSupport", program.getAbstinenceSupport())); - } - - if (program.isPhysicalHealth()) { - criteria.add(Expression.eq("physicalHealth", true)); - } - - if (program.isHousing()) { - criteria.add(Expression.eq("housing", true)); - } - - if (program.isMentalHealth()) { - criteria.add(Expression.eq("mentalHealth", true)); - } - - criteria.add(Expression.eq("facilityId", facilityId)); - - criteria.addOrder(Order.asc("name")); - - List results = new ArrayList(); - try { - results = criteria.list(); - }finally{ - releaseSession(session); - } - - if (log.isDebugEnabled()) { - log.debug("search: # results: " + results.size()); - } - - return results; - } - - public void resetHoldingTank() { - List programs = this.getAllPrograms(); - for(Program p:programs) { - if(p.getHoldingTank()) { - p.setHoldingTank(false); - this.saveProgram(p); - } - - } - - if (log.isDebugEnabled()) { - log.debug("resetHoldingTank:"); - } - } - - public Program getHoldingTankProgram() { - Program result = null; - - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from Program p where p.holdingTank = true"); - - if (!results.isEmpty()) { - result = results.get(0); - } - - if (log.isDebugEnabled()) { - log.debug((result != null) ? "getHoldingTankProgram: program: " + result.getId() : "getHoldingTankProgram: none found"); - } - - return result; - } - - public boolean programExists(Integer programId) { - return(getProgram(programId)!=null); - } - - public List getLinkedServicePrograms(Integer bedProgramId, Integer clientId) { - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find( - "select p from Admission a,Program p where a.programId = p.id and p.type='"+Program.SERVICE_TYPE+"' and p.bedProgramLinkId = ? and a.clientId=?", - new Object[] { bedProgramId, clientId }); - return results; - } - - public boolean isInSameFacility(Integer programId1, Integer programId2) { - if (programId1 == null || programId1 <= 0) { - throw new IllegalArgumentException(); - } - - if (programId2 == null || programId2 <= 0) { - throw new IllegalArgumentException(); - } - - Program p1 = getProgram(programId1); - Program p2 = getProgram(programId2); - - if(p1 == null || p2 == null) - return false; - - return(p1.getFacilityId()==p2.getFacilityId()); - } - - public Program getProgramBySiteSpecificField(String value) { - Program result = null; - - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from Program p where p.siteSpecificField = ?", new Object[]{value}); - - if (!results.isEmpty()) { - result = results.get(0); - } - - return result; - } - - public Program getProgramByName(String value) { - Program result = null; - - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from Program p where p.name = ?", new Object[]{value}); - - if (!results.isEmpty()) { - result = results.get(0); - } - - return result; - } - - public List getRecordsAddedAndUpdatedSinceTime(Integer facilityId, Date date) { - @SuppressWarnings("unchecked") - List programs = getHibernateTemplate().find("select distinct p.id From Program p where p.facilityId = ? and p.lastUpdateDate > ? ",facilityId, date); - - return programs; - } - - public List getRecordsByFacilityId(Integer facilityId) { - @SuppressWarnings("unchecked") - List programs = getHibernateTemplate().find("select distinct p.id From Program p where p.facilityId = ? ",facilityId); - - return programs; - } - - public List getRecordsAddedAndUpdatedSinceTime(Date date) { - @SuppressWarnings("unchecked") - List providers = getHibernateTemplate().find("select distinct p.ProviderNo From Provider p where p.lastUpdateDate > ? ",date); - - return providers; - } +public interface ProgramDao { + + public boolean isBedProgram(Integer programId); + + public boolean isServiceProgram(Integer programId); + + public boolean isCommunityProgram(Integer programId); + + public boolean isExternalProgram(Integer programId); + + public Program getProgram(Integer programId); + + public Program getProgramForApptView(Integer programId); + + public String getProgramName(Integer programId); + + public Integer getProgramIdByProgramName(String programName); + + public List findAll(); + + public List getAllPrograms(); + + public List getAllActivePrograms(); + + public List getAllPrograms(String programStatus, String type, int facilityId); + + public List getPrograms(); + + public List getActivePrograms(); + + public List getProgramsByFacilityId(Integer facilityId); + + public List getProgramsByFacilityIdAndFunctionalCentreId(Integer facilityId, String functionalCentreId); + + public List getCommunityProgramsByFacilityId(Integer facilityId); + + public List getProgramsByType(Integer facilityId, String type, Boolean active); + + public List getProgramByGenderType(String genderType); + + public void saveProgram(Program program); + + public void removeProgram(Integer programId); + + public List search(Program program); + + public List searchByFacility(Program program, Integer facilityId); + + public void resetHoldingTank(); + + public Program getHoldingTankProgram(); + + public boolean programExists(Integer programId); + + public List getLinkedServicePrograms(Integer bedProgramId, Integer clientId); + + public boolean isInSameFacility(Integer programId1, Integer programId2); + + public Program getProgramBySiteSpecificField(String value); + + public Program getProgramByName(String value); + + public List getRecordsAddedAndUpdatedSinceTime(Integer facilityId, Date date); + + public List getRecordsByFacilityId(Integer facilityId); + + public List getRecordsAddedAndUpdatedSinceTime(Date date); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramDaoImpl.java new file mode 100644 index 0000000000..e9ca50e6a5 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramDaoImpl.java @@ -0,0 +1,661 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.logging.log4j.Logger; +import org.hibernate.Criteria; +import org.hibernate.FlushMode; +import org.hibernate.Session; +import org.hibernate.criterion.Expression; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.Restrictions; +import org.oscarehr.PMmodule.model.Program; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; +import org.springframework.transaction.annotation.Transactional; + +import oscar.OscarProperties; + +@Transactional +public class ProgramDaoImpl extends HibernateDaoSupport implements ProgramDao { + + private static final Logger log = MiscUtils.getLogger(); + // public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + @Override + public boolean isBedProgram(Integer programId) { + Program result = getProgram(programId); + if (result == null) + return (false); + return (result.isBed()); + } + + @Override + public boolean isServiceProgram(Integer programId) { + Program result = getProgram(programId); + if (result == null) + return (false); + return (result.isService()); + } + + @Override + public boolean isCommunityProgram(Integer programId) { + Program result = getProgram(programId); + if (result == null) + return (false); + return (result.isCommunity()); + } + + @Override + public boolean isExternalProgram(Integer programId) { + Program result = getProgram(programId); + if (result == null) + return (false); + return (result.isExternal()); + } + + @Override + public Program getProgram(Integer programId) { + if (programId == null || programId.intValue() <= 0) { + return null; + } + + Program program = getHibernateTemplate().get(Program.class, programId); + + return program; + } + + @Override + public Program getProgramForApptView(Integer programId) { + if (programId == null || programId <= 0) { + return null; + } + Program result = null; + String queryStr = "FROM Program p WHERE p.id = ? AND p.exclusiveView = 'appointment'"; + List rs = (List) getHibernateTemplate().find(queryStr, programId); + + if (log.isDebugEnabled()) { + log.debug("isCommunityProgram: id=" + programId); + } + if (!rs.isEmpty()) { + result = rs.get(0); + } + + return result; + } + + @Override + public String getProgramName(Integer programId) { + Program result = getProgram(programId); + if (result == null) + return (null); + return (result.getName()); + } + + @Override + public Integer getProgramIdByProgramName(String programName) { + + if (programName == null) + return null; + + @SuppressWarnings("unchecked") + List programs = (List) getHibernateTemplate() + .find("FROM Program p WHERE p.name = ? ORDER BY p.id ", programName); + if (!programs.isEmpty()) { + return programs.get(0).getId(); + } else { + return null; + } + } + + @Override + public List findAll() { + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find("FROM Program p"); + return rs; + } + + /** + * This method doesn't work, it doesn't find all programs, it only finds all + * community programs. See findAll instead. + * + * @deprecated 2013-12-09 don't use this anymore it's misleading + */ + @Override + public List getAllPrograms() { + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate() + .find("FROM Program p WHERE p.type != ? ORDER BY p.name ", Program.COMMUNITY_TYPE); + + if (log.isDebugEnabled()) { + log.debug("getAllPrograms: # of programs: " + rs.size()); + } + + return rs; + } + + @Override + public List getAllActivePrograms() { + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate() + .find("FROM Program p WHERE p.programStatus = '" + Program.PROGRAM_STATUS_ACTIVE + "'"); + return rs; + } + + /** + * @deprecated 2013-12-09 don't use this anymore use getProgramByType, reason is + * parameters should never have been "Any" + */ + @Override + public List getAllPrograms(String programStatus, String type, int facilityId) { + // Session session = getSession(); + Session session = currentSession(); + try { + @SuppressWarnings("unchecked") + Criteria c = session.createCriteria(Program.class); + if (!"Any".equals(programStatus)) { + c.add(Restrictions.eq("programStatus", programStatus)); + } + if (!"Any".equals(type)) { + c.add(Restrictions.eq("type", type)); + } + if (facilityId > 0) { + c.add(Restrictions.eq("facilityId", facilityId)); + } + return c.list(); + } finally { + // releaseSession(session); + //session.close(); + + } + } + + /** + * This method doesn't work, it doesn't find all programs, it only finds all + * community programs. See findAll instead. + * + * @deprecated 2013-12-09 don't use this anymore it's misleading + */ + @Override + public List getPrograms() { + String queryStr = "FROM Program p WHERE p.type != '" + Program.COMMUNITY_TYPE + "' ORDER BY p.name"; + + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr); + + return rs; + } + + /** + * This method doesn't work, it doesn't find all programs, it only finds all + * community programs. See findAll instead. + * + * @deprecated 2013-12-09 don't use this anymore it's misleading + */ + @Override + public List getActivePrograms() { + String queryStr = "FROM Program p WHERE p.type <> '" + Program.COMMUNITY_TYPE + "' and p.programStatus = '" + + Program.PROGRAM_STATUS_ACTIVE + "'"; + + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr); + + return rs; + } + + /** + * @param facilityId is allowed to be null + * @return a list of programs in the facility and any programs with no facility + * associated + */ + @Override + public List getProgramsByFacilityId(Integer facilityId) { + String queryStr = "FROM Program p WHERE (p.facilityId = " + facilityId + + " or p.facilityId is null) ORDER BY p.name"; + + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr); + + return rs; + } + + @Override + public List getProgramsByFacilityIdAndFunctionalCentreId(Integer facilityId, String functionalCentreId) { + String queryStr = "FROM Program p WHERE p.facilityId = " + facilityId + " and p.functionalCentreId = '" + + functionalCentreId + '\''; + + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr); + + return rs; + } + + /** + * @param facilityId is allowed to be null + * @return a list of community programs in the facility and any programs with no + * facility associated + */ + @Override + public List getCommunityProgramsByFacilityId(Integer facilityId) { + String queryStr = "FROM Program p WHERE (p.facilityId = " + facilityId + + " or p.facilityId is null) AND p.type != '" + Program.COMMUNITY_TYPE + "' ORDER BY p.name"; + + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate().find(queryStr); + + return rs; + } + + /** + * results are ordered by name + * + * @param facilityId can be null for all, but generally shouldn't be + * @param active can be null for both + */ + @Override + public List getProgramsByType(Integer facilityId, String type, Boolean active) { + StringBuilder sqlCommand = new StringBuilder("FROM Program p WHERE p.type = '" + type + "'"); + + if (facilityId != null) + sqlCommand.append(" and p.facilityId = " + facilityId); + if (active != null) + sqlCommand.append(" and p.programStatus='" + + (active ? Program.PROGRAM_STATUS_ACTIVE : Program.PROGRAM_STATUS_INACTIVE) + "'"); + + sqlCommand.append(" ORDER BY p.name"); + + @SuppressWarnings("unchecked") + List list = (List) getHibernateTemplate().find(sqlCommand.toString()); + return (list); + } + + @Override + public List getProgramByGenderType(String genderType) { + // yeah I know, it's not safe to insert random strings and it's also + // inefficient, but unless I fix all the hibernate calls I'm following + // convention of + // using the hibernate templates and just inserting random strings for now. + @SuppressWarnings("unchecked") + List rs = (List) getHibernateTemplate() + .find("FROM Program p WHERE p.manOrWoman = '" + genderType + "'"); + return rs; + } + + @Override + public void saveProgram(Program program) { + if (program == null) { + throw new IllegalArgumentException(); + } + program.setLastUpdateDate(new Date()); + + // Adjusting flush mode + Session session = currentSession(); + FlushMode previousFlushMode = session.getFlushMode(); + session.setFlushMode(FlushMode.COMMIT); + + try { + getHibernateTemplate().saveOrUpdate(program); + } finally { + session.setFlushMode(previousFlushMode); // Restore the original flush mode + } + getHibernateTemplate().saveOrUpdate(program); + + if (log.isDebugEnabled()) { + log.debug("saveProgram: " + program.getId()); + } + } + + @Override + public void removeProgram(Integer programId) { + if (programId == null || programId <= 0) { + throw new IllegalArgumentException(); + } + try { + Object program = getHibernateTemplate().load(Program.class, programId); + + getHibernateTemplate().delete(program); + + if (log.isDebugEnabled()) { + log.debug("deleteProgram: " + programId); + } + } catch (Exception e) { + MiscUtils.getLogger().warn("Unable to delete program " + programId); + } + } + + @Override + public List search(Program program) { + if (program == null) { + throw new IllegalArgumentException(); + } + // Session session = getSession(); + Session session = currentSession(); + Criteria criteria = session.createCriteria(Program.class); + + if (program.getName() != null && program.getName().length() > 0) { + String programName = StringEscapeUtils.escapeSql(program.getName()); + String sql = ""; + sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4))" + " " + "OR (name like '" + "%" + + programName + "%'))"; + criteria.add(Restrictions.sqlRestriction(sql)); + } + + if (program.getType() != null && program.getType().length() > 0) { + criteria.add(Expression.eq("type", program.getType())); + } + + if (program.getType() == null || program.getType().equals("") || !program.getType().equals("community")) { + criteria.add(Expression.ne("type", "community")); + } + + criteria.add(Expression.eq("programStatus", Program.PROGRAM_STATUS_ACTIVE)); + + if (program.getManOrWoman() != null && program.getManOrWoman().length() > 0) { + criteria.add(Expression.eq("manOrWoman", program.getManOrWoman())); + } + + if (program.isTransgender()) { + criteria.add(Expression.eq("transgender", true)); + } + + if (program.isFirstNation()) { + criteria.add(Expression.eq("firstNation", true)); + } + + if (program.isBedProgramAffiliated()) { + criteria.add(Expression.eq("bedProgramAffiliated", true)); + } + + if (program.isAlcohol()) { + criteria.add(Expression.eq("alcohol", true)); + } + + if (program.getAbstinenceSupport() != null && program.getAbstinenceSupport().length() > 0) { + criteria.add(Expression.eq("abstinenceSupport", program.getAbstinenceSupport())); + } + + if (program.isPhysicalHealth()) { + criteria.add(Expression.eq("physicalHealth", true)); + } + + if (program.isHousing()) { + criteria.add(Expression.eq("housing", true)); + } + + if (program.isMentalHealth()) { + criteria.add(Expression.eq("mentalHealth", true)); + } + criteria.addOrder(Order.asc("name")); + + List results = new ArrayList(); + try { + results = criteria.list(); + } finally { + // this.releaseSession(session); + //session.close(); + } + + if (log.isDebugEnabled()) { + log.debug("search: # results: " + results.size()); + } + + return results; + } + + @Override + public List searchByFacility(Program program, Integer facilityId) { + if (program == null) { + throw new IllegalArgumentException(); + } + if (facilityId == null) { + throw new IllegalArgumentException(); + } + + boolean isOracle = OscarProperties.getInstance().getDbType().equals("oracle"); + // Session session = getSession(); + Session session = currentSession(); + Criteria criteria = session.createCriteria(Program.class); + + if (program.getName() != null && program.getName().length() > 0) { + String programName = StringEscapeUtils.escapeSql(program.getName()); + String sql = ""; + if (isOracle) { + sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4)))"; + criteria.add(Restrictions.or(Restrictions.ilike("name", "%" + programName + "%"), + Restrictions.sqlRestriction(sql))); + } else { + sql = "((LEFT(SOUNDEX(name),4) = LEFT(SOUNDEX('" + programName + "'),4))" + " " + "OR (name like '" + + "%" + programName + "%'))"; + criteria.add(Restrictions.sqlRestriction(sql)); + } + } + + if (program.getType() != null && program.getType().length() > 0) { + criteria.add(Expression.eq("type", program.getType())); + } + + if (program.getType() == null || program.getType().equals("") + || !program.getType().equals(Program.COMMUNITY_TYPE)) { + criteria.add(Expression.ne("type", Program.COMMUNITY_TYPE)); + } + + criteria.add(Expression.eq("programStatus", Program.PROGRAM_STATUS_ACTIVE)); + + if (program.getManOrWoman() != null && program.getManOrWoman().length() > 0) { + criteria.add(Expression.eq("manOrWoman", program.getManOrWoman())); + } + + if (program.isTransgender()) { + criteria.add(Expression.eq("transgender", true)); + } + + if (program.isFirstNation()) { + criteria.add(Expression.eq("firstNation", true)); + } + + if (program.isBedProgramAffiliated()) { + criteria.add(Expression.eq("bedProgramAffiliated", true)); + } + + if (program.isAlcohol()) { + criteria.add(Expression.eq("alcohol", true)); + } + + if (program.getAbstinenceSupport() != null && program.getAbstinenceSupport().length() > 0) { + criteria.add(Expression.eq("abstinenceSupport", program.getAbstinenceSupport())); + } + + if (program.isPhysicalHealth()) { + criteria.add(Expression.eq("physicalHealth", true)); + } + + if (program.isHousing()) { + criteria.add(Expression.eq("housing", true)); + } + + if (program.isMentalHealth()) { + criteria.add(Expression.eq("mentalHealth", true)); + } + + criteria.add(Expression.eq("facilityId", facilityId)); + + criteria.addOrder(Order.asc("name")); + + List results = new ArrayList(); + try { + results = criteria.list(); + } finally { + // releaseSession(session); + //session.close(); + } + + if (log.isDebugEnabled()) { + log.debug("search: # results: " + results.size()); + } + + return results; + } + + @Override + public void resetHoldingTank() { + List programs = this.getAllPrograms(); + for (Program p : programs) { + if (p.getHoldingTank()) { + p.setHoldingTank(false); + this.saveProgram(p); + } + + } + + if (log.isDebugEnabled()) { + log.debug("resetHoldingTank:"); + } + } + + @Override + public Program getHoldingTankProgram() { + Program result = null; + + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate() + .find("from Program p where p.holdingTank = true"); + + if (!results.isEmpty()) { + result = results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug((result != null) ? "getHoldingTankProgram: program: " + result.getId() + : "getHoldingTankProgram: none found"); + } + + return result; + } + + @Override + public boolean programExists(Integer programId) { + return (getProgram(programId) != null); + } + + public List getLinkedServicePrograms(Integer bedProgramId, Integer clientId) { + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate().find( + "select p from Admission a,Program p where a.programId = p.id and p.type='" + Program.SERVICE_TYPE + + "' and p.bedProgramLinkId = ? and a.clientId=?", + new Object[] { bedProgramId, clientId }); + return results; + } + + @Override + public boolean isInSameFacility(Integer programId1, Integer programId2) { + if (programId1 == null || programId1 <= 0) { + throw new IllegalArgumentException(); + } + + if (programId2 == null || programId2 <= 0) { + throw new IllegalArgumentException(); + } + + Program p1 = getProgram(programId1); + Program p2 = getProgram(programId2); + + if (p1 == null || p2 == null) + return false; + + return (p1.getFacilityId() == p2.getFacilityId()); + } + + @Override + public Program getProgramBySiteSpecificField(String value) { + Program result = null; + + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate() + .find("from Program p where p.siteSpecificField = ?", new Object[] { value }); + + if (!results.isEmpty()) { + result = results.get(0); + } + + return result; + } + + @Override + public Program getProgramByName(String value) { + Program result = null; + + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate().find("from Program p where p.name = ?", + new Object[] { value }); + + if (!results.isEmpty()) { + result = results.get(0); + } + + return result; + } + + @Override + public List getRecordsAddedAndUpdatedSinceTime(Integer facilityId, Date date) { + @SuppressWarnings("unchecked") + List programs = (List) getHibernateTemplate().find( + "select distinct p.id From Program p where p.facilityId = ? and p.lastUpdateDate > ? ", facilityId, + date); + + return programs; + } + + @Override + public List getRecordsByFacilityId(Integer facilityId) { + @SuppressWarnings("unchecked") + List programs = (List) getHibernateTemplate() + .find("select distinct p.id From Program p where p.facilityId = ? ", facilityId); + + return programs; + } + + @Override + public List getRecordsAddedAndUpdatedSinceTime(Date date) { + @SuppressWarnings("unchecked") + List providers = (List) getHibernateTemplate() + .find("select distinct p.ProviderNo From Provider p where p.lastUpdateDate > ? ", date); + + return providers; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAO.java index c3c6dea5db..e037f92f3a 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -32,138 +35,27 @@ import org.oscarehr.PMmodule.model.FunctionalUserType; import org.oscarehr.PMmodule.model.ProgramFunctionalUser; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramFunctionalUserDAO extends HibernateDaoSupport { - - private static Logger log = MiscUtils.getLogger(); - - public List getFunctionalUserTypes() { - List results = this.getHibernateTemplate().find("from FunctionalUserType"); - - if (log.isDebugEnabled()) { - log.debug("getFunctionalUserTypes: # of results=" + results.size()); - } - return results; - } - - public FunctionalUserType getFunctionalUserType(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - FunctionalUserType result = this.getHibernateTemplate().get(FunctionalUserType.class, id); - - if (log.isDebugEnabled()) { - log.debug("getFunctionalUserType: id=" + id + ",found=" + (result != null)); - } - - return result; - } - - public void saveFunctionalUserType(FunctionalUserType fut) { - if (fut == null) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().saveOrUpdate(fut); - - if (log.isDebugEnabled()) { - log.debug("saveFunctionalUserType:" + fut.getId()); - } - } - - public void deleteFunctionalUserType(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().delete(getFunctionalUserType(id)); - - if (log.isDebugEnabled()) { - log.debug("deleteFunctionalUserType:" + id); - } - } - - public List getFunctionalUsers(Long programId) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - List results = this.getHibernateTemplate().find("from ProgramFunctionalUser pfu where pfu.ProgramId = ?", programId); - - if (log.isDebugEnabled()) { - log.debug("getFunctionalUsers: programId=" + programId + ",# of results=" + results.size()); - } - return results; - } - - public ProgramFunctionalUser getFunctionalUser(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - ProgramFunctionalUser result = this.getHibernateTemplate().get(ProgramFunctionalUser.class, id); - - if (log.isDebugEnabled()) { - log.debug("getFunctionalUser: id=" + id + ",found=" + (result != null)); - } - - return result; - } - - public void saveFunctionalUser(ProgramFunctionalUser pfu) { - if (pfu == null) { - throw new IllegalArgumentException(); - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; - this.getHibernateTemplate().saveOrUpdate(pfu); +public interface ProgramFunctionalUserDAO { - if (log.isDebugEnabled()) { - log.debug("saveFunctionalUser:" + pfu.getId()); - } - } + public List getFunctionalUserTypes(); - public void deleteFunctionalUser(Long id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } + public FunctionalUserType getFunctionalUserType(Long id); - this.getHibernateTemplate().delete(getFunctionalUser(id)); + public void saveFunctionalUserType(FunctionalUserType fut); - if (log.isDebugEnabled()) { - log.debug("deleteFunctionalUser:" + id); - } - } + public void deleteFunctionalUserType(Long id); - public Long getFunctionalUserByUserType(Long programId, Long userTypeId) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - if (userTypeId == null || userTypeId.intValue() <= 0) { - throw new IllegalArgumentException(); - } + public List getFunctionalUsers(Long programId); - Long result = null; + public ProgramFunctionalUser getFunctionalUser(Long id); - Session session = getSession(); - Query q = session.createQuery("select pfu.ProgramId from ProgramFunctionalUser pfu where pfu.ProgramId = ? and pfu.UserTypeId = ?"); - q.setLong(0, programId.longValue()); - q.setLong(1, userTypeId.longValue()); - List results = new ArrayList(); - try { - results = q.list(); - }finally { - releaseSession(session); - } - if (results.size() > 0) { - result = (Long)results.get(0); - } + public void saveFunctionalUser(ProgramFunctionalUser pfu); - if (log.isDebugEnabled()) { - log.debug("getFunctionalUserByUserType: programId=" + programId + ",userTypeId=" + userTypeId + ",result=" + result); - } + public void deleteFunctionalUser(Long id); - return result; - } + public Long getFunctionalUserByUserType(Long programId, Long userTypeId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAOImpl.java new file mode 100644 index 0000000000..b575a37d36 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramFunctionalUserDAOImpl.java @@ -0,0 +1,195 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Query; +import org.hibernate.Session; +import org.oscarehr.PMmodule.model.FunctionalUserType; +import org.oscarehr.PMmodule.model.ProgramFunctionalUser; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +public class ProgramFunctionalUserDAOImpl extends HibernateDaoSupport implements ProgramFunctionalUserDAO { + + private static Logger log = MiscUtils.getLogger(); + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + @Override + public List getFunctionalUserTypes() { + List results = (List) this.getHibernateTemplate() + .find("from FunctionalUserType"); + + if (log.isDebugEnabled()) { + log.debug("getFunctionalUserTypes: # of results=" + results.size()); + } + return results; + } + + @Override + public FunctionalUserType getFunctionalUserType(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + FunctionalUserType result = this.getHibernateTemplate().get(FunctionalUserType.class, id); + + if (log.isDebugEnabled()) { + log.debug("getFunctionalUserType: id=" + id + ",found=" + (result != null)); + } + + return result; + } + + @Override + public void saveFunctionalUserType(FunctionalUserType fut) { + if (fut == null) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().saveOrUpdate(fut); + + if (log.isDebugEnabled()) { + log.debug("saveFunctionalUserType:" + fut.getId()); + } + } + + @Override + public void deleteFunctionalUserType(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().delete(getFunctionalUserType(id)); + + if (log.isDebugEnabled()) { + log.debug("deleteFunctionalUserType:" + id); + } + } + + @Override + public List getFunctionalUsers(Long programId) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + List results = (List) this.getHibernateTemplate() + .find("from ProgramFunctionalUser pfu where pfu.ProgramId = ?", programId); + + if (log.isDebugEnabled()) { + log.debug("getFunctionalUsers: programId=" + programId + ",# of results=" + results.size()); + } + return results; + } + + @Override + public ProgramFunctionalUser getFunctionalUser(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramFunctionalUser result = this.getHibernateTemplate().get(ProgramFunctionalUser.class, id); + + if (log.isDebugEnabled()) { + log.debug("getFunctionalUser: id=" + id + ",found=" + (result != null)); + } + + return result; + } + + @Override + public void saveFunctionalUser(ProgramFunctionalUser pfu) { + if (pfu == null) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().saveOrUpdate(pfu); + + if (log.isDebugEnabled()) { + log.debug("saveFunctionalUser:" + pfu.getId()); + } + } + + @Override + public void deleteFunctionalUser(Long id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().delete(getFunctionalUser(id)); + + if (log.isDebugEnabled()) { + log.debug("deleteFunctionalUser:" + id); + } + } + + @Override + public Long getFunctionalUserByUserType(Long programId, Long userTypeId) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + if (userTypeId == null || userTypeId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + Long result = null; + + // Session session = getSession(); + Session session = sessionFactory.getCurrentSession(); + Query q = session.createQuery( + "select pfu.ProgramId from ProgramFunctionalUser pfu where pfu.ProgramId = ? and pfu.UserTypeId = ?"); + q.setLong(0, programId.longValue()); + q.setLong(1, userTypeId.longValue()); + List results = new ArrayList(); + try { + results = q.list(); + } finally { + // releaseSession(session); + session.close(); + } + if (results.size() > 0) { + result = (Long) results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getFunctionalUserByUserType: programId=" + programId + ",userTypeId=" + userTypeId + ",result=" + + result); + } + + return result; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAO.java index dc5d12c911..f220e26634 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -32,280 +35,45 @@ import org.oscarehr.common.model.Facility; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.QueueCache; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramProviderDAO extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - private static QueueCache> programProviderByProviderProgramIdCache = new QueueCache>(4, 100, DateUtils.MILLIS_PER_HOUR, null); - - private static String makeCacheKey(String providerNo, Long programId) - { - return(providerNo+':'+programId); - } - - @SuppressWarnings("unchecked") - public List getProgramProviderByProviderProgramId(String providerNo, Long programId) { - String cacheKey=makeCacheKey(providerNo, programId); - - List results = programProviderByProviderProgramIdCache.get(cacheKey); - - if (results==null) - { - String q = "select pp from ProgramProvider pp where pp.ProgramId=? and pp.ProviderNo=?"; - results=getHibernateTemplate().find(q, new Object[] {programId, providerNo}); - if (results != null) programProviderByProviderProgramIdCache.put(cacheKey, results); - } - - return results; - } - - @SuppressWarnings("unchecked") - public List getAllProgramProviders() { - return getHibernateTemplate().find("FROM ProgramProvider"); - } - - @SuppressWarnings("unchecked") - public List getProgramProviderByProviderNo(String providerNo) { - String q = "select pp from ProgramProvider pp where pp.ProviderNo=?"; - return getHibernateTemplate().find(q, providerNo); - } - - public List getProgramProviders(Long programId) { - if (programId == null || programId.intValue() < 0) { - throw new IllegalArgumentException(); - } - - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from ProgramProvider pp where pp.ProgramId = ?", programId); - - if (log.isDebugEnabled()) { - log.debug("getProgramProviders: programId=" + programId + ",# of results=" + results.size()); - } - return results; - } - - public List getProgramProvidersByProvider(String providerNo) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } - - List results = this.getHibernateTemplate().find("from ProgramProvider pp where pp.ProviderNo = ?", providerNo); - - if (log.isDebugEnabled()) { - log.debug("getProgramProvidersByProvider: providerNo=" + providerNo + ",# of results=" + results.size()); - } - return results; - } - - public List getProgramProvidersByProviderAndFacility(String providerNo, Integer facilityId) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } - - String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId in " + - "(select s.id from Program s where s.facilityId=? or s.facilityId is null)"; - List results = getHibernateTemplate().find(queryStr, new Object[] { providerNo, facilityId }); - - if (log.isDebugEnabled()) { - log.debug("getProgramProvidersByProviderAndFacility: providerNo=" + providerNo + ",# of results=" + results.size()); - } - return results; - } - - public ProgramProvider getProgramProvider(Long id) { - if (id == null || id.intValue() < 0) { - throw new IllegalArgumentException(); - } - - ProgramProvider result = this.getHibernateTemplate().get(ProgramProvider.class, id); - - if (log.isDebugEnabled()) { - log.debug("getProgramProvider: id=" + id + ",found=" + (result != null)); - } - - return result; - } - - public ProgramProvider getProgramProvider(String providerNo, Long programId) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - ProgramProvider result = null; - List results = this.getHibernateTemplate().find("from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ?", new Object[] { providerNo, programId }); - if (!results.isEmpty()) { - result = (ProgramProvider) results.get(0); - } - - if (log.isDebugEnabled()) { - log.debug("getProgramProvider: providerNo=" + providerNo + ",programId=" + programId + ",found=" + (result != null)); - } - - return result; - } - - public ProgramProvider getProgramProvider(String providerNo, long programId, long roleId) { - - ProgramProvider result = null; - - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ? and pp.RoleId=?", new Object[] { providerNo, programId, roleId }); - - if (!results.isEmpty()) { - result = results.get(0); - } - - return result; - } - - public void saveProgramProvider(ProgramProvider pp) { - if (pp == null) { - throw new IllegalArgumentException(); - } - - programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); - getHibernateTemplate().saveOrUpdate(pp); - - if (log.isDebugEnabled()) { - log.debug("saveProgramProvider: id=" + pp.getId()); - } - - } - - public void deleteProgramProvider(Long id) { - if (id == null || id.intValue() < 0) { - throw new IllegalArgumentException(); - } - - ProgramProvider pp = getProgramProvider(id); - if (pp != null) { - programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); - getHibernateTemplate().delete(pp); - } - - if (log.isDebugEnabled()) { - log.debug("deleteProgramProvider id=" + id); - } - } - - public void deleteProgramProviderByProgramId(Long programId) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - List o = getProgramProviders(programId); - if (o != null) { - Iterator it = o.iterator(); - while (it.hasNext()) { - ProgramProvider pp = (ProgramProvider) it.next(); - programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); - getHibernateTemplate().delete(pp); - } - } - - if (log.isDebugEnabled()) { - log.debug("deleteProgramProvider programId=" + programId); - } - } - - public List getProgramProvidersInTeam(Integer programId, Integer teamId) { - if (programId == null || programId <= 0) { - throw new IllegalArgumentException(); - } - if (teamId == null || teamId <= 0) { - throw new IllegalArgumentException(); - } - Long pId = programId.longValue(); - - List results = this.getHibernateTemplate().find("select pp from ProgramProvider pp left join pp.teams as team where pp.ProgramId = ? and team.id = ?", new Object[] {pId, teamId}); - - if (log.isDebugEnabled()) { - log.debug("getProgramProvidersInTeam: programId=" + programId + ",teamId=" + teamId + ",# of results=" + results.size()); - } - - return results; - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +public interface ProgramProviderDAO { + public List getProgramProviderByProviderProgramId(String providerNo, Long programId); - @SuppressWarnings("unchecked") - public List getProgramDomain(String providerNo) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } + public List getAllProgramProviders(); - List results = this.getHibernateTemplate().find("from ProgramProvider pp where pp.ProviderNo = ?", providerNo); + public List getProgramProviderByProviderNo(String providerNo); - if (log.isDebugEnabled()) { - log.debug("getProgramDomain: providerNo=" + providerNo + ",# of results=" + results.size()); - } - return results; - } + public List getProgramProviders(Long programId); - public List getActiveProgramDomain(String providerNo) { - if (providerNo == null || Long.valueOf(providerNo) == null) { - throw new IllegalArgumentException(); - } + public List getProgramProvidersByProvider(String providerNo); - List results = this.getHibernateTemplate().find("select pp from ProgramProvider pp, Program p where pp.ProgramId=p.id and p.programStatus='active' and pp.ProviderNo = ?", providerNo); + public List getProgramProvidersByProviderAndFacility(String providerNo, Integer facilityId); - if (log.isDebugEnabled()) { - log.debug("getProgramDomain: providerNo=" + providerNo + ",# of results=" + results.size()); - } - return results; - } + public ProgramProvider getProgramProvider(Long id); - public List getProgramDomainByFacility(String providerNo, Integer facilityId) { - if (providerNo == null || Long.valueOf(providerNo) == null) { - throw new IllegalArgumentException(); - } + public ProgramProvider getProgramProvider(String providerNo, Long programId); - String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId in " + - "(select s.id from Program s where s.facilityId=? or s.facilityId is null)"; - List results = getHibernateTemplate().find(queryStr, new Object[] { providerNo, facilityId }); + public ProgramProvider getProgramProvider(String providerNo, long programId, long roleId); - if (log.isDebugEnabled()) { - log.debug("getProgramDomainByFacility: providerNo=" + providerNo + ",# of results=" + results.size()); - } - return results; - } + public void saveProgramProvider(ProgramProvider pp); - public boolean isThisProgramInProgramDomain(String providerNo, Integer programId) - { - if (providerNo == null || Long.valueOf(providerNo) == null) - { - throw new IllegalArgumentException(); - } + public void deleteProgramProvider(Long id); - String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ?"; - List results = getHibernateTemplate().find(queryStr, new Object[]{providerNo, Long.valueOf(programId.longValue())}); - if(results!=null && results.size()>0) { - return true; - } else { - return false; - } + public void deleteProgramProviderByProgramId(Long programId); - } + public List getProgramProvidersInTeam(Integer programId, Integer teamId); + public List getProgramDomain(String providerNo); - @SuppressWarnings("unchecked") - public List getFacilitiesInProgramDomain(String providerNo) { - if (providerNo == null || Long.valueOf(providerNo) == null) { - throw new IllegalArgumentException(); - } - List results = this.getHibernateTemplate().find("select distinct f from Facility f, Room r, ProgramProvider pp where pp.ProgramId = r.programId and f.id = r.facilityId and pp.ProviderNo = ?", providerNo); + public List getActiveProgramDomain(String providerNo); - return results; - } + public List getProgramDomainByFacility(String providerNo, Integer facilityId); + public boolean isThisProgramInProgramDomain(String providerNo, Integer programId); + public List getFacilitiesInProgramDomain(String providerNo); - public void updateProviderRoles(Long providerId, Long roleId) { - getHibernateTemplate().bulkUpdate("UPDATE ProgramProvider pp SET pp.RoleId = ? WHERE pp.Id = ?", new Object[] { roleId, providerId }); - } + public void updateProviderRoles(Long providerId, Long roleId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAOImpl.java new file mode 100644 index 0000000000..c1f27f4808 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramProviderDAOImpl.java @@ -0,0 +1,343 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.lang.time.DateUtils; +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.ProgramProvider; +import org.oscarehr.common.model.Facility; +import org.oscarehr.util.MiscUtils; +import org.oscarehr.util.QueueCache; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class ProgramProviderDAOImpl extends HibernateDaoSupport implements ProgramProviderDAO { + + private Logger log = MiscUtils.getLogger(); + + private static QueueCache> programProviderByProviderProgramIdCache = new QueueCache>( + 4, 100, DateUtils.MILLIS_PER_HOUR, null); + + private static String makeCacheKey(String providerNo, Long programId) { + return (providerNo + ':' + programId); + } + + @SuppressWarnings("unchecked") + @Override + public List getProgramProviderByProviderProgramId(String providerNo, Long programId) { + String cacheKey = makeCacheKey(providerNo, programId); + + List results = programProviderByProviderProgramIdCache.get(cacheKey); + + if (results == null) { + String q = "select pp from ProgramProvider pp where pp.ProgramId=? and pp.ProviderNo=?"; + results = (List) getHibernateTemplate().find(q, new Object[] { programId, providerNo }); + if (results != null) + programProviderByProviderProgramIdCache.put(cacheKey, results); + } + + return results; + } + + @SuppressWarnings("unchecked") + @Override + public List getAllProgramProviders() { + return (List) getHibernateTemplate().find("FROM ProgramProvider"); + } + + @SuppressWarnings("unchecked") + @Override + public List getProgramProviderByProviderNo(String providerNo) { + String q = "select pp from ProgramProvider pp where pp.ProviderNo=?"; + return (List) getHibernateTemplate().find(q, providerNo); + } + + @Override + public List getProgramProviders(Long programId) { + if (programId == null || programId.intValue() < 0) { + throw new IllegalArgumentException(); + } + + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate() + .find("from ProgramProvider pp where pp.ProgramId = ?", programId); + + if (log.isDebugEnabled()) { + log.debug("getProgramProviders: programId=" + programId + ",# of results=" + results.size()); + } + return results; + } + + @Override + public List getProgramProvidersByProvider(String providerNo) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + + List results = (List) this.getHibernateTemplate() + .find("from ProgramProvider pp where pp.ProviderNo = ?", providerNo); + + if (log.isDebugEnabled()) { + log.debug("getProgramProvidersByProvider: providerNo=" + providerNo + ",# of results=" + results.size()); + } + return results; + } + + @Override + public List getProgramProvidersByProviderAndFacility(String providerNo, Integer facilityId) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + + String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId in " + + "(select s.id from Program s where s.facilityId=? or s.facilityId is null)"; + List results = getHibernateTemplate().find(queryStr, new Object[] { providerNo, facilityId }); + + if (log.isDebugEnabled()) { + log.debug("getProgramProvidersByProviderAndFacility: providerNo=" + providerNo + ",# of results=" + + results.size()); + } + return results; + } + + @Override + public ProgramProvider getProgramProvider(Long id) { + if (id == null || id.intValue() < 0) { + throw new IllegalArgumentException(); + } + + ProgramProvider result = this.getHibernateTemplate().get(ProgramProvider.class, id); + + if (log.isDebugEnabled()) { + log.debug("getProgramProvider: id=" + id + ",found=" + (result != null)); + } + + return result; + } + + @Override + public ProgramProvider getProgramProvider(String providerNo, Long programId) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramProvider result = null; + List results = this.getHibernateTemplate().find( + "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ?", + new Object[] { providerNo, programId }); + if (!results.isEmpty()) { + result = (ProgramProvider) results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getProgramProvider: providerNo=" + providerNo + ",programId=" + programId + ",found=" + + (result != null)); + } + + return result; + } + + @Override + public ProgramProvider getProgramProvider(String providerNo, long programId, long roleId) { + + ProgramProvider result = null; + + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate().find( + "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ? and pp.RoleId=?", + new Object[] { providerNo, programId, roleId }); + + if (!results.isEmpty()) { + result = results.get(0); + } + + return result; + } + + @Override + public void saveProgramProvider(ProgramProvider pp) { + if (pp == null) { + throw new IllegalArgumentException(); + } + + programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); + getHibernateTemplate().saveOrUpdate(pp); + + if (log.isDebugEnabled()) { + log.debug("saveProgramProvider: id=" + pp.getId()); + } + + } + + @Override + public void deleteProgramProvider(Long id) { + if (id == null || id.intValue() < 0) { + throw new IllegalArgumentException(); + } + + ProgramProvider pp = getProgramProvider(id); + if (pp != null) { + programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); + getHibernateTemplate().delete(pp); + } + + if (log.isDebugEnabled()) { + log.debug("deleteProgramProvider id=" + id); + } + } + + @Override + public void deleteProgramProviderByProgramId(Long programId) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + List o = getProgramProviders(programId); + if (o != null) { + Iterator it = o.iterator(); + while (it.hasNext()) { + ProgramProvider pp = (ProgramProvider) it.next(); + programProviderByProviderProgramIdCache.remove(makeCacheKey(pp.getProviderNo(), pp.getProgramId())); + getHibernateTemplate().delete(pp); + } + } + + if (log.isDebugEnabled()) { + log.debug("deleteProgramProvider programId=" + programId); + } + } + + @Override + public List getProgramProvidersInTeam(Integer programId, Integer teamId) { + if (programId == null || programId <= 0) { + throw new IllegalArgumentException(); + } + if (teamId == null || teamId <= 0) { + throw new IllegalArgumentException(); + } + Long pId = programId.longValue(); + + List results = (List) this.getHibernateTemplate().find( + "select pp from ProgramProvider pp left join pp.teams as team where pp.ProgramId = ? and team.id = ?", + new Object[] { pId, teamId }); + + if (log.isDebugEnabled()) { + log.debug("getProgramProvidersInTeam: programId=" + programId + ",teamId=" + teamId + ",# of results=" + + results.size()); + } + + return results; + } + + @SuppressWarnings("unchecked") + @Override + public List getProgramDomain(String providerNo) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + + List results = this.getHibernateTemplate().find("from ProgramProvider pp where pp.ProviderNo = ?", providerNo); + + if (log.isDebugEnabled()) { + log.debug("getProgramDomain: providerNo=" + providerNo + ",# of results=" + results.size()); + } + return results; + } + + @Override + public List getActiveProgramDomain(String providerNo) { + if (providerNo == null || Long.valueOf(providerNo) == null) { + throw new IllegalArgumentException(); + } + + List results = this.getHibernateTemplate().find( + "select pp from ProgramProvider pp, Program p where pp.ProgramId=p.id and p.programStatus='active' and pp.ProviderNo = ?", + providerNo); + + if (log.isDebugEnabled()) { + log.debug("getProgramDomain: providerNo=" + providerNo + ",# of results=" + results.size()); + } + return results; + } + + @Override + public List getProgramDomainByFacility(String providerNo, Integer facilityId) { + if (providerNo == null || Long.valueOf(providerNo) == null) { + throw new IllegalArgumentException(); + } + + String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId in " + + "(select s.id from Program s where s.facilityId=? or s.facilityId is null)"; + List results = getHibernateTemplate().find(queryStr, new Object[] { providerNo, facilityId }); + + if (log.isDebugEnabled()) { + log.debug("getProgramDomainByFacility: providerNo=" + providerNo + ",# of results=" + results.size()); + } + return results; + } + + @Override + public boolean isThisProgramInProgramDomain(String providerNo, Integer programId) { + if (providerNo == null || Long.valueOf(providerNo) == null) { + throw new IllegalArgumentException(); + } + + String queryStr = "from ProgramProvider pp where pp.ProviderNo = ? and pp.ProgramId = ?"; + List results = getHibernateTemplate().find(queryStr, + new Object[] { providerNo, Long.valueOf(programId.longValue()) }); + if (results != null && results.size() > 0) { + return true; + } else { + return false; + } + + } + + @SuppressWarnings("unchecked") + @Override + public List getFacilitiesInProgramDomain(String providerNo) { + if (providerNo == null || Long.valueOf(providerNo) == null) { + throw new IllegalArgumentException(); + } + List results = this.getHibernateTemplate().find( + "select distinct f from Facility f, Room r, ProgramProvider pp where pp.ProgramId = r.programId and f.id = r.facilityId and pp.ProviderNo = ?", + providerNo); + + return results; + } + + @Override + public void updateProviderRoles(Long providerId, Long roleId) { + getHibernateTemplate().bulkUpdate("UPDATE ProgramProvider pp SET pp.RoleId = ? WHERE pp.Id = ?", + new Object[] { roleId, providerId }); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDao.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDao.java index 1de20286f0..08328dfc39 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -28,112 +31,18 @@ import org.apache.logging.log4j.Logger; import org.oscarehr.PMmodule.model.ProgramQueue; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramQueueDao extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - - public ProgramQueue getProgramQueue(Long queueId) { - if (queueId == null || queueId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - ProgramQueue result = getHibernateTemplate().get(ProgramQueue.class, queueId); - - if (log.isDebugEnabled()) { - log.debug("getProgramQueue: queueId=" + queueId + ",found=" + (result != null)); - } - - return result; - } - - public List getProgramQueuesByProgramId(Long programId) { - if (programId == null) { - throw new IllegalArgumentException(); - } - - String queryStr = " FROM ProgramQueue q WHERE q.ProgramId=? ORDER BY q.Id "; - List results = getHibernateTemplate().find(queryStr, programId); - - if (log.isDebugEnabled()) { - log.debug("getProgramQueue: programId=" + programId + ",# of results=" + results.size()); - } - - return results; - } - - public List getActiveProgramQueuesByProgramId(Long programId) { - if (programId == null) { - throw new IllegalArgumentException(); - } - - List results = this.getHibernateTemplate().find("from ProgramQueue pq where pq.ProgramId = ? and pq.Status = 'active' order by pq.ReferralDate", Long.valueOf(programId)); - - if (log.isDebugEnabled()) { - log.debug("getActiveProgramQueuesByProgramId: programId=" + programId + ",# of results=" + results.size()); - } - - return results; - } - - public void saveProgramQueue(ProgramQueue programQueue) { - if (programQueue == null) { - return; - } - - getHibernateTemplate().saveOrUpdate(programQueue); - - if (log.isDebugEnabled()) { - log.debug("saveProgramQueue: id=" + programQueue.getId()); - } - - } - - public ProgramQueue getQueue(Long programId, Long clientId) { - if (programId == null) { - throw new IllegalArgumentException(); - } - if (clientId == null) { - throw new IllegalArgumentException(); - } - - ProgramQueue result = null; - List results = this.getHibernateTemplate().find("from ProgramQueue pq where pq.ProgramId = ? and pq.ClientId = ?", - new Object[]{Long.valueOf(programId), Long.valueOf(clientId)}); - - if (!results.isEmpty()) { - result = (ProgramQueue) results.get(0); - } - - if (log.isDebugEnabled()) { - log.debug("getQueue: programId=" + programId + ",clientId=" + clientId + ",found=" + (result != null)); - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; - return result; - } +public interface ProgramQueueDao { + public ProgramQueue getProgramQueue(Long queueId); - public ProgramQueue getActiveProgramQueue(Long programId, Long demographicNo) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - if (demographicNo == null || demographicNo.intValue() <= 0) { - throw new IllegalArgumentException(); - } + public List getProgramQueuesByProgramId(Long programId); - ProgramQueue result = null; + public List getActiveProgramQueuesByProgramId(Long programId); - List results = this.getHibernateTemplate().find("from ProgramQueue pq where pq.ProgramId = ? and pq.ClientId = ? and pq.Status='active'", - new Object[]{programId, demographicNo}); - if (!results.isEmpty()) { - result = (ProgramQueue) results.get(0); - } + public void saveProgramQueue(ProgramQueue programQueue); - if (log.isDebugEnabled()) { - log.debug("getActiveProgramQueue: programId=" + programId + ",demogaphicNo=" + demographicNo + ",found=" + (result != null)); - } + public ProgramQueue getQueue(Long programId, Long clientId); - return result; - } + public ProgramQueue getActiveProgramQueue(Long programId, Long demographicNo); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDaoImpl.java new file mode 100644 index 0000000000..8f69914b13 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramQueueDaoImpl.java @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.ProgramQueue; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class ProgramQueueDaoImpl extends HibernateDaoSupport implements ProgramQueueDao { + + private Logger log = MiscUtils.getLogger(); + + @Override + public ProgramQueue getProgramQueue(Long queueId) { + if (queueId == null || queueId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramQueue result = getHibernateTemplate().get(ProgramQueue.class, queueId); + + if (log.isDebugEnabled()) { + log.debug("getProgramQueue: queueId=" + queueId + ",found=" + (result != null)); + } + + return result; + } + + @Override + public List getProgramQueuesByProgramId(Long programId) { + if (programId == null) { + throw new IllegalArgumentException(); + } + + String queryStr = " FROM ProgramQueue q WHERE q.ProgramId=? ORDER BY q.Id "; + List results = getHibernateTemplate().find(queryStr, programId); + + if (log.isDebugEnabled()) { + log.debug("getProgramQueue: programId=" + programId + ",# of results=" + results.size()); + } + + return results; + } + + @Override + public List getActiveProgramQueuesByProgramId(Long programId) { + if (programId == null) { + throw new IllegalArgumentException(); + } + + List results = this.getHibernateTemplate().find( + "from ProgramQueue pq where pq.ProgramId = ? and pq.Status = 'active' order by pq.ReferralDate", + Long.valueOf(programId)); + + if (log.isDebugEnabled()) { + log.debug("getActiveProgramQueuesByProgramId: programId=" + programId + ",# of results=" + results.size()); + } + + return results; + } + + @Override + public void saveProgramQueue(ProgramQueue programQueue) { + if (programQueue == null) { + return; + } + + getHibernateTemplate().saveOrUpdate(programQueue); + + if (log.isDebugEnabled()) { + log.debug("saveProgramQueue: id=" + programQueue.getId()); + } + + } + + @Override + public ProgramQueue getQueue(Long programId, Long clientId) { + if (programId == null) { + throw new IllegalArgumentException(); + } + if (clientId == null) { + throw new IllegalArgumentException(); + } + + ProgramQueue result = null; + List results = this.getHibernateTemplate().find( + "from ProgramQueue pq where pq.ProgramId = ? and pq.ClientId = ?", + new Object[] { Long.valueOf(programId), Long.valueOf(clientId) }); + + if (!results.isEmpty()) { + result = (ProgramQueue) results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getQueue: programId=" + programId + ",clientId=" + clientId + ",found=" + (result != null)); + } + + return result; + } + + @Override + public ProgramQueue getActiveProgramQueue(Long programId, Long demographicNo) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + if (demographicNo == null || demographicNo.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramQueue result = null; + + List results = this.getHibernateTemplate().find( + "from ProgramQueue pq where pq.ProgramId = ? and pq.ClientId = ? and pq.Status='active'", + new Object[] { programId, demographicNo }); + if (!results.isEmpty()) { + result = (ProgramQueue) results.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getActiveProgramQueue: programId=" + programId + ",demogaphicNo=" + demographicNo + ",found=" + + (result != null)); + } + + return result; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDao.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDao.java index b1725defd5..f3de064ed0 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -29,55 +32,13 @@ import org.apache.logging.log4j.Logger; import org.oscarehr.PMmodule.model.ProgramSignature; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramSignatureDao extends HibernateDaoSupport { - - private static final Logger log=MiscUtils.getLogger(); - - //get the creator of the program - public ProgramSignature getProgramFirstSignature(Integer programId) { - ProgramSignature programSignature = null; - if (programId == null || programId.intValue() <= 0) { - return null; - } - List ps = getHibernateTemplate().find("FROM ProgramSignature ps where ps.programId = ? ORDER BY ps.updateDate ASC", programId); - - if (!ps.isEmpty()) { - programSignature = (ProgramSignature)ps.get(0); - } - - if (log.isDebugEnabled()) { - log.debug("getProgramFirstSignature: " + ((programSignature != null)?String.valueOf(programSignature.getId()):"null")); - } - - return programSignature; - } - - public List getProgramSignatures(Integer programId) { - if (programId == null || programId.intValue() <= 0) { - return null; - } - - List rs = getHibernateTemplate().find("FROM ProgramSignature ps WHERE ps.programId = ? ORDER BY ps.updateDate ASC", programId); +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; - if (log.isDebugEnabled()) { - log.debug("getProgramSignatures: # of programs: " + rs.size()); - } - return rs; +public interface ProgramSignatureDao { - } + public ProgramSignature getProgramFirstSignature(Integer programId); - public void saveProgramSignature(ProgramSignature programSignature) { - if (programSignature == null) { - throw new IllegalArgumentException(); - } - programSignature.setUpdateDate(new Date()); - getHibernateTemplate().saveOrUpdate(programSignature); - getHibernateTemplate().flush(); + public List getProgramSignatures(Integer programId); - if (log.isDebugEnabled()) { - log.debug("saveAdmission: id= " + programSignature.getId()); - } - } + public void saveProgramSignature(ProgramSignature programSignature); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDaoImpl.java new file mode 100644 index 0000000000..68ea5b63a2 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramSignatureDaoImpl.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.oscarehr.PMmodule.dao; + + import java.util.Date; + import java.util.List; + + import org.apache.logging.log4j.Logger; + import org.oscarehr.PMmodule.model.ProgramSignature; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate3.support.HibernateDaoSupport; + + public class ProgramSignatureDaoImpl extends HibernateDaoSupport implements ProgramSignatureDao{ + + private static final Logger log=MiscUtils.getLogger(); + + //get the creator of the program + public ProgramSignature getProgramFirstSignature(Integer programId) { + ProgramSignature programSignature = null; + if (programId == null || programId.intValue() <= 0) { + return null; + } + List ps = getHibernateTemplate().find("FROM ProgramSignature ps where ps.programId = ? ORDER BY ps.updateDate ASC", programId); + + if (!ps.isEmpty()) { + programSignature = (ProgramSignature)ps.get(0); + } + + if (log.isDebugEnabled()) { + log.debug("getProgramFirstSignature: " + ((programSignature != null)?String.valueOf(programSignature.getId()):"null")); + } + + return programSignature; + } + + public List getProgramSignatures(Integer programId) { + if (programId == null || programId.intValue() <= 0) { + return null; + } + + List rs = getHibernateTemplate().find("FROM ProgramSignature ps WHERE ps.programId = ? ORDER BY ps.updateDate ASC", programId); + + if (log.isDebugEnabled()) { + log.debug("getProgramSignatures: # of programs: " + rs.size()); + } + return rs; + + } + + public void saveProgramSignature(ProgramSignature programSignature) { + if (programSignature == null) { + throw new IllegalArgumentException(); + } + programSignature.setUpdateDate(new Date()); + getHibernateTemplate().saveOrUpdate(programSignature); + getHibernateTemplate().flush(); + + if (log.isDebugEnabled()) { + log.debug("saveAdmission: id= " + programSignature.getId()); + } + } + } \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAO.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAO.java index 945f270c57..5f9e484e10 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAO.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAO.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -31,126 +34,16 @@ import org.hibernate.Session; import org.oscarehr.PMmodule.model.ProgramTeam; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class ProgramTeamDAO extends HibernateDaoSupport { - - private Logger log=MiscUtils.getLogger(); - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#teamExists(java.lang.Integer) - */ - public boolean teamExists(Integer teamId) { - boolean exists = getHibernateTemplate().get(ProgramTeam.class, teamId) != null; - log.debug("teamExists: " + exists); - - return exists; - } - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#teamNameExists(java.lang.Integer, java.lang.String) - */ - public boolean teamNameExists(Integer programId, String teamName) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - if (teamName == null || teamName.length() <= 0) { - throw new IllegalArgumentException(); - } - Session session = getSession(); - Query query = session.createQuery("select pt.id from ProgramTeam pt where pt.programId = ? and pt.name = ?"); - query.setLong(0, programId.longValue()); - query.setString(1, teamName); - - List teams = new ArrayList(); - try { - teams = query.list(); - }finally{ - this.releaseSession(session); - } - - if (log.isDebugEnabled()) { - log.debug("teamNameExists: programId = " + programId + ", teamName = " + teamName + ", result = " + !teams.isEmpty()); - } - - return !teams.isEmpty(); - } - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#getProgramTeam(java.lang.Integer) - */ - public ProgramTeam getProgramTeam(Integer id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - ProgramTeam result = this.getHibernateTemplate().get(ProgramTeam.class, id); - - if (log.isDebugEnabled()) { - log.debug("getProgramTeam: id=" + id + ",found=" + (result != null)); - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#getProgramTeams(java.lang.Integer) - */ - public List getProgramTeams(Integer programId) { - if (programId == null || programId.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - List results = this.getHibernateTemplate().find("from ProgramTeam tp where tp.programId = ?", programId); - - if (log.isDebugEnabled()) { - log.debug("getProgramTeams: programId=" + programId + ",# of results=" + results.size()); - } - - return results; - } - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#saveProgramTeam(org.oscarehr.PMmodule.model.ProgramTeam) - */ - public void saveProgramTeam(ProgramTeam team) { - if (team == null) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().saveOrUpdate(team); - - if (log.isDebugEnabled()) { - log.debug("saveProgramTeam: id=" + team.getId()); - } - } - - /* - * (non-Javadoc) - * - * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#deleteProgramTeam(java.lang.Integer) - */ - public void deleteProgramTeam(Integer id) { - if (id == null || id.intValue() <= 0) { - throw new IllegalArgumentException(); - } - - this.getHibernateTemplate().delete(getProgramTeam(id)); - - if (log.isDebugEnabled()) { - log.debug("deleteProgramTeam: id=" + id); - } - } - +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; + +public interface ProgramTeamDAO { + + public boolean teamExists(Integer teamId); + public boolean teamNameExists(Integer programId, String teamName); + public ProgramTeam getProgramTeam(Integer id); + public List getProgramTeams(Integer programId); + public void saveProgramTeam(ProgramTeam team); + public void deleteProgramTeam(Integer id); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAOImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAOImpl.java new file mode 100644 index 0000000000..edbd6dc435 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProgramTeamDAOImpl.java @@ -0,0 +1,176 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.oscarehr.PMmodule.dao; + + import java.util.ArrayList; + import java.util.List; + + import org.apache.logging.log4j.Logger; + import org.hibernate.Query; + import org.hibernate.Session; + import org.oscarehr.PMmodule.model.ProgramTeam; + import org.oscarehr.util.MiscUtils; + import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + import org.springframework.beans.factory.annotation.Autowired; + import org.hibernate.SessionFactory; + + public class ProgramTeamDAOImpl extends HibernateDaoSupport implements ProgramTeamDAO { + + private Logger log=MiscUtils.getLogger(); + public SessionFactory sessionFactory; + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + super.setSessionFactory(sessionFactory); + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#teamExists(java.lang.Integer) + */ + @Override + public boolean teamExists(Integer teamId) { + boolean exists = getHibernateTemplate().get(ProgramTeam.class, teamId) != null; + log.debug("teamExists: " + exists); + + return exists; + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#teamNameExists(java.lang.Integer, java.lang.String) + */ + @Override + public boolean teamNameExists(Integer programId, String teamName) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + if (teamName == null || teamName.length() <= 0) { + throw new IllegalArgumentException(); + } + // Session session = getSession(); + Session session = sessionFactory.getCurrentSession(); + Query query = session.createQuery("select pt.id from ProgramTeam pt where pt.programId = ? and pt.name = ?"); + query.setLong(0, programId.longValue()); + query.setString(1, teamName); + + List teams = new ArrayList(); + try { + teams = query.list(); + }finally{ + // this.releaseSession(session); + session.close(); + } + + if (log.isDebugEnabled()) { + log.debug("teamNameExists: programId = " + programId + ", teamName = " + teamName + ", result = " + !teams.isEmpty()); + } + + return !teams.isEmpty(); + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#getProgramTeam(java.lang.Integer) + */ + @Override + public ProgramTeam getProgramTeam(Integer id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + ProgramTeam result = this.getHibernateTemplate().get(ProgramTeam.class, id); + + if (log.isDebugEnabled()) { + log.debug("getProgramTeam: id=" + id + ",found=" + (result != null)); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#getProgramTeams(java.lang.Integer) + */ + @Override + public List getProgramTeams(Integer programId) { + if (programId == null || programId.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + List results = (List) this.getHibernateTemplate().find("from ProgramTeam tp where tp.programId = ?", programId); + + if (log.isDebugEnabled()) { + log.debug("getProgramTeams: programId=" + programId + ",# of results=" + results.size()); + } + + return results; + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#saveProgramTeam(org.oscarehr.PMmodule.model.ProgramTeam) + */ + @Override + public void saveProgramTeam(ProgramTeam team) { + if (team == null) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().saveOrUpdate(team); + + if (log.isDebugEnabled()) { + log.debug("saveProgramTeam: id=" + team.getId()); + } + } + + /* + * (non-Javadoc) + * + * @see org.oscarehr.PMmodule.dao.ProgramTeamDAO#deleteProgramTeam(java.lang.Integer) + */ + @Override + public void deleteProgramTeam(Integer id) { + if (id == null || id.intValue() <= 0) { + throw new IllegalArgumentException(); + } + + this.getHibernateTemplate().delete(getProgramTeam(id)); + + if (log.isDebugEnabled()) { + log.debug("deleteProgramTeam: id=" + id); + } + } + + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProviderDao.java b/src/main/java/org/oscarehr/PMmodule/dao/ProviderDao.java index eb239faa40..6dab452baa 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/ProviderDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProviderDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -49,743 +52,132 @@ import org.oscarehr.util.LoggedInInfo; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.hibernate.type.StandardBasicTypes; import oscar.OscarProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; import com.quatro.model.security.SecProvider; @SuppressWarnings("unchecked") -public class ProviderDao extends HibernateDaoSupport { - +public interface ProviderDao { + public static final String PR_TYPE_DOCTOR = "doctor"; - public static final String PR_TYPE_RESIDENT = "resident"; - - private static Logger log = MiscUtils.getLogger(); - - public boolean providerExists(String providerNo) { - return getHibernateTemplate().get(Provider.class, providerNo) != null; - } - - public Provider getProvider(String providerNo) { - if (providerNo == null || providerNo.length() <= 0) { - return null; - } - - Provider provider = getHibernateTemplate().get(Provider.class, providerNo); - - if (log.isDebugEnabled()) { - log.debug("getProvider: providerNo=" + providerNo + ",found=" + (provider != null)); - } - - return provider; - } - - public String getProviderName(String providerNo) { - - String providerName = ""; - Provider provider = getProvider(providerNo); - - if (provider != null) { - if (provider.getFirstName() != null) { - providerName = provider.getFirstName() + " "; - } - - if (provider.getLastName() != null) { - providerName += provider.getLastName(); - } - - if (log.isDebugEnabled()) { - log.debug("getProviderName: providerNo=" + providerNo + ",result=" + providerName); - } - } - - return providerName; - } - - public String getProviderNameLastFirst(String providerNo) { - if (providerNo == null || providerNo.length() <= 0) { - throw new IllegalArgumentException(); - } - - String providerName = ""; - Provider provider = getProvider(providerNo); - - if (provider != null) { - if (provider.getLastName() != null) { - providerName = provider.getLastName() + ", "; - } - - if (provider.getFirstName() != null) { - providerName += provider.getFirstName(); - } - - if (log.isDebugEnabled()) { - log.debug("getProviderNameLastFirst: providerNo=" + providerNo + ",result=" + providerName); - } - } - - return providerName; - } - - public List getProviders() { - - List rs = getHibernateTemplate().find( - "FROM Provider p ORDER BY p.LastName"); - - if (log.isDebugEnabled()) { - log.debug("getProviders: # of results=" + rs.size()); - } - return rs; - } - - public List getProviders(String[] providers) { - List rs = getHibernateTemplate().find( - "FROM Provider p WHERE p.providerNumber IN (?)", (Object[]) providers); - return rs; - } - - - public List getProviderFromFirstLastName(String firstname,String lastname){ - firstname=firstname.trim(); - lastname=lastname.trim(); - String s="From Provider p where p.FirstName=? and p.LastName=?"; - ArrayList paramList=new ArrayList(); - paramList.add(firstname); - paramList.add(lastname); - Object params[]=paramList.toArray(new Object[paramList.size()]); - return getHibernateTemplate().find(s,params); - } - - public List getProviderLikeFirstLastName(String firstname,String lastname){ - firstname=firstname.trim(); - lastname=lastname.trim(); - String s="From Provider p where p.FirstName like ? and p.LastName like ?"; - ArrayList paramList=new ArrayList(); - paramList.add(firstname); - paramList.add(lastname); - Object params[]=paramList.toArray(new Object[paramList.size()]); - return getHibernateTemplate().find(s,params); - } - - public List getActiveProviderLikeFirstLastName(String firstname,String lastname){ - firstname=firstname.trim(); - lastname=lastname.trim(); - String s="From Provider p where p.FirstName like ? and p.LastName like ? and p.Status='1'"; - ArrayList paramList=new ArrayList(); - paramList.add(firstname); - paramList.add(lastname); - Object params[]=paramList.toArray(new Object[paramList.size()]); - return getHibernateTemplate().find(s,params); - } - - public List getActiveProviders(Integer programId) { - ArrayList paramList = new ArrayList(); - - String sSQL="FROM SecProvider p where p.status='1' and p.providerNo in " + - "(select sr.providerNo from secUserRole sr, LstOrgcd o " + - " where o.code = 'P' || ? " + - " and o.codecsv like '%' || sr.orgcd || ',%' " + - " and not (sr.orgcd like 'R%' or sr.orgcd like 'O%'))" + - " ORDER BY p.lastName"; - - paramList.add(programId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - - return getHibernateTemplate().find(sSQL ,params); - } - - public List getActiveProviders(String facilityId, String programId) { - ArrayList paramList = new ArrayList(); - - String sSQL; - List rs; - if (programId != null && "0".equals(programId) == false) { - sSQL = "FROM Provider p where p.Status='1' and p.ProviderNo in " - + "(select c.ProviderNo from ProgramProvider c where c.ProgramId =?) ORDER BY p.LastName"; - paramList.add(Long.valueOf(programId)); - Object params[] = paramList.toArray(new Object[paramList.size()]); - rs = getHibernateTemplate().find(sSQL, params); - } else if (facilityId != null && "0".equals(facilityId) == false) { - sSQL = "FROM Provider p where p.Status='1' and p.ProviderNo in " - + "(select c.ProviderNo from ProgramProvider c where c.ProgramId in " - + "(select a.id from Program a where a.facilityId=?)) ORDER BY p.LastName"; - // JS 2192700 - string facilityId seems to be throwing class cast - // exception - Integer intFacilityId = Integer.valueOf(facilityId); - paramList.add(intFacilityId); - Object params[] = paramList.toArray(new Object[paramList.size()]); - rs = getHibernateTemplate().find(sSQL, params); - } else { - sSQL = "FROM Provider p where p.Status='1' ORDER BY p.LastName"; - rs = getHibernateTemplate().find(sSQL); - } - // List rs = - // getHibernateTemplate().find("FROM Provider p ORDER BY p.LastName"); - - return rs; - } - - public List getActiveProviders() { - - List rs = getHibernateTemplate().find( - "FROM Provider p where p.Status='1' AND p.ProviderNo NOT LIKE '-%' ORDER BY p.LastName"); - - if (log.isDebugEnabled()) { - log.debug("getProviders: # of results=" + rs.size()); - } - return rs; - } - - public List getActiveProviders(boolean filterOutSystemAndImportedProviders ) { - - List rs = null; - - if(!filterOutSystemAndImportedProviders) { - rs = getHibernateTemplate().find( - "FROM Provider p where p.Status='1' ORDER BY p.LastName"); - } else { - rs = getHibernateTemplate().find( - "FROM Provider p where p.Status='1' AND p.ProviderNo > -1 ORDER BY p.LastName"); - } - - if (log.isDebugEnabled()) { - log.debug("getProviders: # of results=" + rs.size()); - } - return rs; - } - - public List getActiveProvidersByRole(String role) { - - List rs = getHibernateTemplate().find( - "select p FROM Provider p, SecUserRole s where p.ProviderNo = s.ProviderNo and p.Status='1' and s.RoleName = ? order by p.LastName, p.FirstName", role); - - if (log.isDebugEnabled()) { - log.debug("getActiveProvidersByRole: # of results=" + rs.size()); - } - return rs; - } - - public List getDoctorsWithOhip(){ - return getHibernateTemplate().find( - "FROM Provider p " + - "WHERE p.ProviderType = 'doctor' " + - "AND p.Status = '1' " + - "AND p.OhipNo IS NOT NULL " + - "ORDER BY p.LastName, p.FirstName"); - } - - public List getBillableProviders() { - List rs = getHibernateTemplate().find("FROM Provider p where p.OhipNo != '' and p.Status = '1' order by p.LastName"); - return rs; - } - - /** - * Add loggedininfo to excluded logged in provider. - * Usefull when setting personal preferrences. - * @param loggedInInfo - * @return - */ - public List getBillableProvidersInBC(LoggedInInfo loggedInInfo) { - return getHibernateTemplate().find("FROM Provider p where (p.OhipNo <> '' or p.RmaNo <> '' or p.BillingNo <> '' or p.HsoNo <> '') and p.Status = '1' and p.ProviderNo not like ? order by p.LastName", loggedInInfo.getLoggedInProviderNo()); - } - - @SuppressWarnings("unchecked") - public List getBillableProvidersInBC() { - List rs = getHibernateTemplate().find("FROM Provider p where (p.OhipNo <> '' or p.RmaNo <> '' or p.BillingNo <> '' or p.HsoNo <> '')and p.Status = '1' order by p.LastName"); - return rs; - } - - public List getProviders(boolean active) { - - List rs = getHibernateTemplate().find( - "FROM Provider p where p.Status='" + (active?1:0) + "' order by p.LastName" ); - return rs; - } - - public List getActiveProviders(String providerNo, Integer shelterId) { - // - String sql; - if (shelterId == null || shelterId.intValue() == 0) - sql = "FROM Provider p where p.Status='1'" + - " and p.ProviderNo in (select sr.providerNo from Secuserrole sr " + - " where sr.orgcd in (select o.code from LstOrgcd o, Secuserrole srb " + - " where o.codecsv like '%' || srb.orgcd || ',%' and srb.providerNo =?))" + - " ORDER BY p.LastName"; - else - sql = "FROM Provider p where p.Status='1'" + - " and p.ProviderNo in (select sr.providerNo from Secuserrole sr " + - " where sr.orgcd in (select o.code from LstOrgcd o, Secuserrole srb " + - " where o.codecsv like '%S" + shelterId.toString()+ ",%' and o.codecsv like '%' || srb.orgcd || ',%' and srb.providerNo =?))" + - " ORDER BY p.LastName"; - - ArrayList paramList = new ArrayList(); - paramList.add(providerNo); - - Object params[] = paramList.toArray(new Object[paramList.size()]); - - List rs = getHibernateTemplate().find(sql,params); - - if (log.isDebugEnabled()) { - log.debug("getProviders: # of results=" + rs.size()); - } - return rs; - } - - public List getActiveProvider(String providerNo) { - - String sql = "FROM Provider p where p.Status='1' and p.ProviderNo =?"; - - ArrayList paramList = new ArrayList(); - paramList.add(providerNo); - - Object params[] = paramList.toArray(new Object[paramList.size()]); - - List rs = getHibernateTemplate().find(sql,params); - - if (log.isDebugEnabled()) { - log.debug("getProvider: # of results=" + rs.size()); - } - return rs; - } - - - public List search(String name) { - boolean isOracle = OscarProperties.getInstance().getDbType().equals( - "oracle"); - Session session = getSession(); - - Criteria c = session.createCriteria(Provider.class); - if (isOracle) { - c.add(Restrictions.or(Expression.ilike("FirstName", name + "%"), - Expression.ilike("LastName", name + "%"))); - } else { - c.add(Restrictions.or(Expression.like("FirstName", name + "%"), - Expression.like("LastName", name + "%"))); - } - c.addOrder(Order.asc("ProviderNo")); - - List results = new ArrayList(); - - try { - results = c.list(); - }finally { - this.releaseSession(session); - } - - if (log.isDebugEnabled()) { - log.debug("search: # of results=" + results.size()); - } - return results; - } - - public List getProvidersByTypeWithNonEmptyOhipNo(String type) { - List results = this.getHibernateTemplate().find( - "from Provider p where p.ProviderType = ? and p.OhipNo <> ''", type); - return results; - } - - - public List getProvidersByType(String type) { - - List results = this.getHibernateTemplate().find( - "from Provider p where p.ProviderType = ?", type); - - if (log.isDebugEnabled()) { - log.debug("getProvidersByType: type=" + type + ",# of results=" - + results.size()); - } - - return results; - } - - public List getProvidersByTypePattern(String typePattern) { - - List results = this.getHibernateTemplate().find( - "from Provider p where p.ProviderType like ?", typePattern); - return results; - } - - public List getShelterIds(String provider_no) - { - - String sql ="select distinct c.id as shelter_id from lst_shelter c, lst_orgcd a, secUserRole b where instr('RO',substr(b.orgcd,1,1)) = 0 and a.codecsv like '%' || b.orgcd || ',%'" + - " and b.provider_no=? and a.codecsv like '%S' || c.id || ',%'"; - Session session = getSession(); - - Query query = session.createSQLQuery(sql); - ((SQLQuery) query).addScalar("shelter_id", Hibernate.INTEGER); - query.setString(0, provider_no); - List lst = new ArrayList(); - try { - lst=query.list(); - }finally { - this.releaseSession(session); - } - return lst; - - } - - public static void addProviderToFacility(String provider_no, int facilityId) { - try { - ProviderFacility pf = new ProviderFacility(); - pf.setId(new ProviderFacilityPK()); - pf.getId().setProviderNo(provider_no); - pf.getId().setFacilityId(facilityId); - ProviderFacilityDao pfDao = SpringUtils.getBean(ProviderFacilityDao.class); - pfDao.persist(pf); - } catch (RuntimeException e) { - // chances are it's a duplicate unique entry exception so it's safe - // to ignore. - // this is still unexpected because duplicate calls shouldn't be - // made - log.warn("Unexpected exception occurred.", e); - } - } - - public static void removeProviderFromFacility(String provider_no, - int facilityId) { - ProviderFacilityDao dao = SpringUtils.getBean(ProviderFacilityDao.class); - for(ProviderFacility p:dao.findByProviderNoAndFacilityId(provider_no,facilityId)) { - dao.remove(p.getId()); - } - } - - - public List getFacilityIds(String provider_no) { - Session session = getSession(); - try { - SQLQuery query = session.createSQLQuery("select facility_id from provider_facility,Facility where Facility.id=provider_facility.facility_id and Facility.disabled=0 and provider_no=\'"+provider_no +"\'"); - List results = query.list(); - return results; - }finally { - this.releaseSession(session); - } - } - - - public List getProviderIds(int facilityId) { - Session session = getSession(); - try { - SQLQuery query = session.createSQLQuery("select provider_no from provider_facility where facility_id="+facilityId); - List results = query.list(); - return results; - }finally { - this.releaseSession(session); - } - - } - - public void updateProvider( Provider provider) { - this.getHibernateTemplate().update(provider); - } - - public void saveProvider( Provider provider) { - this.getHibernateTemplate().save(provider); - } - - public Provider getProviderByPractitionerNo(String practitionerNo) { - if (practitionerNo == null || practitionerNo.length() <= 0) { - return null; - } - - List providerList = getHibernateTemplate().find("From Provider p where p.practitionerNo=?",new Object[]{practitionerNo}); - - if(providerList.size()>1) { - logger.warn("Found more than 1 provider with practitionerNo="+practitionerNo); - } - if(providerList.size()>0) - return providerList.get(0); - - return null; - } - - public Provider getProviderByPractitionerNo(String practitionerNoType, String practitionerNo) { - return getProviderByPractitionerNo(new String[] {practitionerNoType},practitionerNo); - } - - public Provider getProviderByPractitionerNo(String[] practitionerNoTypes, String practitionerNo) { - if (practitionerNoTypes == null || practitionerNoTypes.length <= 0) { - throw new IllegalArgumentException(); - } - if (practitionerNo == null || practitionerNo.length() <= 0) { - throw new IllegalArgumentException(); - } - - List providerList = getHibernateTemplate().findByNamedParam("From Provider p where p.practitionerNoType IN (:types) AND p.practitionerNo=:pId", new String[] {"types","pId"}, new Object[] {practitionerNoTypes,practitionerNo}); -// List providerList = getHibernateTemplate().find("From Provider p where p.practitionerNoType IN (:types) AND p.practitionerNo=?",new Object[]{practitionerNo}); - - if(providerList.size()>1) { - logger.warn("Found more than 1 provider with practitionerNo="+practitionerNo); - } - if(providerList.size()>0) - return providerList.get(0); - - return null; - } - - public List getUniqueTeams() { - - List providerList = getHibernateTemplate().find("select distinct p.Team From Provider p"); - - return providerList; - } - - public List getBillableProvidersOnTeam(Provider p) { - - List providers = this.getHibernateTemplate().find("from Provider p where status='1' and ohip_no!='' and p.Team=? order by last_name, first_name", p.getTeam()); - - return providers; - } - - public List getBillableProvidersByOHIPNo(String ohipNo) { - if (ohipNo == null || ohipNo.length() <= 0) { - throw new IllegalArgumentException(); - } - - - List providers = this.getHibernateTemplate().find("from Provider p where ohip_no like ? order by last_name, first_name", ohipNo); - - if(providers.size()>1) { - logger.warn("Found more than 1 provider with ohipNo="+ohipNo); - } - if(providers.isEmpty()) - return null; - else - return providers; - } - - public List getProvidersWithNonEmptyOhip(LoggedInInfo loggedInInfo) { - return getHibernateTemplate().find("FROM Provider WHERE ohip_no != '' and ProviderNo not like ? order by last_name, first_name", loggedInInfo.getLoggedInProviderNo()); - } - - /** - * Gets all providers with non-empty OHIP number ordered by last,then first name - * - * @return - * Returns the all found providers - */ - - public List getProvidersWithNonEmptyOhip() { - return getHibernateTemplate().find("FROM Provider WHERE ohip_no != '' order by last_name, first_name"); - } - - public List getCurrentTeamProviders(String providerNo) { - String hql = "SELECT p FROM Provider p " - + "WHERE p.Status='1' and p.OhipNo != '' " - + "AND (p.ProviderNo='"+providerNo+"' or team=(SELECT p2.Team FROM Provider p2 where p2.ProviderNo='"+providerNo+"')) " - + "ORDER BY p.LastName, p.FirstName"; - - return this.getHibernateTemplate().find(hql); - } - - public List getActiveTeams() { - List providerList = getHibernateTemplate().find("select distinct p.Team From Provider p where p.Status = '1' and p.Team != '' order by p.Team"); - return providerList; - } - - @NativeSql({"provider", "providersite"}) - - public List getActiveTeamsViaSites(String providerNo) { - Session session = getSession(); - try { - // providersite is not mapped in hibernate - this can be rewritten w.o. subselect with a cross product IHMO - SQLQuery query = session.createSQLQuery("select distinct team from provider p inner join providersite s on s.provider_no = p.provider_no " + - " where s.site_id in (select site_id from providersite where provider_no = '" + providerNo + "') order by team "); - return query.list(); - }finally { - this.releaseSession(session); - } - } - - - public List getProviderByPatientId(Integer patientId) { - String hql = "SELECT p FROM Provider p, Demographic d " - + "WHERE d.ProviderNo = p.ProviderNo " - + "AND d.DemographicNo = ?"; - return this.getHibernateTemplate().find(hql, patientId); - } - - public List getDoctorsWithNonEmptyCredentials() { - String sql = "FROM Provider p WHERE p.ProviderType = 'doctor' " + - "AND p.Status='1' " + - "AND p.OhipNo IS NOT NULL " + - "AND p.OhipNo != '' " + - "ORDER BY p.LastName, p.FirstName"; - return getHibernateTemplate().find(sql); - } - - public List getProvidersWithNonEmptyCredentials() { - String sql = "FROM Provider p WHERE p.Status='1' " + - "AND p.OhipNo IS NOT NULL " + - "AND p.OhipNo != '' " + - "ORDER BY p.LastName, p.FirstName"; - return getHibernateTemplate().find(sql); - } - - public List getProvidersInTeam(String teamName) { - List providerList = getHibernateTemplate().find("select distinct p.ProviderNo from Provider p where p.Team = ?",new Object[]{teamName}); - return providerList; - } - - public List getDistinctProviders() { - List providerList = getHibernateTemplate().find("select distinct p.ProviderNo, p.ProviderType from Provider p ORDER BY p.LastName"); - return providerList; - } - - public List getRecordsAddedAndUpdatedSinceTime(Date date) { - @SuppressWarnings("unchecked") - List providers = getHibernateTemplate().find("select distinct p.ProviderNo From Provider p where p.lastUpdateDate > ? ",date); - - return providers; - } - - @SuppressWarnings("unchecked") - public List searchProviderByNamesString(String searchString, int startIndex, int itemsToReturn) { - String sqlCommand = "select x from Provider x"; - if (searchString != null) { - if(searchString.indexOf(",") != -1 && searchString.split(",").length>1 && searchString.split(",")[1].length()>0) { - sqlCommand = sqlCommand + " where x.LastName like :ln AND x.FirstName like :fn"; - } else { - sqlCommand = sqlCommand + " where x.LastName like :ln"; - } - - } - - Session session = this.getSession(); - try { - Query q = session.createQuery(sqlCommand); - if (searchString != null) { - q.setParameter("ln", "%" + searchString.split(",")[0] + "%"); - if(searchString.indexOf(",") != -1 && searchString.split(",").length>1 && searchString.split(",")[1].length()>0) { - q.setParameter("fn", "%" + searchString.split(",")[1] + "%"); - - } - } - q.setFirstResult(startIndex); - q.setMaxResults(itemsToReturn); - return (q.list()); - } finally { - this.releaseSession(session); - } - } - - @SuppressWarnings("unchecked") - public List search(String term, boolean active, int startIndex, int itemsToReturn) { - String sqlCommand = "select x from Provider x WHERE x.Status = :status "; - - - if(term != null && term.length()>0) { - sqlCommand += "AND (x.LastName like :term OR x.FirstName like :term) "; - } - - sqlCommand += " ORDER BY x.LastName,x.FirstName"; - - - - Session session = this.getSession(); - try { - Query q = session.createQuery(sqlCommand); - - q.setString("status", active?"1":"0"); - if(term != null && term.length()>0) { - q.setString("term", term + "%"); - } - - q.setFirstResult(startIndex); - q.setMaxResults(itemsToReturn); - return (q.list()); - } finally { - this.releaseSession(session); - } - } - - @NativeSql({"provider", "appointment"}) - public List getProviderNosWithAppointmentsOnDate(Date appointmentDate) { - Session session = getSession(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - try { - String sql = "SELECT p.provider_no FROM provider p WHERE p.provider_no IN (SELECT DISTINCT a.provider_no FROM appointment a WHERE a.appointment_date = '" + sdf.format(appointmentDate) + "') " + - "AND p.Status='1'"; - SQLQuery query = session.createSQLQuery(sql); - - return query.list(); - }finally { - this.releaseSession(session); - } - } - - public List getOlisHicProviders() { - UserPropertyDAO userPropertyDAO = SpringUtils.getBean(UserPropertyDAO.class); - Session session = getSession(); - String sql = "FROM Provider p WHERE p.practitionerNo IS NOT NULL AND p.practitionerNo != ''"; - Query query = session.createQuery(sql); - List practitionerNoProviders = query.list(); - - List results = new ArrayList(); - for (Provider practitionerNoProvider : practitionerNoProviders) { - String olisType = userPropertyDAO.getStringValue(practitionerNoProvider.getProviderNo(), UserProperty.OFFICIAL_OLIS_IDTYPE); - if (olisType != null && !olisType.isEmpty()) { - results.add(practitionerNoProvider); - } - } - return results; - } - - public Provider getProviderByPractitionerNoAndOlisType(String practitionerNo, String olisIdentifierType) { - UserPropertyDAO userPropertyDAO = SpringUtils.getBean(UserPropertyDAO.class); - String sql = "FROM Provider p WHERE p.practitionerNo=?"; - - List providers = getHibernateTemplate().find(sql, practitionerNo); - - if (!providers.isEmpty()) { - Provider provider = providers.get(0); - String olisType = userPropertyDAO.getStringValue(provider.getProviderNo(), UserProperty.OFFICIAL_OLIS_IDTYPE); - if (olisIdentifierType.equals(olisType)) { - return providers.get(0); - } - } - return null; - } - - public List getOlisProvidersByPractitionerNo(List practitionerNumbers) { - Session session = getSession(); - String sql = "FROM Provider p WHERE p.practitionerNo IN (:practitionerNumbers)"; - Query query = session.createQuery(sql); - query.setParameterList("practitionerNumbers", practitionerNumbers); - List providers = query.list(); - - return providers; - } - - /** - * Gets a list of provider numbers based on the provided list of provider numbers - * @param providerNumbers The list of provider numbers to get the related objects for - * @return A list of providers - */ - public List getProvidersByIds(List providerNumbers) { - Session session = getSession(); - String sql = "FROM Provider p WHERE p.ProviderNo IN (:providerNumbers)"; - Query query = session.createQuery(sql); - query.setParameterList("providerNumbers", providerNumbers); - - List providers = query.list(); - return providers; - } - - /** - * Gets a map of provider names with the provider number as the map key based on the provided list of provider numbers - * @param providerNumbers A list of provider numbers to get the name map for - * @return A map of provider names with their related provider number as the key - */ - public Map getProviderNamesByIdsAsMap(List providerNumbers) { - Map providerNameMap = new HashMap<>(); - List providers = getProvidersByIds(providerNumbers); - - for (Provider provider : providers) { - providerNameMap.put(provider.getProviderNo(), provider.getFullName()); - } - - return providerNameMap; - } + public static final String PR_TYPE_RESIDENT = "resident"; + + public boolean providerExists(String providerNo); + + public Provider getProvider(String providerNo); + + public String getProviderName(String providerNo); + + public String getProviderNameLastFirst(String providerNo); + + public List getProviders(); + + public List getProviders(String[] providers); + + public List getProviderFromFirstLastName(String firstname, String lastname); + + public List getProviderLikeFirstLastName(String firstname, String lastname); + + public List getActiveProviderLikeFirstLastName(String firstname, String lastname); + + public List getActiveProviders(Integer programId); + + public List getActiveProviders(String facilityId, String programId); + + public List getActiveProviders(); + + public List getActiveProviders(boolean filterOutSystemAndImportedProviders); + + public List getActiveProvidersByRole(String role); + + public List getDoctorsWithOhip(); + + public List getBillableProviders(); + + public List getBillableProvidersInBC(LoggedInInfo loggedInInfo); + + public List getBillableProvidersInBC(); + + public List getProviders(boolean active); + + public List getActiveProviders(String providerNo, Integer shelterId); + + public List getActiveProvider(String providerNo); + + public List search(String name); + + public List getProvidersByTypeWithNonEmptyOhipNo(String type); + + public List getProvidersByType(String type); + + public List getProvidersByTypePattern(String typePattern); + + public List getShelterIds(String provider_no); + + public void addProviderToFacility(String provider_no, int facilityId); + + public void removeProviderFromFacility(String provider_no, + int facilityId); + + public List getFacilityIds(String provider_no); + + public List getProviderIds(int facilityId); + + public void updateProvider(Provider provider); + + public void saveProvider(Provider provider); + + public Provider getProviderByPractitionerNo(String practitionerNo); + + public Provider getProviderByPractitionerNo(String practitionerNoType, String practitionerNo); + + public Provider getProviderByPractitionerNo(String[] practitionerNoTypes, String practitionerNo); + + public List getUniqueTeams(); + + public List getBillableProvidersOnTeam(Provider p); + + public List getBillableProvidersByOHIPNo(String ohipNo); + + public List getProvidersWithNonEmptyOhip(LoggedInInfo loggedInInfo); + + public List getProvidersWithNonEmptyOhip(); + + public List getCurrentTeamProviders(String providerNo); + + public List getActiveTeams(); + + public List getActiveTeamsViaSites(String providerNo); + + public List getProviderByPatientId(Integer patientId); + + public List getDoctorsWithNonEmptyCredentials(); + + public List getProvidersWithNonEmptyCredentials(); + + public List getProvidersInTeam(String teamName); + + public List getDistinctProviders(); + + public List getRecordsAddedAndUpdatedSinceTime(Date date); + + public List searchProviderByNamesString(String searchString, int startIndex, int itemsToReturn); + + public List search(String term, boolean active, int startIndex, int itemsToReturn); + + public List getProviderNosWithAppointmentsOnDate(Date appointmentDate); + + public List getOlisHicProviders(); + + public Provider getProviderByPractitionerNoAndOlisType(String practitionerNo, String olisIdentifierType); + + public List getOlisProvidersByPractitionerNo(List practitionerNumbers); + + public List getProvidersByIds(List providerNumbers); + + public Map getProviderNamesByIdsAsMap(List providerNumbers); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/ProviderDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/ProviderDaoImpl.java new file mode 100644 index 0000000000..b0b1cdc1d5 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/ProviderDaoImpl.java @@ -0,0 +1,914 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Criteria; +import org.hibernate.Hibernate; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.criterion.Expression; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.Restrictions; +import org.oscarehr.common.NativeSql; +import org.oscarehr.common.dao.ProviderFacilityDao; +import org.oscarehr.common.dao.UserPropertyDAO; +import org.oscarehr.common.model.Provider; +import org.oscarehr.common.model.ProviderFacility; +import org.oscarehr.common.model.ProviderFacilityPK; +import org.oscarehr.common.model.UserProperty; +import org.oscarehr.util.LoggedInInfo; +import org.oscarehr.util.MiscUtils; +import org.oscarehr.util.SpringUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; +import org.hibernate.type.StandardBasicTypes; +import oscar.OscarProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.hibernate.SessionFactory; +import org.springframework.transaction.annotation.Transactional; + +import com.quatro.model.security.SecProvider; + +@SuppressWarnings("unchecked") +@Transactional +public class ProviderDaoImpl extends HibernateDaoSupport implements ProviderDao { + + public static final String PR_TYPE_DOCTOR = "doctor"; + public static final String PR_TYPE_RESIDENT = "resident"; + + private static Logger log = MiscUtils.getLogger(); + + @Autowired + public void setSessionFactoryOverride(SessionFactory sessionFactory) { + log.info("Setting session factory in ProviderDaoImpl"); + if (sessionFactory == null) { + log.error("SessionFactory is null!"); + } else { + log.info("SessionFactory is successfully set."); + } + super.setSessionFactory(sessionFactory); + } + + public boolean providerExists(String providerNo) { + return getHibernateTemplate().get(Provider.class, providerNo) != null; + } + + @Override + public Provider getProvider(String providerNo) { + if (providerNo == null || providerNo.length() <= 0) { + return null; + } + + Provider provider = getHibernateTemplate().get(Provider.class, providerNo); + + if (log.isDebugEnabled()) { + log.debug("getProvider: providerNo=" + providerNo + ",found=" + (provider != null)); + } + + return provider; + } + + @Override + public String getProviderName(String providerNo) { + + String providerName = ""; + Provider provider = getProvider(providerNo); + + if (provider != null) { + if (provider.getFirstName() != null) { + providerName = provider.getFirstName() + " "; + } + + if (provider.getLastName() != null) { + providerName += provider.getLastName(); + } + + if (log.isDebugEnabled()) { + log.debug("getProviderName: providerNo=" + providerNo + ",result=" + providerName); + } + } + + return providerName; + } + + @Override + public String getProviderNameLastFirst(String providerNo) { + if (providerNo == null || providerNo.length() <= 0) { + throw new IllegalArgumentException(); + } + + String providerName = ""; + Provider provider = getProvider(providerNo); + + if (provider != null) { + if (provider.getLastName() != null) { + providerName = provider.getLastName() + ", "; + } + + if (provider.getFirstName() != null) { + providerName += provider.getFirstName(); + } + + if (log.isDebugEnabled()) { + log.debug("getProviderNameLastFirst: providerNo=" + providerNo + ",result=" + providerName); + } + } + + return providerName; + } + + @Override + public List getProviders() { + + List rs = (List) getHibernateTemplate().find( + "FROM Provider p ORDER BY p.LastName"); + + if (log.isDebugEnabled()) { + log.debug("getProviders: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List getProviders(String[] providers) { + List rs = (List) getHibernateTemplate().find( + "FROM Provider p WHERE p.providerNumber IN (?)", (Object[]) providers); + return rs; + } + + @Override + public List getProviderFromFirstLastName(String firstname, String lastname) { + firstname = firstname.trim(); + lastname = lastname.trim(); + String s = "From Provider p where p.FirstName=? and p.LastName=?"; + ArrayList paramList = new ArrayList(); + paramList.add(firstname); + paramList.add(lastname); + Object params[] = paramList.toArray(new Object[paramList.size()]); + return (List) getHibernateTemplate().find(s, params); + } + + @Override + public List getProviderLikeFirstLastName(String firstname, String lastname) { + firstname = firstname.trim(); + lastname = lastname.trim(); + String s = "From Provider p where p.FirstName like ? and p.LastName like ?"; + ArrayList paramList = new ArrayList(); + paramList.add(firstname); + paramList.add(lastname); + Object params[] = paramList.toArray(new Object[paramList.size()]); + return (List) getHibernateTemplate().find(s, params); + } + + @Override + public List getActiveProviderLikeFirstLastName(String firstname, String lastname) { + firstname = firstname.trim(); + lastname = lastname.trim(); + String s = "From Provider p where p.FirstName like ? and p.LastName like ? and p.Status='1'"; + ArrayList paramList = new ArrayList(); + paramList.add(firstname); + paramList.add(lastname); + Object params[] = paramList.toArray(new Object[paramList.size()]); + return (List) getHibernateTemplate().find(s, params); + } + + @Override + public List getActiveProviders(Integer programId) { + ArrayList paramList = new ArrayList(); + + String sSQL = "FROM SecProvider p where p.status='1' and p.providerNo in " + + "(select sr.providerNo from secUserRole sr, LstOrgcd o " + + " where o.code = 'P' || ? " + + " and o.codecsv like '%' || sr.orgcd || ',%' " + + " and not (sr.orgcd like 'R%' or sr.orgcd like 'O%'))" + + " ORDER BY p.lastName"; + + paramList.add(programId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + + return (List) getHibernateTemplate().find(sSQL, params); + } + + @Override + public List getActiveProviders(String facilityId, String programId) { + ArrayList paramList = new ArrayList(); + + String sSQL; + List rs; + if (programId != null && "0".equals(programId) == false) { + sSQL = "FROM Provider p where p.Status='1' and p.ProviderNo in " + + "(select c.ProviderNo from ProgramProvider c where c.ProgramId =?) ORDER BY p.LastName"; + paramList.add(Long.valueOf(programId)); + Object params[] = paramList.toArray(new Object[paramList.size()]); + rs = (List) getHibernateTemplate().find(sSQL, params); + } else if (facilityId != null && "0".equals(facilityId) == false) { + sSQL = "FROM Provider p where p.Status='1' and p.ProviderNo in " + + "(select c.ProviderNo from ProgramProvider c where c.ProgramId in " + + "(select a.id from Program a where a.facilityId=?)) ORDER BY p.LastName"; + // JS 2192700 - string facilityId seems to be throwing class cast + // exception + Integer intFacilityId = Integer.valueOf(facilityId); + paramList.add(intFacilityId); + Object params[] = paramList.toArray(new Object[paramList.size()]); + rs = (List) getHibernateTemplate().find(sSQL, params); + } else { + sSQL = "FROM Provider p where p.Status='1' ORDER BY p.LastName"; + rs = (List) getHibernateTemplate().find(sSQL); + } + // List rs = + // getHibernateTemplate().find("FROM Provider p ORDER BY p.LastName"); + + return rs; + } + + @Override + public List getActiveProviders() { + + List rs = (List) getHibernateTemplate().find( + "FROM Provider p where p.Status='1' AND p.ProviderNo NOT LIKE '-%' ORDER BY p.LastName"); + + if (log.isDebugEnabled()) { + log.debug("getProviders: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List getActiveProviders(boolean filterOutSystemAndImportedProviders) { + + List rs = null; + + if (!filterOutSystemAndImportedProviders) { + rs = (List) getHibernateTemplate().find( + "FROM Provider p where p.Status='1' ORDER BY p.LastName"); + } else { + rs = (List) getHibernateTemplate().find( + "FROM Provider p where p.Status='1' AND p.ProviderNo > -1 ORDER BY p.LastName"); + } + + if (log.isDebugEnabled()) { + log.debug("getProviders: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List getActiveProvidersByRole(String role) { + + List rs = (List) getHibernateTemplate().find( + "select p FROM Provider p, SecUserRole s where p.ProviderNo = s.ProviderNo and p.Status='1' and s.RoleName = ? order by p.LastName, p.FirstName", + role); + + if (log.isDebugEnabled()) { + log.debug("getActiveProvidersByRole: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List getDoctorsWithOhip() { + return (List) getHibernateTemplate().find( + "FROM Provider p " + + "WHERE p.ProviderType = 'doctor' " + + "AND p.Status = '1' " + + "AND p.OhipNo IS NOT NULL " + + "ORDER BY p.LastName, p.FirstName"); + } + + @Override + public List getBillableProviders() { + List rs = (List) getHibernateTemplate() + .find("FROM Provider p where p.OhipNo != '' and p.Status = '1' order by p.LastName"); + return rs; + } + + /** + * Add loggedininfo to excluded logged in provider. + * Usefull when setting personal preferrences. + * + * @param loggedInInfo + * @return + */ + @Override + public List getBillableProvidersInBC(LoggedInInfo loggedInInfo) { + return (List) getHibernateTemplate().find( + "FROM Provider p where (p.OhipNo <> '' or p.RmaNo <> '' or p.BillingNo <> '' or p.HsoNo <> '') and p.Status = '1' and p.ProviderNo not like ? order by p.LastName", + loggedInInfo.getLoggedInProviderNo()); + } + + @SuppressWarnings("unchecked") + @Override + public List getBillableProvidersInBC() { + List rs = (List) getHibernateTemplate().find( + "FROM Provider p where (p.OhipNo <> '' or p.RmaNo <> '' or p.BillingNo <> '' or p.HsoNo <> '')and p.Status = '1' order by p.LastName"); + return rs; + } + + @Override + public List getProviders(boolean active) { + + List rs = (List) getHibernateTemplate().find( + "FROM Provider p where p.Status='" + (active ? 1 : 0) + "' order by p.LastName"); + return rs; + } + + @Override + public List getActiveProviders(String providerNo, Integer shelterId) { + // + String sql; + if (shelterId == null || shelterId.intValue() == 0) + sql = "FROM Provider p where p.Status='1'" + + " and p.ProviderNo in (select sr.providerNo from Secuserrole sr " + + " where sr.orgcd in (select o.code from LstOrgcd o, Secuserrole srb " + + " where o.codecsv like '%' || srb.orgcd || ',%' and srb.providerNo =?))" + + " ORDER BY p.LastName"; + else + sql = "FROM Provider p where p.Status='1'" + + " and p.ProviderNo in (select sr.providerNo from Secuserrole sr " + + " where sr.orgcd in (select o.code from LstOrgcd o, Secuserrole srb " + + " where o.codecsv like '%S" + shelterId.toString() + + ",%' and o.codecsv like '%' || srb.orgcd || ',%' and srb.providerNo =?))" + + " ORDER BY p.LastName"; + + ArrayList paramList = new ArrayList(); + paramList.add(providerNo); + + Object params[] = paramList.toArray(new Object[paramList.size()]); + + List rs = (List) getHibernateTemplate().find(sql, params); + + if (log.isDebugEnabled()) { + log.debug("getProviders: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List getActiveProvider(String providerNo) { + + String sql = "FROM Provider p where p.Status='1' and p.ProviderNo =?"; + + ArrayList paramList = new ArrayList(); + paramList.add(providerNo); + + Object params[] = paramList.toArray(new Object[paramList.size()]); + + List rs = (List) getHibernateTemplate().find(sql, params); + + if (log.isDebugEnabled()) { + log.debug("getProvider: # of results=" + rs.size()); + } + return rs; + } + + @Override + public List search(String name) { + boolean isOracle = OscarProperties.getInstance().getDbType().equals( + "oracle"); + // Session session = getSession(); + Session session = currentSession(); + + Criteria c = session.createCriteria(Provider.class); + if (isOracle) { + c.add(Restrictions.or(Expression.ilike("FirstName", name + "%"), + Expression.ilike("LastName", name + "%"))); + } else { + c.add(Restrictions.or(Expression.like("FirstName", name + "%"), + Expression.like("LastName", name + "%"))); + } + c.addOrder(Order.asc("ProviderNo")); + + List results = new ArrayList(); + + try { + results = c.list(); + } finally { + // this.releaseSession(session); + //session.close(); + } + + if (log.isDebugEnabled()) { + log.debug("search: # of results=" + results.size()); + } + return results; + } + + @Override + public List getProvidersByTypeWithNonEmptyOhipNo(String type) { + List results = (List) this.getHibernateTemplate().find( + "from Provider p where p.ProviderType = ? and p.OhipNo <> ''", type); + return results; + } + + @Override + public List getProvidersByType(String type) { + + List results = (List) this.getHibernateTemplate().find( + "from Provider p where p.ProviderType = ?", type); + + if (log.isDebugEnabled()) { + log.debug("getProvidersByType: type=" + type + ",# of results=" + + results.size()); + } + + return results; + } + + @Override + public List getProvidersByTypePattern(String typePattern) { + + List results = (List) this.getHibernateTemplate().find( + "from Provider p where p.ProviderType like ?", typePattern); + return results; + } + + @Override + public List getShelterIds(String provider_no) { + + String sql = "select distinct c.id as shelter_id from lst_shelter c, lst_orgcd a, secUserRole b where instr('RO',substr(b.orgcd,1,1)) = 0 and a.codecsv like '%' || b.orgcd || ',%'" + + + " and b.provider_no=? and a.codecsv like '%S' || c.id || ',%'"; + // Session session = getSession(); + Session session = currentSession(); + + Query query = session.createSQLQuery(sql); + ((SQLQuery) query).addScalar("shelter_id", StandardBasicTypes.INTEGER); + query.setString(0, provider_no); + List lst = new ArrayList(); + try { + lst = query.list(); + } finally { + // this.releaseSession(session); + //session.close(); + } + return lst; + + } + + @Override + public void addProviderToFacility(String provider_no, int facilityId) { + try { + ProviderFacility pf = new ProviderFacility(); + pf.setId(new ProviderFacilityPK()); + pf.getId().setProviderNo(provider_no); + pf.getId().setFacilityId(facilityId); + ProviderFacilityDao pfDao = SpringUtils.getBean(ProviderFacilityDao.class); + pfDao.persist(pf); + } catch (RuntimeException e) { + // chances are it's a duplicate unique entry exception so it's safe + // to ignore. + // this is still unexpected because duplicate calls shouldn't be + // made + log.warn("Unexpected exception occurred.", e); + } + } + + @Override + public void removeProviderFromFacility(String provider_no, + int facilityId) { + ProviderFacilityDao dao = SpringUtils.getBean(ProviderFacilityDao.class); + for (ProviderFacility p : dao.findByProviderNoAndFacilityId(provider_no, facilityId)) { + dao.remove(p.getId()); + } + } + + @Override + public List getFacilityIds(String provider_no) { + // Session session = getSession(); + Session session = currentSession(); + try { + SQLQuery query = session.createSQLQuery( + "select facility_id from provider_facility,Facility where Facility.id=provider_facility.facility_id and Facility.disabled=0 and provider_no=\'" + + provider_no + "\'"); + List results = query.list(); + return results; + } finally { + // this.releaseSession(session); + //session.close(); + } + } + + @Override + public List getProviderIds(int facilityId) { + // Session session = getSession(); + Session session = currentSession(); + try { + SQLQuery query = session + .createSQLQuery("select provider_no from provider_facility where facility_id=" + facilityId); + List results = query.list(); + return results; + } finally { + // this.releaseSession(session); + //session.close(); + } + + } + + @Override + public void updateProvider(Provider provider) { + this.getHibernateTemplate().update(provider); + } + + @Override + public void saveProvider(Provider provider) { + this.getHibernateTemplate().save(provider); + } + + @Override + public Provider getProviderByPractitionerNo(String practitionerNo) { + if (practitionerNo == null || practitionerNo.length() <= 0) { + return null; + } + + List providerList = (List) getHibernateTemplate() + .find("From Provider p where p.practitionerNo=?", new Object[] { practitionerNo }); + + if (providerList.size() > 1) { + logger.warn("Found more than 1 provider with practitionerNo=" + practitionerNo); + } + if (providerList.size() > 0) + return providerList.get(0); + + return null; + } + + @Override + public Provider getProviderByPractitionerNo(String practitionerNoType, String practitionerNo) { + return getProviderByPractitionerNo(new String[] { practitionerNoType }, practitionerNo); + } + + @Override + public Provider getProviderByPractitionerNo(String[] practitionerNoTypes, String practitionerNo) { + if (practitionerNoTypes == null || practitionerNoTypes.length <= 0) { + throw new IllegalArgumentException(); + } + if (practitionerNo == null || practitionerNo.length() <= 0) { + throw new IllegalArgumentException(); + } + + List providerList = (List) getHibernateTemplate().findByNamedParam( + "From Provider p where p.practitionerNoType IN (:types) AND p.practitionerNo=:pId", + new String[] { "types", "pId" }, new Object[] { practitionerNoTypes, practitionerNo }); + // List providerList = getHibernateTemplate().find("From Provider p + // where p.practitionerNoType IN (:types) AND p.practitionerNo=?",new + // Object[]{practitionerNo}); + + if (providerList.size() > 1) { + logger.warn("Found more than 1 provider with practitionerNo=" + practitionerNo); + } + if (providerList.size() > 0) + return providerList.get(0); + + return null; + } + + @Override + public List getUniqueTeams() { + + List providerList = (List) getHibernateTemplate() + .find("select distinct p.Team From Provider p"); + + return providerList; + } + + @Override + public List getBillableProvidersOnTeam(Provider p) { + + List providers = (List) this.getHibernateTemplate().find( + "from Provider p where status='1' and ohip_no!='' and p.Team=? order by last_name, first_name", + p.getTeam()); + + return providers; + } + + @Override + public List getBillableProvidersByOHIPNo(String ohipNo) { + if (ohipNo == null || ohipNo.length() <= 0) { + throw new IllegalArgumentException(); + } + + List providers = (List) this.getHibernateTemplate() + .find("from Provider p where ohip_no like ? order by last_name, first_name", ohipNo); + + if (providers.size() > 1) { + logger.warn("Found more than 1 provider with ohipNo=" + ohipNo); + } + if (providers.isEmpty()) + return null; + else + return providers; + } + + @Override + public List getProvidersWithNonEmptyOhip(LoggedInInfo loggedInInfo) { + return (List) getHibernateTemplate().find( + "FROM Provider WHERE ohip_no != '' and ProviderNo not like ? order by last_name, first_name", + loggedInInfo.getLoggedInProviderNo()); + } + + /** + * Gets all providers with non-empty OHIP number ordered by last,then first name + * + * @return + * Returns the all found providers + */ + @Override + public List getProvidersWithNonEmptyOhip() { + return (List) getHibernateTemplate() + .find("FROM Provider WHERE ohip_no != '' order by last_name, first_name"); + } + + @Override + public List getCurrentTeamProviders(String providerNo) { + String hql = "SELECT p FROM Provider p " + + "WHERE p.Status='1' and p.OhipNo != '' " + + "AND (p.ProviderNo='" + providerNo + + "' or team=(SELECT p2.Team FROM Provider p2 where p2.ProviderNo='" + providerNo + "')) " + + "ORDER BY p.LastName, p.FirstName"; + + return (List) this.getHibernateTemplate().find(hql); + } + + @Override + public List getActiveTeams() { + List providerList = (List) getHibernateTemplate() + .find("select distinct p.Team From Provider p where p.Status = '1' and p.Team != '' order by p.Team"); + return providerList; + } + + @NativeSql({ "provider", "providersite" }) + @Override + public List getActiveTeamsViaSites(String providerNo) { + // Session session = getSession(); + Session session = currentSession(); + try { + // providersite is not mapped in hibernate - this can be rewritten w.o. + // subselect with a cross product IHMO + SQLQuery query = session.createSQLQuery( + "select distinct team from provider p inner join providersite s on s.provider_no = p.provider_no " + + " where s.site_id in (select site_id from providersite where provider_no = '" + providerNo + + "') order by team "); + return query.list(); + } finally { + // this.releaseSession(session); + //session.close(); + } + } + + @Override + public List getProviderByPatientId(Integer patientId) { + String hql = "SELECT p FROM Provider p, Demographic d " + + "WHERE d.ProviderNo = p.ProviderNo " + + "AND d.DemographicNo = ?"; + return (List) this.getHibernateTemplate().find(hql, patientId); + } + + @Override + public List getDoctorsWithNonEmptyCredentials() { + String sql = "FROM Provider p WHERE p.ProviderType = 'doctor' " + + "AND p.Status='1' " + + "AND p.OhipNo IS NOT NULL " + + "AND p.OhipNo != '' " + + "ORDER BY p.LastName, p.FirstName"; + return (List) getHibernateTemplate().find(sql); + } + + @Override + public List getProvidersWithNonEmptyCredentials() { + String sql = "FROM Provider p WHERE p.Status='1' " + + "AND p.OhipNo IS NOT NULL " + + "AND p.OhipNo != '' " + + "ORDER BY p.LastName, p.FirstName"; + return (List) getHibernateTemplate().find(sql); + } + + @Override + public List getProvidersInTeam(String teamName) { + List providerList = (List) getHibernateTemplate() + .find("select distinct p.ProviderNo from Provider p where p.Team = ?", new Object[] { teamName }); + return providerList; + } + + @Override + public List getDistinctProviders() { + List providerList = (List) getHibernateTemplate() + .find("select distinct p.ProviderNo, p.ProviderType from Provider p ORDER BY p.LastName"); + return providerList; + } + + @Override + public List getRecordsAddedAndUpdatedSinceTime(Date date) { + @SuppressWarnings("unchecked") + List providers = (List) getHibernateTemplate() + .find("select distinct p.ProviderNo From Provider p where p.lastUpdateDate > ? ", date); + + return providers; + } + + @SuppressWarnings("unchecked") + @Override + public List searchProviderByNamesString(String searchString, int startIndex, int itemsToReturn) { + String sqlCommand = "select x from Provider x"; + if (searchString != null) { + if (searchString.indexOf(",") != -1 && searchString.split(",").length > 1 + && searchString.split(",")[1].length() > 0) { + sqlCommand = sqlCommand + " where x.LastName like :ln AND x.FirstName like :fn"; + } else { + sqlCommand = sqlCommand + " where x.LastName like :ln"; + } + + } + + // Session session = this.getSession(); + Session session = currentSession(); + try { + Query q = session.createQuery(sqlCommand); + if (searchString != null) { + q.setParameter("ln", "%" + searchString.split(",")[0] + "%"); + if (searchString.indexOf(",") != -1 && searchString.split(",").length > 1 + && searchString.split(",")[1].length() > 0) { + q.setParameter("fn", "%" + searchString.split(",")[1] + "%"); + + } + } + q.setFirstResult(startIndex); + q.setMaxResults(itemsToReturn); + return (q.list()); + } finally { + // this.releaseSession(session); + //session.close(); + } + } + + @SuppressWarnings("unchecked") + @Override + public List search(String term, boolean active, int startIndex, int itemsToReturn) { + String sqlCommand = "select x from Provider x WHERE x.Status = :status "; + + if (term != null && term.length() > 0) { + sqlCommand += "AND (x.LastName like :term OR x.FirstName like :term) "; + } + + sqlCommand += " ORDER BY x.LastName,x.FirstName"; + + // Session session = this.getSession(); + Session session = currentSession(); + try { + Query q = session.createQuery(sqlCommand); + + q.setString("status", active ? "1" : "0"); + if (term != null && term.length() > 0) { + q.setString("term", term + "%"); + } + + q.setFirstResult(startIndex); + q.setMaxResults(itemsToReturn); + return (q.list()); + } finally { + // this.releaseSession(session); + //session.close(); + } + } + + @NativeSql({ "provider", "appointment" }) + @Override + public List getProviderNosWithAppointmentsOnDate(Date appointmentDate) { + // Session session = getSession(); + Session session = currentSession(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + String sql = "SELECT p.provider_no FROM provider p WHERE p.provider_no IN (SELECT DISTINCT a.provider_no FROM appointment a WHERE a.appointment_date = '" + + sdf.format(appointmentDate) + "') " + + "AND p.Status='1'"; + SQLQuery query = session.createSQLQuery(sql); + + return query.list(); + } finally { + // this.releaseSession(session); + //session.close(); + } + } + + @Override + public List getOlisHicProviders() { + UserPropertyDAO userPropertyDAO = SpringUtils.getBean(UserPropertyDAO.class); + // Session session = getSession(); + Session session = currentSession(); + String sql = "FROM Provider p WHERE p.practitionerNo IS NOT NULL AND p.practitionerNo != ''"; + Query query = session.createQuery(sql); + List practitionerNoProviders = query.list(); + + List results = new ArrayList(); + for (Provider practitionerNoProvider : practitionerNoProviders) { + String olisType = userPropertyDAO.getStringValue(practitionerNoProvider.getProviderNo(), + UserProperty.OFFICIAL_OLIS_IDTYPE); + if (olisType != null && !olisType.isEmpty()) { + results.add(practitionerNoProvider); + } + } + //session.close(); + return results; + } + + @Override + public Provider getProviderByPractitionerNoAndOlisType(String practitionerNo, String olisIdentifierType) { + UserPropertyDAO userPropertyDAO = SpringUtils.getBean(UserPropertyDAO.class); + String sql = "FROM Provider p WHERE p.practitionerNo=?"; + + List providers = (List) getHibernateTemplate().find(sql, practitionerNo); + + if (!providers.isEmpty()) { + Provider provider = providers.get(0); + String olisType = userPropertyDAO.getStringValue(provider.getProviderNo(), + UserProperty.OFFICIAL_OLIS_IDTYPE); + if (olisIdentifierType.equals(olisType)) { + return providers.get(0); + } + } + return null; + } + + @Override + public List getOlisProvidersByPractitionerNo(List practitionerNumbers) { + // Session session = getSession(); + Session session = currentSession(); + String sql = "FROM Provider p WHERE p.practitionerNo IN (:practitionerNumbers)"; + Query query = session.createQuery(sql); + query.setParameterList("practitionerNumbers", practitionerNumbers); + List providers = query.list(); + //session.close(); + return providers; + } + + /** + * Gets a list of provider numbers based on the provided list of provider + * numbers + * + * @param providerNumbers The list of provider numbers to get the related + * objects for + * @return A list of providers + */ + @Override + public List getProvidersByIds(List providerNumbers) { + // Session session = getSession(); + Session session = currentSession(); + String sql = "FROM Provider p WHERE p.ProviderNo IN (:providerNumbers)"; + Query query = session.createQuery(sql); + query.setParameterList("providerNumbers", providerNumbers); + + List providers = query.list(); + //session.close(); + return providers; + } + + /** + * Gets a map of provider names with the provider number as the map key based on + * the provided list of provider numbers + * + * @param providerNumbers A list of provider numbers to get the name map for + * @return A map of provider names with their related provider number as the key + */ + @Override + public Map getProviderNamesByIdsAsMap(List providerNumbers) { + Map providerNameMap = new HashMap<>(); + List providers = getProvidersByIds(providerNumbers); + + for (Provider provider : providers) { + providerNameMap.put(provider.getProviderNo(), provider.getFullName()); + } + + return providerNameMap; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDao.java b/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDao.java index 61b2ada505..cfab72481e 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -29,74 +32,22 @@ import org.apache.logging.log4j.Logger; import org.oscarehr.PMmodule.model.SecUserRole; import org.oscarehr.util.MiscUtils; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class SecUserRoleDao extends HibernateDaoSupport { - - private static Logger log = MiscUtils.getLogger(); - - public List getUserRoles(String providerNo) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } - - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from SecUserRole s where s.ProviderNo = ?", providerNo); - - if (log.isDebugEnabled()) { - log.debug("getUserRoles: providerNo=" + providerNo + ",# of results=" + results.size()); - } - - return results; - } +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; - public List getSecUserRolesByRoleName(String roleName) { - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from SecUserRole s where s.RoleName = ?", roleName); +public interface SecUserRoleDao { - return results; - } - - public List findByRoleNameAndProviderNo(String roleName, String providerNo) { - @SuppressWarnings("unchecked") - List results = getHibernateTemplate().find("from SecUserRole s where s.RoleName = ? and s.ProviderNo=?", new Object[]{roleName,providerNo}); + public List getUserRoles(String providerNo); - return results; - } + public List getSecUserRolesByRoleName(String roleName); - public boolean hasAdminRole(String providerNo) { - if (providerNo == null) { - throw new IllegalArgumentException(); - } + public List findByRoleNameAndProviderNo(String roleName, String providerNo); - boolean result = false; - @SuppressWarnings("unchecked") - List results = this.getHibernateTemplate().find("from SecUserRole s where s.ProviderNo = ? and s.RoleName = 'admin'", providerNo); - if (!results.isEmpty()) { - result = true; - } + public boolean hasAdminRole(String providerNo); - if (log.isDebugEnabled()) { - log.debug("hasAdminRole: providerNo=" + providerNo + ",result=" + result); - } + public SecUserRole find(Long id); - return result; - } + public void save(SecUserRole sur); - public SecUserRole find(Long id) { - return this.getHibernateTemplate().get(SecUserRole.class, id); - } + public List getRecordsAddedAndUpdatedSinceTime(Date date); - public void save(SecUserRole sur) { - sur.setLastUpdateDate(new Date()); - this.getHibernateTemplate().save(sur); - } - - public List getRecordsAddedAndUpdatedSinceTime(Date date) { - @SuppressWarnings("unchecked") - List records = getHibernateTemplate().find("select p.ProviderNo From SecUserRole p WHERE p.lastUpdateDate > ?",date); - - return records; - } - } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDaoImpl.java new file mode 100644 index 0000000000..21ad4c4d58 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/SecUserRoleDaoImpl.java @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.Date; +import java.util.List; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.model.SecUserRole; +import org.oscarehr.util.MiscUtils; +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class SecUserRoleDaoImpl extends HibernateDaoSupport implements SecUserRoleDao { + + private static Logger log = MiscUtils.getLogger(); + + @Override + public List getUserRoles(String providerNo) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate() + .find("from SecUserRole s where s.ProviderNo = ?", providerNo); + + if (log.isDebugEnabled()) { + log.debug("getUserRoles: providerNo=" + providerNo + ",# of results=" + results.size()); + } + + return results; + } + + @Override + public List getSecUserRolesByRoleName(String roleName) { + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate() + .find("from SecUserRole s where s.RoleName = ?", roleName); + + return results; + } + + @Override + public List findByRoleNameAndProviderNo(String roleName, String providerNo) { + @SuppressWarnings("unchecked") + List results = (List) getHibernateTemplate().find( + "from SecUserRole s where s.RoleName = ? and s.ProviderNo=?", new Object[] { roleName, providerNo }); + + return results; + } + + @Override + public boolean hasAdminRole(String providerNo) { + if (providerNo == null) { + throw new IllegalArgumentException(); + } + + boolean result = false; + @SuppressWarnings("unchecked") + List results = (List) this.getHibernateTemplate() + .find("from SecUserRole s where s.ProviderNo = ? and s.RoleName = 'admin'", providerNo); + if (!results.isEmpty()) { + result = true; + } + + if (log.isDebugEnabled()) { + log.debug("hasAdminRole: providerNo=" + providerNo + ",result=" + result); + } + + return result; + } + + @Override + public SecUserRole find(Long id) { + return this.getHibernateTemplate().get(SecUserRole.class, id); + } + + @Override + public void save(SecUserRole sur) { + sur.setLastUpdateDate(new Date()); + this.getHibernateTemplate().save(sur); + } + + @Override + public List getRecordsAddedAndUpdatedSinceTime(Date date) { + @SuppressWarnings("unchecked") + List records = (List) getHibernateTemplate() + .find("select p.ProviderNo From SecUserRole p WHERE p.lastUpdateDate > ?", date); + + return records; + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDao.java b/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDao.java index adf2f8d5c0..b0825f6711 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,15 +20,11 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.dao; -import org.springframework.orm.hibernate3.support.HibernateDaoSupport; - -public class StreetHealthDao extends HibernateDaoSupport { - //empty - - - +public interface StreetHealthDao { + } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDaoImpl.java new file mode 100644 index 0000000000..3247a2a370 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/StreetHealthDaoImpl.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import org.springframework.orm.hibernate4.support.HibernateDaoSupport; + +public class StreetHealthDaoImpl extends HibernateDaoSupport implements StreetHealthDao{ + //empty + + + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDao.java b/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDao.java index f34a1da029..646acfc770 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,6 +20,8 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -26,19 +29,10 @@ import org.oscarehr.common.dao.SecObjPrivilegeDao; import org.oscarehr.util.SpringUtils; -public class SurveySecurityDao { +public interface SurveySecurityDao { - //switch the quatro security manager when available - //true = allowed - //false = restricted - public boolean checkPrivilege(String formName, String providerNo) { - //check to see if there's a privilege defined - SecObjPrivilegeDao dao = SpringUtils.getBean(SecObjPrivilegeDao.class); - int count = dao.countObjectsByName("_ucf." + formName); - if (count <= 0) { - return true; - } - - return !dao.findByFormNamePrivilegeAndProviderNo("_ucf." + formName, "x", providerNo).isEmpty(); - } + // switch the quatro security manager when available + // true = allowed + // false = restricted + public boolean checkPrivilege(String formName, String providerNo); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDaoImpl.java new file mode 100644 index 0000000000..fcd44c6192 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/SurveySecurityDaoImpl.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import org.oscarehr.common.dao.SecObjPrivilegeDao; +import org.oscarehr.util.SpringUtils; + +public class SurveySecurityDaoImpl implements SurveySecurityDao { + + // switch the quatro security manager when available + // true = allowed + // false = restricted + @Override + public boolean checkPrivilege(String formName, String providerNo) { + // check to see if there's a privilege defined + SecObjPrivilegeDao dao = SpringUtils.getBean(SecObjPrivilegeDao.class); + int count = dao.countObjectsByName("_ucf." + formName); + if (count <= 0) { + return true; + } + + return !dao.findByFormNamePrivilegeAndProviderNo("_ucf." + formName, "x", providerNo).isEmpty(); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDao.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDao.java index 310adbc36c..ea134b9a5d 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,6 +21,8 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -31,56 +34,16 @@ import org.oscarehr.common.dao.AbstractDao; import org.springframework.stereotype.Repository; -@Repository -public class VacancyClientMatchDao extends AbstractDao { - - public VacancyClientMatchDao() { - super(VacancyClientMatch.class); - } - - public List findByClientIdAndVacancyId(int clientId, int vacancyId){ - Query q = entityManager.createQuery("select x from VacancyClientMatch x where x.client_id = ? and x.vacancy_id = ?"); - q.setParameter(1, clientId); - q.setParameter(2, vacancyId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - public List findByClientId(int clientId){ - Query q = entityManager.createQuery("select x from VacancyClientMatch x where x.client_id = ?"); - q.setParameter(1, clientId); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - public List findBystatus(String status){ - Query q = entityManager.createQuery("select x from VacancyClientMatch x where x.status = ?"); - q.setParameter(1, status); - - @SuppressWarnings("unchecked") - List results = q.getResultList(); - - return results; - } - - - public void updateStatus(String status, int clientId, int vacancyId) { - for(VacancyClientMatch v:this.findByClientIdAndVacancyId(clientId, vacancyId)) { - v.setStatus(status); - } - } +public interface VacancyClientMatchDao extends AbstractDao { + + public List findByClientIdAndVacancyId(int clientId, int vacancyId); + + public List findByClientId(int clientId); + + public List findBystatus(String status); + + public void updateStatus(String status, int clientId, int vacancyId); - public void updateStatusAndRejectedReason(String status, String rejectedReason, int clientId, int vacancyId) { - for(VacancyClientMatch v:this.findByClientIdAndVacancyId(clientId, vacancyId)) { - v.setStatus(status); - v.setRejectionReason(rejectedReason); - } - } + public void updateStatusAndRejectedReason(String status, String rejectedReason, int clientId, int vacancyId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDaoImpl.java new file mode 100644 index 0000000000..ef660ad278 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyClientMatchDaoImpl.java @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.VacancyClientMatch; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class VacancyClientMatchDaoImpl extends AbstractDaoImpl implements VacancyClientMatchDao { + + public VacancyClientMatchDaoImpl() { + super(VacancyClientMatch.class); + } + + @Override + public List findByClientIdAndVacancyId(int clientId, int vacancyId) { + Query q = entityManager + .createQuery("select x from VacancyClientMatch x where x.client_id = ? and x.vacancy_id = ?"); + q.setParameter(1, clientId); + q.setParameter(2, vacancyId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + @Override + public List findByClientId(int clientId) { + Query q = entityManager.createQuery("select x from VacancyClientMatch x where x.client_id = ?"); + q.setParameter(1, clientId); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + @Override + public List findBystatus(String status) { + Query q = entityManager.createQuery("select x from VacancyClientMatch x where x.status = ?"); + q.setParameter(1, status); + + @SuppressWarnings("unchecked") + List results = q.getResultList(); + + return results; + } + + @Override + public void updateStatus(String status, int clientId, int vacancyId) { + for (VacancyClientMatch v : this.findByClientIdAndVacancyId(clientId, vacancyId)) { + v.setStatus(status); + } + } + + @Override + public void updateStatusAndRejectedReason(String status, String rejectedReason, int clientId, int vacancyId) { + for (VacancyClientMatch v : this.findByClientIdAndVacancyId(clientId, vacancyId)) { + v.setStatus(status); + v.setRejectionReason(rejectedReason); + } + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyDao.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyDao.java index 7713a0ff36..2e72db804c 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/VacancyDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,6 +21,8 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -32,76 +35,17 @@ import org.oscarehr.common.dao.AbstractDao; import org.springframework.stereotype.Repository; -@Repository -public class VacancyDao extends AbstractDao { - - public VacancyDao() { - super(Vacancy.class); - } - - @SuppressWarnings("unchecked") - public List getVacanciesByWlProgramId(Integer wlProgramId) { - String sqlCommand = "select x from Vacancy x where x.wlProgramId=?1 order by x.name"; - - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, wlProgramId); - - return query.getResultList(); - } - - @SuppressWarnings("unchecked") - public List getVacanciesByWlProgramIdAndStatus(Integer wlProgramId,String status) { - String sqlCommand = "select x from Vacancy x where x.wlProgramId=?1 and x.status=?2 order by x.name"; - - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, wlProgramId); - query.setParameter(2, status); - - return query.getResultList(); - } - - - @SuppressWarnings("unchecked") - public List getVacanciesByName(String vacancyName) { - String sqlCommand = "select x from Vacancy x where x.name=?1 order by x.name"; - - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, vacancyName); - - return query.getResultList(); - } - - @SuppressWarnings("unchecked") - public List findByStatusAndVacancyId(String status, int vacancyId) { - String sqlCommand = "select x from Vacancy x where x.status=?1 and x.id=?2"; - - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, status); - query.setParameter(2, vacancyId); - - return query.getResultList(); - } +public interface VacancyDao extends AbstractDao { - public Vacancy getVacancyById(int vacancyId) { - String sqlCommand = "select x from Vacancy x where x.id=?1"; + public List getVacanciesByWlProgramId(Integer wlProgramId); - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, vacancyId); + public List getVacanciesByWlProgramIdAndStatus(Integer wlProgramId, String status); - List l = query.getResultList(); - if(l!=null&&!l.isEmpty())return l.get(0); - else return null; - } + public List getVacanciesByName(String vacancyName); + public List findByStatusAndVacancyId(String status, int vacancyId); - @SuppressWarnings("unchecked") - public List findCurrent() { - String sqlCommand = "select x from Vacancy x where x.status=?1"; + public Vacancy getVacancyById(int vacancyId); - Query query = entityManager.createQuery(sqlCommand); - query.setParameter(1, "ACTIVE"); -; - - return query.getResultList(); - } + public List findCurrent(); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyDaoImpl.java new file mode 100644 index 0000000000..e478156cd8 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyDaoImpl.java @@ -0,0 +1,116 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.Vacancy; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class VacancyDaoImpl extends AbstractDaoImpl implements VacancyDao { + + public VacancyDaoImpl() { + super(Vacancy.class); + } + + @SuppressWarnings("unchecked") + @Override + public List getVacanciesByWlProgramId(Integer wlProgramId) { + String sqlCommand = "select x from Vacancy x where x.wlProgramId=?1 order by x.name"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, wlProgramId); + + return query.getResultList(); + } + + @SuppressWarnings("unchecked") + @Override + public List getVacanciesByWlProgramIdAndStatus(Integer wlProgramId, String status) { + String sqlCommand = "select x from Vacancy x where x.wlProgramId=?1 and x.status=?2 order by x.name"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, wlProgramId); + query.setParameter(2, status); + + return query.getResultList(); + } + + @SuppressWarnings("unchecked") + @Override + public List getVacanciesByName(String vacancyName) { + String sqlCommand = "select x from Vacancy x where x.name=?1 order by x.name"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, vacancyName); + + return query.getResultList(); + } + + @SuppressWarnings("unchecked") + @Override + public List findByStatusAndVacancyId(String status, int vacancyId) { + String sqlCommand = "select x from Vacancy x where x.status=?1 and x.id=?2"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, status); + query.setParameter(2, vacancyId); + + return query.getResultList(); + } + + @Override + public Vacancy getVacancyById(int vacancyId) { + String sqlCommand = "select x from Vacancy x where x.id=?1"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, vacancyId); + + List l = query.getResultList(); + if (l != null && !l.isEmpty()) + return l.get(0); + else + return null; + } + + @SuppressWarnings("unchecked") + @Override + public List findCurrent() { + String sqlCommand = "select x from Vacancy x where x.status=?1"; + + Query query = entityManager.createQuery(sqlCommand); + query.setParameter(1, "ACTIVE"); + ; + + return query.getResultList(); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDao.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDao.java index 56d255a535..5878fd6d33 100644 --- a/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,6 +21,8 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -32,44 +35,15 @@ import org.oscarehr.common.dao.AbstractDao; import org.springframework.stereotype.Repository; -@Repository -public class VacancyTemplateDao extends AbstractDao { +public interface VacancyTemplateDao extends AbstractDao { + + public void saveVacancyTemplate(VacancyTemplate obj); + + public void mergeVacancyTemplate(VacancyTemplate obj); + + public VacancyTemplate getVacancyTemplate(Integer templateId); - public VacancyTemplateDao() { - super(VacancyTemplate.class); - } + public List getVacancyTemplateByWlProgramId(Integer wlProgramId); - public void saveVacancyTemplate(VacancyTemplate obj) { - persist(obj); - } - - public void mergeVacancyTemplate(VacancyTemplate obj) { - merge(obj); - } - - public VacancyTemplate getVacancyTemplate(Integer templateId) { - return find(templateId); - } - - public List getVacancyTemplateByWlProgramId(Integer wlProgramId) { - Query query = entityManager.createQuery("select x from VacancyTemplate x where x.wlProgramId=?"); - query.setParameter(1, wlProgramId); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - - return results; - } - - public List getActiveVacancyTemplatesByWlProgramId(Integer wlProgramId) { - Query query = entityManager.createQuery("select x from VacancyTemplate x where x.wlProgramId=? and x.active=?"); - query.setParameter(1, wlProgramId); - query.setParameter(2, true); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - - return results; - } + public List getActiveVacancyTemplatesByWlProgramId(Integer wlProgramId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDaoImpl.java new file mode 100644 index 0000000000..e76d7d9fd1 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/VacancyTemplateDaoImpl.java @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.dao; + +import java.util.List; + +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.VacancyTemplate; +import org.oscarehr.common.dao.AbstractDaoImpl; +import org.springframework.stereotype.Repository; + +@Repository +public class VacancyTemplateDaoImpl extends AbstractDaoImpl implements VacancyTemplateDao { + + public VacancyTemplateDaoImpl() { + super(VacancyTemplate.class); + } + + @Override + public void saveVacancyTemplate(VacancyTemplate obj) { + persist(obj); + } + + @Override + public void mergeVacancyTemplate(VacancyTemplate obj) { + merge(obj); + } + + @Override + public VacancyTemplate getVacancyTemplate(Integer templateId) { + return find(templateId); + } + + @Override + public List getVacancyTemplateByWlProgramId(Integer wlProgramId) { + Query query = entityManager.createQuery("select x from VacancyTemplate x where x.wlProgramId=?"); + query.setParameter(1, wlProgramId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } + + @Override + public List getActiveVacancyTemplatesByWlProgramId(Integer wlProgramId) { + Query query = entityManager.createQuery("select x from VacancyTemplate x where x.wlProgramId=? and x.active=?"); + query.setParameter(1, wlProgramId); + query.setParameter(2, true); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + + return results; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDao.java b/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDao.java index 586e571705..6b61835b4c 100755 --- a/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDao.java +++ b/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDao.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,6 +21,8 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ package org.oscarehr.PMmodule.dao; @@ -49,598 +52,41 @@ import org.oscarehr.match.vacancy.VacancyTemplateData; import org.springframework.stereotype.Repository; -@Repository -public class WaitlistDao { +public interface WaitlistDao { + + public List getClientMatches(int vacancyId); + + public List getClientMatchesWithMinPercentage(int vacancyId, double percentage); - @PersistenceContext - protected EntityManager entityManager = null; - - private List constructMatchBOList(List results) { - - List list = new ArrayList(); - - for (Object[] cols : results) { - MatchBO out = new MatchBO(); - out.setClientID((Integer)cols[0]); - out.setClientName((String)cols[1]); - out.setClientName(out.getClientName() + " " + (String)cols[2]); - - if (cols[3] instanceof BigInteger){ // to avoid java.lang.ClassCastException exception - out.setDaysInWaitList(((BigInteger)cols[3]).intValue()); - } else if (cols[3] instanceof Long) { - out.setDaysInWaitList(((Long)cols[3]).intValue()); - } - - if (cols[4] instanceof BigInteger){ - out.setDaysSinceLastContact(((BigInteger)cols[4]).intValue()); - } else if (cols[4] instanceof Long){ - out.setDaysSinceLastContact(((Long)cols[4]).intValue()); - } - out.setFormDataID((Integer)cols[5]); - out.setPercentageMatch((Double)cols[6]); - out.setProportion((String)cols[7]); - list.add(out); - } - return list; - } - - @SuppressWarnings("unchecked") - public List getClientMatches(int vacancyId) { - String sql = "SELECT client_id, first_name, last_name, DATEDIFF(CURDATE(), e.form_date) days_in_waitlist, " + - "DATEDIFF(CURDATE(), last_contact_date) last_contact_days, form_id, match_percent, proportion " - + " FROM vacancy_client_match m, demographic d, eform_data e WHERE vacancy_id = ?1 " + - "and d.demographic_no = m.client_id and m.form_id = e.fdid" - + " order by match_percent desc"; - - Query q = entityManager.createNativeQuery(sql); - q.setParameter(1, vacancyId); - - return constructMatchBOList(q.getResultList()); - } - - @SuppressWarnings("unchecked") - public List getClientMatchesWithMinPercentage(int vacancyId, double percentage) { - String sql = "SELECT client_id, first_name, last_name, DATEDIFF(CURDATE(), e.form_date) days_in_waitlist, " + - "DATEDIFF(CURDATE(), last_contact_date) last_contact_days, form_id, match_percent, proportion " - + " FROM vacancy_client_match m, demographic d, eform_data e WHERE vacancy_id = ?1 " + - "and d.demographic_no = m.client_id and m.form_id = e.fdid and m.match_percent>=?2" - + " order by match_percent desc"; - - Query q = entityManager.createNativeQuery(sql); - q.setParameter(1, vacancyId); - q.setParameter(2, percentage); - - return constructMatchBOList(q.getResultList()); - } - - public Collection searchForMatchingEforms(CriteriasBO crits){ - Map forms=new HashMap(); - - String sql="SELECT fdid, demographic_no, form_date FROM eform_data ef WHERE 1=1\n"; - - for(CriteriaBO crit:crits.crits){ - if(crit.value!=null){ - sql=sql+" AND ef.fdid IN (select fdid from eform_values where var_name=?1 and var_value=?2)\n"; - }else if(crit.rangeStart!=null){ - sql=sql+" AND ef.fdid IN (select fdid from eform_values where var_name=?1 and (var_value BETWEEN ?2 and ?3))\n"; - }else if(crit.values!=null){ - sql=sql+" AND ef.fdid IN (select fdid from eform_values where var_name=?1 and ("; - for(int i=0;i0) sql=sql+" OR "; - sql=sql+"(CONCAT(',',var_value,',') LIKE CONCAT('%,',?" + (i+2)+",',%'))"; - } - sql=sql+"))\n"; - } - } - Query query = entityManager.createNativeQuery(sql); - int c=1; - for(CriteriaBO crit:crits.crits){ - query.setParameter(c++, crit.field); - if(crit.value!=null){ - query.setParameter(c++, crit.value); - }else if(crit.rangeStart!=null){ - query.setParameter(c++, crit.rangeStart); - query.setParameter(c++, crit.rangeEnd); - }else if(crit.values!=null){ - for(int i=0;i results = query.getResultList(); - for (Object[] cols : results) { - EFormData f = new EFormData(); - f.setId((Integer)cols[0]); - f.setDemographicId((Integer)cols[1]); - f.setFormDate((Timestamp)cols[2]); - EFormData prior=forms.get(f.getId()); - if(prior==null || prior.getFormDate().getTime() searchForMatchingEforms(CriteriasBO crits); - - public List listDisplayVacanciesForWaitListProgram(int programID) { - List bos = new ArrayList(); - String queryString = "SELECT v.id, t.NAME, v.dateCreated FROM vacancy v JOIN vacancy_template t ON " - + "v.templateId=t.TEMPLATE_ID WHERE t.WL_PROGRAM_ID=?1 and v.status=?2"; - - Query query = entityManager.createNativeQuery(queryString); - query.setParameter(1, programID); - query.setParameter(2, "active"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - for (Object[] cols : results) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - bo.setVacancyID((Integer)cols[0]); - bo.setVacancyTemplateName((String)cols[1]); - bo.setCreated((Date)cols[2]); - bos.add(bo); - } - return bos; - } - - - public List listDisplayVacanciesForAllWaitListPrograms() { - List bos = new ArrayList(); - String queryString = "SELECT v.id, t.NAME as tname, v.dateCreated, p.name as pname, v.vacancyName, v.wlProgramId FROM vacancy v JOIN vacancy_template t ON " + - "v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE v.status=?1 order by v.id asc"; - - Query query = entityManager.createNativeQuery(queryString); - query.setParameter(1, "active"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - for (Object[] cols : results) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - bo.setVacancyID((Integer)cols[0]); - bo.setVacancyTemplateName((String)cols[1]); - bo.setCreated((Date)cols[2]); - bo.setProgramName((String)cols[3]); - bo.setVacancyName((String)cols[4]); - bo.setProgramId((Integer)cols[5]); - bos.add(bo); - } - - return bos; - } + public List listDisplayVacanciesForWaitListProgram(int programID); - public List getDisplayVacanciesForAgencyProgram(int programID) { - List bos = new ArrayList(); - String queryString = "SELECT v.id, t.NAME as tname, v.dateCreated, p.name as pname, v.vacancyName, v.wlProgramId FROM vacancy v JOIN vacancy_template t ON" + - " v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE t.WL_PROGRAM_ID=?1 and v.status=?2"; - - Query query = entityManager.createNativeQuery(queryString); - query.setParameter(1, programID); - query.setParameter(2, "active"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - for (Object[] cols : results) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - bo.setVacancyID((Integer)cols[0]); - bo.setVacancyTemplateName((String)cols[1]); - bo.setCreated((Date)cols[2]); - bo.setProgramName((String)cols[3]); - bo.setVacancyName((String)cols[4]); - bo.setProgramId((Integer)cols[5]); - bos.add(bo); - } - - return bos; - } + public List listDisplayVacanciesForAllWaitListPrograms(); - public VacancyDisplayBO getDisplayVacancy(int vacancyID) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - String queryString = "SELECT v.vacancyName, t.NAME, " + - "v.dateCreated, p.name, v.vacancyName FROM vacancy v JOIN vacancy_template t ON v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE v.id=?1"; - - Query query = entityManager.createNativeQuery(queryString); - query.setParameter(1, vacancyID); - - @SuppressWarnings("unchecked") - List rows = query.getResultList(); - if(rows.size()==0) return null; - Object[] cols = rows.get(0); - if(cols != null){ - bo.setVacancyName((String)cols[0]); - bo.setVacancyTemplateName((String)cols[1]); - bo.setCreated((Date)cols[2]); - bo.setProgramName((String)cols[3]); - bo.setVacancyName((String)cols[4]); - } - loadStats(bo); - return bo; - } + public List getDisplayVacanciesForAgencyProgram(int programID); - public void loadStats(VacancyDisplayBO bo) { - String queryStr = "SELECT " + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?1 and status='REJECTED') " + - "as rejected, " + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?2 and status='ACCEPTED') as accepted, " - + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?3 and status='PENDING') as pending"; - Query query = entityManager.createNativeQuery(queryStr); - query.setParameter(1, bo.getVacancyID()); - query.setParameter(2, bo.getVacancyID()); - query.setParameter(3, bo.getVacancyID()); - - @SuppressWarnings("unchecked") - List rows = query.getResultList(); - if(rows.size()>0) { - Object[] result = rows.get(0); - if(result != null){ - bo.setRejectedCount(((BigInteger)result[0]).intValue()); - bo.setAcceptedCount(((BigInteger)result[1]).intValue()); - bo.setPendingCount(((BigInteger)result[2]).intValue()); - } - } - } + public VacancyDisplayBO getDisplayVacancy(int vacancyID); - public Integer getProgramIdByVacancyId(int vacancyId) { - List programIds = new ArrayList(); - //String queryString = "SELECT t.PROGRAM_ID FROM vacancy v JOIN vacancy_template t ON " + "v.templateId=t.TEMPLATE_ID WHERE v.id=?1"; - String queryString = "SELECT wlProgramId FROM vacancy where id=?1"; - Query query = entityManager.createNativeQuery(queryString); - query.setParameter(1, vacancyId); - - @SuppressWarnings("unchecked") - List rows = query.getResultList(); - if(rows.size()==0) return null; - Integer result = rows.get(0); - - if(result != null){ - programIds.add(result); - } - - if (!programIds.isEmpty()) { - return programIds.get(0); - } else { - return null; - } - } - + public void loadStats(VacancyDisplayBO bo); + public Integer getProgramIdByVacancyId(int vacancyId); - public List listNoOfVacanciesForWaitListProgram() { - final List bos = new ArrayList(); - String queryStr = "SELECT p.id , COUNT(*) vacncyCnt,v.vacancyName,v.dateCreated,v.id FROM vacancy v JOIN program p ON " - + "v.wlProgramId=p.id where v.status=?1 GROUP by v.wlProgramId"; - Query query = entityManager.createNativeQuery(queryStr); - query.setParameter(1, "active"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - for (Object[] cols : results) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - bo.setProgramId((Integer)cols[0]); - bo.setNoOfVacancy(((BigInteger)cols[1]).intValue()); - bo.setVacancyName((String)cols[2]); - bo.setCreated((java.util.Date)cols[3]); - bo.setVacancyID((Integer)cols[4]); - bos.add(bo); - } - - return bos; - } + public List listNoOfVacanciesForWaitListProgram(); - public List listVacanciesForWaitListProgram() { - final List bos = new ArrayList(); - String queryStr = "SELECT p.id, v.vacancyName, v.dateCreated, v.id as vacancyId, vt.name FROM vacancy v, program p, vacancy_template vt where " - + "v.wlProgramId=p.id and v.templateId=vt.TEMPLATE_ID and v.status=?1 order by v.vacancyName"; - Query query = entityManager.createNativeQuery(queryStr); - query.setParameter(1, "active"); - - @SuppressWarnings("unchecked") - List results = query.getResultList(); - for (Object[] cols : results) { - VacancyDisplayBO bo = new VacancyDisplayBO(); - bo.setProgramId((Integer)cols[0]); - bo.setVacancyName((String)cols[1]); - bo.setCreated((java.util.Date)cols[2]); - bo.setVacancyID((Integer)cols[3]); - bo.setVacancyTemplateName((String)cols[4]); - bos.add(bo); - } - - return bos; - } - private static final String QUERY_ALL_CLIENT_DATA = "SELECT DISTINCT demographic_no, fdid, var_name, var_value " - + "FROM eform_values LEFT JOIN client_referral cr ON cr.client_id=demographic_no, " - + "(SELECT demographic_no AS dmb,MAX(fdid) AS ffdid FROM eform_values GROUP BY demographic_no) xyz " - + "WHERE cr.referral_id IS NULL AND " + "demographic_no= xyz.dmb AND fdid=xyz.ffdid"; - - private static final String QUERY_ALL_CLIENT_DATA_BY_PROGRAMID = "SELECT DISTINCT ef.demographic_no, ef.fdid, ef.var_name, ef.var_value " - + "FROM eform_values ef LEFT JOIN client_referral cr ON cr.client_id=ef.demographic_no" - + " where cr.program_id=?1 and ef.var_name in ('age-years','gender','current-housing','preferred-language','location-preferences','referrer-contact-province','contact-province','Age category','prepared-live-toronto','bed_community_program_id','has-mental-illness-primary','current-legal-involvements')" - + " and LENGTH(ef.var_value)>0 and not exists (select * from eform_values where demographic_no=ef.demographic_no and var_name=ef.var_name and fdid>ef.fdid)"; + public List listVacanciesForWaitListProgram(); - - private static final String QUERY_GET_CLIENT_DATA = "SELECT DISTINCT ef.demographic_no, ef.fdid, ef.var_name, ef.var_value " - + "FROM eform_values ef WHERE ef.demographic_no= ?1 and " - +" ef.var_name in ('age-years','gender','current-housing','preferred-language','location-preferences','referrer-contact-province','contact-province','Age category','prepared-live-toronto','bed_community_program_id','has-mental-illness-primary','current-legal-involvements')" - + "and LENGTH(ef.var_value)>0 AND not exists (select * from eform_values where ef.demographic_no=demographic_no and var_name=ef.var_name and fdid>ef.fdid)"; + public List getAllClientsData(); + public List getAllClientsDataByProgramId(int wlProgramId); - - - public List getAllClientsData() { - Map clientsDataList = new HashMap(); - - Query query = entityManager.createNativeQuery(QUERY_ALL_CLIENT_DATA); - - @SuppressWarnings("unchecked") - Listresult = query.getResultList(); - for (Object[] cols : result) { - Integer demographicId = (Integer)cols[0]; - Integer formId = (Integer)cols[1]; - String paramName = (String)cols[2]; - String paramValue = (String)cols[3]; - if(demographicId == null) { - demographicId = 0; - } - ClientData clientData = clientsDataList.get(demographicId); - if(clientData == null){ - clientData = new ClientData(); - clientData.setClientId(demographicId); - clientData.setFormId(formId); - clientsDataList.put(demographicId, clientData); - } - - if (paramName != null) { - paramName = paramName.toLowerCase(); - } - if ("has-mental-illness-primary".equalsIgnoreCase(paramValue) && "no".equalsIgnoreCase(paramValue)) { - String[] paramsValues = intakeVarToCriteriaFiled(paramValue,paramValue); - if (paramsValues.length == 4) { - clientData.getClientData().put(paramsValues[0], paramsValues[1]); - clientData.getClientData().put(paramsValues[2], paramsValues[3]); - } - } else { - String[] paramVal = intakeVarToCriteriaFiled(paramValue,paramValue); - clientData.getClientData().put(paramVal[0], paramVal[1]); - } - } - return new ArrayList(clientsDataList.values()); - } - - public List getAllClientsDataByProgramId(int wlProgramId) { - Map clientsDataList = new HashMap(); - - Query query = entityManager.createNativeQuery(QUERY_ALL_CLIENT_DATA_BY_PROGRAMID); - query.setParameter(1, wlProgramId); - - @SuppressWarnings("unchecked") - Listresult = query.getResultList(); - for (Object[] cols : result) { - Integer demographicId = (Integer)cols[0]; - Integer formId = (Integer)cols[1]; - String paramName = (String)cols[2]; - String paramValue = (String)cols[3]; - if(demographicId == null) { - demographicId = 0; - } - ClientData clientData = clientsDataList.get(demographicId); - if(clientData == null){ - clientData = new ClientData(); - clientData.setClientId(demographicId); - clientData.setFormId(formId); - clientsDataList.put(demographicId, clientData); - } - - if (paramName != null) { - paramName = paramName.toLowerCase(); - } - if ("has-mental-illness-primary".equalsIgnoreCase(paramName) && !"no".equalsIgnoreCase(paramValue)) { - String[] paramsValues = intakeVarToCriteriaFiled(paramName,paramValue); - if (paramsValues.length == 4) { - clientData.getClientData().put(paramsValues[0], paramsValues[1]); - clientData.getClientData().put(paramsValues[2], paramsValues[3]); - } - } else { - String[] paramVal = intakeVarToCriteriaFiled(paramName,paramValue); - clientData.getClientData().put(paramVal[0], paramVal[1]); - } - } - return new ArrayList(clientsDataList.values()); - } - - private String[] intakeVarToCriteriaFiled(String varName, String varValue) { - if ("age-years".equalsIgnoreCase(varName) || "age category".equalsIgnoreCase(varName)) { - return new String[]{"age",varValue}; - } else if ("gender".equalsIgnoreCase(varName)) { - return new String[]{"gender",varValue}; - } else if ("preferred-language".equalsIgnoreCase(varName)) { - if ("eng".equalsIgnoreCase(varValue) || "english".equalsIgnoreCase(varValue)) { - return new String[]{"language","English"}; - } else if ("fre".equalsIgnoreCase(varValue) || "french".equalsIgnoreCase(varValue)) { - return new String[]{"language","French"}; - } else { - return new String[]{"language","Other"}; - } - } else if ("location-preferences".equalsIgnoreCase(varName)){ - return new String[]{"area",varValue}; - } else if ("prepared-live-toronto".equalsIgnoreCase(varName)) { - if ("yes".equalsIgnoreCase(varValue)) { - return new String[]{"area", "Toronto"}; - } - } else if ("current-housing".equalsIgnoreCase(varName)) { - if ("other".equalsIgnoreCase(varValue)) { - return new String[]{"residence", "Homeless"}; - } else if ("no-fixed-address".equalsIgnoreCase(varValue)) { - return new String[]{"residence", "Transitional"}; - } else { - return new String[]{"residence", "Housed"}; - } - } else if ("has-mental-illness-primary".equalsIgnoreCase(varName)) { - if (!"no".equalsIgnoreCase(varValue) && !"unknown".equalsIgnoreCase(varValue)) { - return new String[]{"Serious and Persistent Mental Illness Diagnosis", varValue, "Serious and Persistent Mental Illness Diagnosis", "No Formal Diagnosis"}; - } else if (!"no".equalsIgnoreCase(varValue)) { - return new String[]{"Serious and Persistent Mental Illness Diagnosis", "Formal Diagnosis", "Serious and Persistent Mental Illness Diagnosis", varValue}; - } - } else if ("current-legal-involvements".equalsIgnoreCase(varName)) { - return new String[]{"Legal History", varValue}; - } - return new String[]{varName, varValue}; - } - - public ClientData getClientData(int clientId) { - ClientData clientData = new ClientData(); - clientData.setClientId(clientId); - - Query query = entityManager.createNativeQuery(QUERY_GET_CLIENT_DATA); - query.setParameter(1, clientId); - - @SuppressWarnings("unchecked") - List rows = query.getResultList(); - if(rows.size()==0) return clientData; - for (Object[] cols : rows) { - Integer demographicId = (Integer)cols[0]; - Integer formId = (Integer)cols[1]; - String paramName = (String)cols[2]; - String paramValue = (String)cols[3]; - if(demographicId == null) { - demographicId = 0; - } - clientData.setFormId(formId); - - if (paramName != null) { - paramName = paramName.toLowerCase(); - } - if ("has-mental-illness-primary".equalsIgnoreCase(paramName) && "no".equalsIgnoreCase(paramValue)) { - String[] paramsValues = intakeVarToCriteriaFiled(paramName,paramValue); - if (paramsValues.length == 4) { - clientData.getClientData().put(paramsValues[0], paramsValues[1]); - clientData.getClientData().put(paramsValues[2], paramsValues[3]); - } - } else { - String[] paramVal = intakeVarToCriteriaFiled(paramName,paramValue); - clientData.getClientData().put(paramVal[0], paramVal[1]); - } - } - - return clientData; - } + public ClientData getClientData(int clientId); - - - private static final String QUERY_VACANCY_DATA = "SELECT v.id, v.wlProgramId, ct.field_name,ct.field_type," - + "c.criteria_value,cso.option_value,c.range_start_value,c.range_end_value " - + "FROM criteria c JOIN criteria_type ct ON c.CRITERIA_TYPE_ID=ct.CRITERIA_TYPE_ID " - + "LEFT JOIN criteria_selection_option cso ON cso.CRITERIA_ID=c.CRITERIA_ID " - + "JOIN vacancy v ON v.id=c.VACANCY_ID WHERE v.id=?1"; - - private static final String QUERY_VACANCY_DATA_BY_PROGRAMID = "SELECT v.id, v.wlProgramId, ct.field_name,ct.field_type," - + "c.criteria_value,cso.option_value,c.range_start_value,c.range_end_value " - + "FROM criteria c JOIN criteria_type ct ON c.CRITERIA_TYPE_ID=ct.CRITERIA_TYPE_ID " - + "LEFT JOIN criteria_selection_option cso ON cso.CRITERIA_ID=c.CRITERIA_ID " - + "JOIN vacancy v ON v.id=c.VACANCY_ID WHERE v.id=?1 and v.wlProgramId=?2"; - + // private static final String field_type_one = "select_one"; + // private static final String field_type_number = "number"; - private static final String field_type_multiple = "select_multiple"; - private static final String field_type_range = "select_one_range"; - //private static final String field_type_one = "select_one"; - //private static final String field_type_number = "number"; - - - public VacancyData loadVacancyData(final int vacancyId) { - VacancyData vacancyData = new VacancyData(); - Vacancy vacancy = VacancyTemplateManager.getVacancyById(vacancyId); - if (vacancy == null) { - return vacancyData; - } - vacancyData.setVacancy_id(vacancy.getId()); - vacancyData.setProgram_id(vacancy.getWlProgramId()); - Query query = entityManager.createNativeQuery(QUERY_VACANCY_DATA); - query.setParameter(1, vacancyId); - - @SuppressWarnings("unchecked") - Listresults = query.getResultList(); - for (Object[] cols : results) { - - String fieldName = (String)cols[2]; - String fieldType = (String)cols[3]; - String critValue = (String)cols[4]; - String optionValue = (String)cols[5]; - Integer rangeStart = (Integer)cols[6]; - Integer rangeEnd = (Integer)cols[7]; - if (fieldName != null) { - fieldName = fieldName.toLowerCase(Locale.ENGLISH); - } - VacancyTemplateData vtData = new VacancyTemplateData(); - vtData.setParam(fieldName); - if (field_type_range.equals(fieldType)) { - vtData.setRange(true); - vtData.addRange(rangeStart, rangeEnd); - } else { - if (field_type_multiple.equals(fieldType)) { - VacancyTemplateData vtMultiData = vacancyData.getVacancyData().get(fieldName); - if (vtMultiData != null) { - vtData = vtMultiData; - } - } - if (critValue != null) { - vtData.getValues().add(critValue); - } else { - vtData.getValues().add(optionValue); - } - } - - vacancyData.getVacancyData().put(vtData.getParam(), vtData); - } - - return vacancyData; - } - - public VacancyData loadVacancyData(final int vacancyId, final int wlProgramId) { - VacancyData vacancyData = new VacancyData(); - Vacancy vacancy = VacancyTemplateManager.getVacancyById(vacancyId); - if (vacancy == null) { - return vacancyData; - } - vacancyData.setVacancy_id(vacancy.getId()); - vacancyData.setProgram_id(vacancy.getWlProgramId()); - Query query = entityManager.createNativeQuery(QUERY_VACANCY_DATA_BY_PROGRAMID); - query.setParameter(1, vacancyId); - query.setParameter(2, wlProgramId); - - @SuppressWarnings("unchecked") - Listresults = query.getResultList(); - for (Object[] cols : results) { - String fieldName = (String)cols[2]; - String fieldType = (String)cols[3]; - String critValue = (String)cols[4]; - String optionValue = (String)cols[5]; - Integer rangeStart = (Integer)cols[6]; - Integer rangeEnd = (Integer)cols[7]; - if (fieldName != null) { - fieldName = fieldName.toLowerCase(Locale.ENGLISH); - } - VacancyTemplateData vtData = new VacancyTemplateData(); - vtData.setParam(fieldName); - if (field_type_range.equals(fieldType)) { - vtData.setRange(true); - vtData.addRange(rangeStart, rangeEnd); - } else { - if (field_type_multiple.equals(fieldType)) { - VacancyTemplateData vtMultiData = vacancyData.getVacancyData().get(fieldName); - if (vtMultiData != null) { - vtData = vtMultiData; - } - } - if (critValue != null) { - vtData.getValues().add(critValue); - } else { - vtData.getValues().add(optionValue); - } - } - vacancyData.getVacancyData().put(vtData.getParam(), vtData); - } - - return vacancyData; - } + public VacancyData loadVacancyData(final int vacancyId); + public VacancyData loadVacancyData(final int vacancyId, final int wlProgramId); } diff --git a/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDaoImpl.java b/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDaoImpl.java new file mode 100644 index 0000000000..a6b52d5be3 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/dao/WaitlistDaoImpl.java @@ -0,0 +1,666 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for the + * Department of Family Medicine + * McMaster University + * Hamilton + * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.dao; + +import java.math.BigInteger; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + +import org.oscarehr.PMmodule.model.Vacancy; +import org.oscarehr.PMmodule.service.VacancyTemplateManager; +import org.oscarehr.PMmodule.service.VacancyTemplateManagerImpl; +import org.oscarehr.PMmodule.wlmatch.CriteriaBO; +import org.oscarehr.PMmodule.wlmatch.CriteriasBO; +import org.oscarehr.PMmodule.wlmatch.MatchBO; +import org.oscarehr.PMmodule.wlmatch.VacancyDisplayBO; +import org.oscarehr.common.model.EFormData; +import org.oscarehr.match.client.ClientData; +import org.oscarehr.match.vacancy.VacancyData; +import org.oscarehr.match.vacancy.VacancyTemplateData; +import org.springframework.stereotype.Repository; + +@Repository +public class WaitlistDaoImpl implements WaitlistDao { + + @PersistenceContext + protected EntityManager entityManager = null; + + private List constructMatchBOList(List results) { + + List list = new ArrayList(); + + for (Object[] cols : results) { + MatchBO out = new MatchBO(); + out.setClientID((Integer) cols[0]); + out.setClientName((String) cols[1]); + out.setClientName(out.getClientName() + " " + (String) cols[2]); + + if (cols[3] instanceof BigInteger) { // to avoid java.lang.ClassCastException exception + out.setDaysInWaitList(((BigInteger) cols[3]).intValue()); + } else if (cols[3] instanceof Long) { + out.setDaysInWaitList(((Long) cols[3]).intValue()); + } + + if (cols[4] instanceof BigInteger) { + out.setDaysSinceLastContact(((BigInteger) cols[4]).intValue()); + } else if (cols[4] instanceof Long) { + out.setDaysSinceLastContact(((Long) cols[4]).intValue()); + } + out.setFormDataID((Integer) cols[5]); + out.setPercentageMatch((Double) cols[6]); + out.setProportion((String) cols[7]); + list.add(out); + } + return list; + } + + @SuppressWarnings("unchecked") + @Override + public List getClientMatches(int vacancyId) { + String sql = "SELECT client_id, first_name, last_name, DATEDIFF(CURDATE(), e.form_date) days_in_waitlist, " + + "DATEDIFF(CURDATE(), last_contact_date) last_contact_days, form_id, match_percent, proportion " + + " FROM vacancy_client_match m, demographic d, eform_data e WHERE vacancy_id = ?1 " + + "and d.demographic_no = m.client_id and m.form_id = e.fdid" + + " order by match_percent desc"; + + Query q = entityManager.createNativeQuery(sql); + q.setParameter(1, vacancyId); + + return constructMatchBOList(q.getResultList()); + } + + @SuppressWarnings("unchecked") + @Override + public List getClientMatchesWithMinPercentage(int vacancyId, double percentage) { + String sql = "SELECT client_id, first_name, last_name, DATEDIFF(CURDATE(), e.form_date) days_in_waitlist, " + + "DATEDIFF(CURDATE(), last_contact_date) last_contact_days, form_id, match_percent, proportion " + + " FROM vacancy_client_match m, demographic d, eform_data e WHERE vacancy_id = ?1 " + + "and d.demographic_no = m.client_id and m.form_id = e.fdid and m.match_percent>=?2" + + " order by match_percent desc"; + + Query q = entityManager.createNativeQuery(sql); + q.setParameter(1, vacancyId); + q.setParameter(2, percentage); + + return constructMatchBOList(q.getResultList()); + } + + @Override + public Collection searchForMatchingEforms(CriteriasBO crits) { + Map forms = new HashMap(); + + String sql = "SELECT fdid, demographic_no, form_date FROM eform_data ef WHERE 1=1\n"; + + for (CriteriaBO crit : crits.crits) { + if (crit.value != null) { + sql = sql + " AND ef.fdid IN (select fdid from eform_values where var_name=?1 and var_value=?2)\n"; + } else if (crit.rangeStart != null) { + sql = sql + + " AND ef.fdid IN (select fdid from eform_values where var_name=?1 and (var_value BETWEEN ?2 and ?3))\n"; + } else if (crit.values != null) { + sql = sql + " AND ef.fdid IN (select fdid from eform_values where var_name=?1 and ("; + for (int i = 0; i < crit.values.length; i++) { + if (i > 0) + sql = sql + " OR "; + sql = sql + "(CONCAT(',',var_value,',') LIKE CONCAT('%,',?" + (i + 2) + ",',%'))"; + } + sql = sql + "))\n"; + } + } + Query query = entityManager.createNativeQuery(sql); + int c = 1; + for (CriteriaBO crit : crits.crits) { + query.setParameter(c++, crit.field); + if (crit.value != null) { + query.setParameter(c++, crit.value); + } else if (crit.rangeStart != null) { + query.setParameter(c++, crit.rangeStart); + query.setParameter(c++, crit.rangeEnd); + } else if (crit.values != null) { + for (int i = 0; i < crit.values.length; i++) { + query.setParameter(c++, crit.values[i]); + } + } + } + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + EFormData f = new EFormData(); + f.setId((Integer) cols[0]); + f.setDemographicId((Integer) cols[1]); + f.setFormDate((Timestamp) cols[2]); + EFormData prior = forms.get(f.getId()); + if (prior == null || prior.getFormDate().getTime() < f.getFormDate().getTime()) { + forms.put(f.getId(), f); + } + } + return forms.values(); + } + + @Override + public List listDisplayVacanciesForWaitListProgram(int programID) { + List bos = new ArrayList(); + String queryString = "SELECT v.id, t.NAME, v.dateCreated FROM vacancy v JOIN vacancy_template t ON " + + "v.templateId=t.TEMPLATE_ID WHERE t.WL_PROGRAM_ID=?1 and v.status=?2"; + + Query query = entityManager.createNativeQuery(queryString); + query.setParameter(1, programID); + query.setParameter(2, "active"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + bo.setVacancyID((Integer) cols[0]); + bo.setVacancyTemplateName((String) cols[1]); + bo.setCreated((Date) cols[2]); + bos.add(bo); + } + return bos; + } + + @Override + public List listDisplayVacanciesForAllWaitListPrograms() { + List bos = new ArrayList(); + String queryString = "SELECT v.id, t.NAME as tname, v.dateCreated, p.name as pname, v.vacancyName, v.wlProgramId FROM vacancy v JOIN vacancy_template t ON " + + + "v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE v.status=?1 order by v.id asc"; + + Query query = entityManager.createNativeQuery(queryString); + query.setParameter(1, "active"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + bo.setVacancyID((Integer) cols[0]); + bo.setVacancyTemplateName((String) cols[1]); + bo.setCreated((Date) cols[2]); + bo.setProgramName((String) cols[3]); + bo.setVacancyName((String) cols[4]); + bo.setProgramId((Integer) cols[5]); + bos.add(bo); + } + + return bos; + } + + @Override + public List getDisplayVacanciesForAgencyProgram(int programID) { + List bos = new ArrayList(); + String queryString = "SELECT v.id, t.NAME as tname, v.dateCreated, p.name as pname, v.vacancyName, v.wlProgramId FROM vacancy v JOIN vacancy_template t ON" + + + " v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE t.WL_PROGRAM_ID=?1 and v.status=?2"; + + Query query = entityManager.createNativeQuery(queryString); + query.setParameter(1, programID); + query.setParameter(2, "active"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + bo.setVacancyID((Integer) cols[0]); + bo.setVacancyTemplateName((String) cols[1]); + bo.setCreated((Date) cols[2]); + bo.setProgramName((String) cols[3]); + bo.setVacancyName((String) cols[4]); + bo.setProgramId((Integer) cols[5]); + bos.add(bo); + } + + return bos; + } + + @Override + public VacancyDisplayBO getDisplayVacancy(int vacancyID) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + String queryString = "SELECT v.vacancyName, t.NAME, " + + "v.dateCreated, p.name, v.vacancyName FROM vacancy v JOIN vacancy_template t ON v.templateId=t.TEMPLATE_ID JOIN program p ON v.wlProgramId=p.id WHERE v.id=?1"; + + Query query = entityManager.createNativeQuery(queryString); + query.setParameter(1, vacancyID); + + @SuppressWarnings("unchecked") + List rows = query.getResultList(); + if (rows.size() == 0) + return null; + Object[] cols = rows.get(0); + if (cols != null) { + bo.setVacancyName((String) cols[0]); + bo.setVacancyTemplateName((String) cols[1]); + bo.setCreated((Date) cols[2]); + bo.setProgramName((String) cols[3]); + bo.setVacancyName((String) cols[4]); + } + loadStats(bo); + return bo; + } + + @Override + public void loadStats(VacancyDisplayBO bo) { + String queryStr = "SELECT " + + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?1 and status='REJECTED') " + + "as rejected, " + + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?2 and status='ACCEPTED') as accepted, " + + "(SELECT COUNT(*) FROM vacancy_client_match WHERE vacancy_id=?3 and status='PENDING') as pending"; + Query query = entityManager.createNativeQuery(queryStr); + query.setParameter(1, bo.getVacancyID()); + query.setParameter(2, bo.getVacancyID()); + query.setParameter(3, bo.getVacancyID()); + + @SuppressWarnings("unchecked") + List rows = query.getResultList(); + if (rows.size() > 0) { + Object[] result = rows.get(0); + if (result != null) { + bo.setRejectedCount(((BigInteger) result[0]).intValue()); + bo.setAcceptedCount(((BigInteger) result[1]).intValue()); + bo.setPendingCount(((BigInteger) result[2]).intValue()); + } + } + } + + @Override + public Integer getProgramIdByVacancyId(int vacancyId) { + List programIds = new ArrayList(); + // String queryString = "SELECT t.PROGRAM_ID FROM vacancy v JOIN + // vacancy_template t ON " + "v.templateId=t.TEMPLATE_ID WHERE v.id=?1"; + String queryString = "SELECT wlProgramId FROM vacancy where id=?1"; + Query query = entityManager.createNativeQuery(queryString); + query.setParameter(1, vacancyId); + + @SuppressWarnings("unchecked") + List rows = query.getResultList(); + if (rows.size() == 0) + return null; + Integer result = rows.get(0); + + if (result != null) { + programIds.add(result); + } + + if (!programIds.isEmpty()) { + return programIds.get(0); + } else { + return null; + } + } + + @Override + public List listNoOfVacanciesForWaitListProgram() { + final List bos = new ArrayList(); + String queryStr = "SELECT p.id , COUNT(*) vacncyCnt,v.vacancyName,v.dateCreated,v.id FROM vacancy v JOIN program p ON " + + "v.wlProgramId=p.id where v.status=?1 GROUP by v.wlProgramId"; + Query query = entityManager.createNativeQuery(queryStr); + query.setParameter(1, "active"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + bo.setProgramId((Integer) cols[0]); + bo.setNoOfVacancy(((BigInteger) cols[1]).intValue()); + bo.setVacancyName((String) cols[2]); + bo.setCreated((java.util.Date) cols[3]); + bo.setVacancyID((Integer) cols[4]); + bos.add(bo); + } + + return bos; + } + + @Override + public List listVacanciesForWaitListProgram() { + final List bos = new ArrayList(); + String queryStr = "SELECT p.id, v.vacancyName, v.dateCreated, v.id as vacancyId, vt.name FROM vacancy v, program p, vacancy_template vt where " + + "v.wlProgramId=p.id and v.templateId=vt.TEMPLATE_ID and v.status=?1 order by v.vacancyName"; + Query query = entityManager.createNativeQuery(queryStr); + query.setParameter(1, "active"); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + VacancyDisplayBO bo = new VacancyDisplayBO(); + bo.setProgramId((Integer) cols[0]); + bo.setVacancyName((String) cols[1]); + bo.setCreated((java.util.Date) cols[2]); + bo.setVacancyID((Integer) cols[3]); + bo.setVacancyTemplateName((String) cols[4]); + bos.add(bo); + } + + return bos; + } + + private static final String QUERY_ALL_CLIENT_DATA = "SELECT DISTINCT demographic_no, fdid, var_name, var_value " + + "FROM eform_values LEFT JOIN client_referral cr ON cr.client_id=demographic_no, " + + "(SELECT demographic_no AS dmb,MAX(fdid) AS ffdid FROM eform_values GROUP BY demographic_no) xyz " + + "WHERE cr.referral_id IS NULL AND " + "demographic_no= xyz.dmb AND fdid=xyz.ffdid"; + + private static final String QUERY_ALL_CLIENT_DATA_BY_PROGRAMID = "SELECT DISTINCT ef.demographic_no, ef.fdid, ef.var_name, ef.var_value " + + "FROM eform_values ef LEFT JOIN client_referral cr ON cr.client_id=ef.demographic_no" + + " where cr.program_id=?1 and ef.var_name in ('age-years','gender','current-housing','preferred-language','location-preferences','referrer-contact-province','contact-province','Age category','prepared-live-toronto','bed_community_program_id','has-mental-illness-primary','current-legal-involvements')" + + " and LENGTH(ef.var_value)>0 and not exists (select * from eform_values where demographic_no=ef.demographic_no and var_name=ef.var_name and fdid>ef.fdid)"; + + private static final String QUERY_GET_CLIENT_DATA = "SELECT DISTINCT ef.demographic_no, ef.fdid, ef.var_name, ef.var_value " + + "FROM eform_values ef WHERE ef.demographic_no= ?1 and " + + " ef.var_name in ('age-years','gender','current-housing','preferred-language','location-preferences','referrer-contact-province','contact-province','Age category','prepared-live-toronto','bed_community_program_id','has-mental-illness-primary','current-legal-involvements')" + + "and LENGTH(ef.var_value)>0 AND not exists (select * from eform_values where ef.demographic_no=demographic_no and var_name=ef.var_name and fdid>ef.fdid)"; + + @Override + public List getAllClientsData() { + Map clientsDataList = new HashMap(); + + Query query = entityManager.createNativeQuery(QUERY_ALL_CLIENT_DATA); + + @SuppressWarnings("unchecked") + List result = query.getResultList(); + for (Object[] cols : result) { + Integer demographicId = (Integer) cols[0]; + Integer formId = (Integer) cols[1]; + String paramName = (String) cols[2]; + String paramValue = (String) cols[3]; + if (demographicId == null) { + demographicId = 0; + } + ClientData clientData = clientsDataList.get(demographicId); + if (clientData == null) { + clientData = new ClientData(); + clientData.setClientId(demographicId); + clientData.setFormId(formId); + clientsDataList.put(demographicId, clientData); + } + + if (paramName != null) { + paramName = paramName.toLowerCase(); + } + if ("has-mental-illness-primary".equalsIgnoreCase(paramValue) && "no".equalsIgnoreCase(paramValue)) { + String[] paramsValues = intakeVarToCriteriaFiled(paramValue, paramValue); + if (paramsValues.length == 4) { + clientData.getClientData().put(paramsValues[0], paramsValues[1]); + clientData.getClientData().put(paramsValues[2], paramsValues[3]); + } + } else { + String[] paramVal = intakeVarToCriteriaFiled(paramValue, paramValue); + clientData.getClientData().put(paramVal[0], paramVal[1]); + } + } + return new ArrayList(clientsDataList.values()); + } + + @Override + public List getAllClientsDataByProgramId(int wlProgramId) { + Map clientsDataList = new HashMap(); + + Query query = entityManager.createNativeQuery(QUERY_ALL_CLIENT_DATA_BY_PROGRAMID); + query.setParameter(1, wlProgramId); + + @SuppressWarnings("unchecked") + List result = query.getResultList(); + for (Object[] cols : result) { + Integer demographicId = (Integer) cols[0]; + Integer formId = (Integer) cols[1]; + String paramName = (String) cols[2]; + String paramValue = (String) cols[3]; + if (demographicId == null) { + demographicId = 0; + } + ClientData clientData = clientsDataList.get(demographicId); + if (clientData == null) { + clientData = new ClientData(); + clientData.setClientId(demographicId); + clientData.setFormId(formId); + clientsDataList.put(demographicId, clientData); + } + + if (paramName != null) { + paramName = paramName.toLowerCase(); + } + if ("has-mental-illness-primary".equalsIgnoreCase(paramName) && !"no".equalsIgnoreCase(paramValue)) { + String[] paramsValues = intakeVarToCriteriaFiled(paramName, paramValue); + if (paramsValues.length == 4) { + clientData.getClientData().put(paramsValues[0], paramsValues[1]); + clientData.getClientData().put(paramsValues[2], paramsValues[3]); + } + } else { + String[] paramVal = intakeVarToCriteriaFiled(paramName, paramValue); + clientData.getClientData().put(paramVal[0], paramVal[1]); + } + } + return new ArrayList(clientsDataList.values()); + } + + private String[] intakeVarToCriteriaFiled(String varName, String varValue) { + if ("age-years".equalsIgnoreCase(varName) || "age category".equalsIgnoreCase(varName)) { + return new String[] { "age", varValue }; + } else if ("gender".equalsIgnoreCase(varName)) { + return new String[] { "gender", varValue }; + } else if ("preferred-language".equalsIgnoreCase(varName)) { + if ("eng".equalsIgnoreCase(varValue) || "english".equalsIgnoreCase(varValue)) { + return new String[] { "language", "English" }; + } else if ("fre".equalsIgnoreCase(varValue) || "french".equalsIgnoreCase(varValue)) { + return new String[] { "language", "French" }; + } else { + return new String[] { "language", "Other" }; + } + } else if ("location-preferences".equalsIgnoreCase(varName)) { + return new String[] { "area", varValue }; + } else if ("prepared-live-toronto".equalsIgnoreCase(varName)) { + if ("yes".equalsIgnoreCase(varValue)) { + return new String[] { "area", "Toronto" }; + } + } else if ("current-housing".equalsIgnoreCase(varName)) { + if ("other".equalsIgnoreCase(varValue)) { + return new String[] { "residence", "Homeless" }; + } else if ("no-fixed-address".equalsIgnoreCase(varValue)) { + return new String[] { "residence", "Transitional" }; + } else { + return new String[] { "residence", "Housed" }; + } + } else if ("has-mental-illness-primary".equalsIgnoreCase(varName)) { + if (!"no".equalsIgnoreCase(varValue) && !"unknown".equalsIgnoreCase(varValue)) { + return new String[] { "Serious and Persistent Mental Illness Diagnosis", varValue, + "Serious and Persistent Mental Illness Diagnosis", "No Formal Diagnosis" }; + } else if (!"no".equalsIgnoreCase(varValue)) { + return new String[] { "Serious and Persistent Mental Illness Diagnosis", "Formal Diagnosis", + "Serious and Persistent Mental Illness Diagnosis", varValue }; + } + } else if ("current-legal-involvements".equalsIgnoreCase(varName)) { + return new String[] { "Legal History", varValue }; + } + return new String[] { varName, varValue }; + } + + @Override + public ClientData getClientData(int clientId) { + ClientData clientData = new ClientData(); + clientData.setClientId(clientId); + + Query query = entityManager.createNativeQuery(QUERY_GET_CLIENT_DATA); + query.setParameter(1, clientId); + + @SuppressWarnings("unchecked") + List rows = query.getResultList(); + if (rows.size() == 0) + return clientData; + for (Object[] cols : rows) { + Integer demographicId = (Integer) cols[0]; + Integer formId = (Integer) cols[1]; + String paramName = (String) cols[2]; + String paramValue = (String) cols[3]; + if (demographicId == null) { + demographicId = 0; + } + clientData.setFormId(formId); + + if (paramName != null) { + paramName = paramName.toLowerCase(); + } + if ("has-mental-illness-primary".equalsIgnoreCase(paramName) && "no".equalsIgnoreCase(paramValue)) { + String[] paramsValues = intakeVarToCriteriaFiled(paramName, paramValue); + if (paramsValues.length == 4) { + clientData.getClientData().put(paramsValues[0], paramsValues[1]); + clientData.getClientData().put(paramsValues[2], paramsValues[3]); + } + } else { + String[] paramVal = intakeVarToCriteriaFiled(paramName, paramValue); + clientData.getClientData().put(paramVal[0], paramVal[1]); + } + } + + return clientData; + } + + private static final String QUERY_VACANCY_DATA = "SELECT v.id, v.wlProgramId, ct.field_name,ct.field_type," + + "c.criteria_value,cso.option_value,c.range_start_value,c.range_end_value " + + "FROM criteria c JOIN criteria_type ct ON c.CRITERIA_TYPE_ID=ct.CRITERIA_TYPE_ID " + + "LEFT JOIN criteria_selection_option cso ON cso.CRITERIA_ID=c.CRITERIA_ID " + + "JOIN vacancy v ON v.id=c.VACANCY_ID WHERE v.id=?1"; + + private static final String QUERY_VACANCY_DATA_BY_PROGRAMID = "SELECT v.id, v.wlProgramId, ct.field_name,ct.field_type," + + "c.criteria_value,cso.option_value,c.range_start_value,c.range_end_value " + + "FROM criteria c JOIN criteria_type ct ON c.CRITERIA_TYPE_ID=ct.CRITERIA_TYPE_ID " + + "LEFT JOIN criteria_selection_option cso ON cso.CRITERIA_ID=c.CRITERIA_ID " + + "JOIN vacancy v ON v.id=c.VACANCY_ID WHERE v.id=?1 and v.wlProgramId=?2"; + + private static final String field_type_multiple = "select_multiple"; + private static final String field_type_range = "select_one_range"; + // private static final String field_type_one = "select_one"; + // private static final String field_type_number = "number"; + + @Override + public VacancyData loadVacancyData(final int vacancyId) { + VacancyData vacancyData = new VacancyData(); + Vacancy vacancy = VacancyTemplateManagerImpl.getVacancyById(vacancyId); + if (vacancy == null) { + return vacancyData; + } + vacancyData.setVacancy_id(vacancy.getId()); + vacancyData.setProgram_id(vacancy.getWlProgramId()); + Query query = entityManager.createNativeQuery(QUERY_VACANCY_DATA); + query.setParameter(1, vacancyId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + + String fieldName = (String) cols[2]; + String fieldType = (String) cols[3]; + String critValue = (String) cols[4]; + String optionValue = (String) cols[5]; + Integer rangeStart = (Integer) cols[6]; + Integer rangeEnd = (Integer) cols[7]; + if (fieldName != null) { + fieldName = fieldName.toLowerCase(Locale.ENGLISH); + } + VacancyTemplateData vtData = new VacancyTemplateData(); + vtData.setParam(fieldName); + if (field_type_range.equals(fieldType)) { + vtData.setRange(true); + vtData.addRange(rangeStart, rangeEnd); + } else { + if (field_type_multiple.equals(fieldType)) { + VacancyTemplateData vtMultiData = vacancyData.getVacancyData().get(fieldName); + if (vtMultiData != null) { + vtData = vtMultiData; + } + } + if (critValue != null) { + vtData.getValues().add(critValue); + } else { + vtData.getValues().add(optionValue); + } + } + + vacancyData.getVacancyData().put(vtData.getParam(), vtData); + } + + return vacancyData; + } + + @Override + public VacancyData loadVacancyData(final int vacancyId, final int wlProgramId) { + VacancyData vacancyData = new VacancyData(); + Vacancy vacancy = VacancyTemplateManagerImpl.getVacancyById(vacancyId); + if (vacancy == null) { + return vacancyData; + } + vacancyData.setVacancy_id(vacancy.getId()); + vacancyData.setProgram_id(vacancy.getWlProgramId()); + Query query = entityManager.createNativeQuery(QUERY_VACANCY_DATA_BY_PROGRAMID); + query.setParameter(1, vacancyId); + query.setParameter(2, wlProgramId); + + @SuppressWarnings("unchecked") + List results = query.getResultList(); + for (Object[] cols : results) { + String fieldName = (String) cols[2]; + String fieldType = (String) cols[3]; + String critValue = (String) cols[4]; + String optionValue = (String) cols[5]; + Integer rangeStart = (Integer) cols[6]; + Integer rangeEnd = (Integer) cols[7]; + if (fieldName != null) { + fieldName = fieldName.toLowerCase(Locale.ENGLISH); + } + VacancyTemplateData vtData = new VacancyTemplateData(); + vtData.setParam(fieldName); + if (field_type_range.equals(fieldType)) { + vtData.setRange(true); + vtData.addRange(rangeStart, rangeEnd); + } else { + if (field_type_multiple.equals(fieldType)) { + VacancyTemplateData vtMultiData = vacancyData.getVacancyData().get(fieldName); + if (vtMultiData != null) { + vtData = vtMultiData; + } + } + if (critValue != null) { + vtData.getValues().add(critValue); + } else { + vtData.getValues().add(optionValue); + } + } + vacancyData.getVacancyData().put(vtData.getParam(), vtData); + } + + return vacancyData; + } + +} diff --git a/src/main/java/org/oscarehr/PMmodule/exporter/TestServlet.java b/src/main/java/org/oscarehr/PMmodule/exporter/TestServlet.java index 837e22b934..1fe989c1f9 100644 --- a/src/main/java/org/oscarehr/PMmodule/exporter/TestServlet.java +++ b/src/main/java/org/oscarehr/PMmodule/exporter/TestServlet.java @@ -57,25 +57,25 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro switch(fileno) { case 1: - exporter = (DATISAgencyInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterAgencyInformation"); + exporter = (DATISAgencyInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISAgencyInformation.class); break; case 2: - exporter = (DATISListOfPrograms)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterListOfPrograms"); + exporter = (DATISListOfPrograms)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISListOfPrograms.class); break; case 3: - exporter = (DATISMain)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterMain"); + exporter = (DATISMain)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISMain.class); break; case 4: - exporter = (DATISProgramInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterProgramInformation"); + exporter = (DATISProgramInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISProgramInformation.class); break; case 5: - exporter = (DATISGamingForm)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterGamblingForm"); + exporter = (DATISGamingForm)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISGamingForm.class); break; case 6: - exporter = (DATISNonClientService)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterNonClientService"); + exporter = (DATISNonClientService)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISNonClientService.class); break; default: - exporter = (DATISAgencyInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean("intakeExporterAgencyInformation"); + exporter = (DATISAgencyInformation)WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()).getBean(DATISAgencyInformation.class); break; } diff --git a/src/main/java/org/oscarehr/PMmodule/notification/EmailTriggerServlet.java b/src/main/java/org/oscarehr/PMmodule/notification/EmailTriggerServlet.java index f5cab0e16e..a22e85c8f3 100644 --- a/src/main/java/org/oscarehr/PMmodule/notification/EmailTriggerServlet.java +++ b/src/main/java/org/oscarehr/PMmodule/notification/EmailTriggerServlet.java @@ -93,8 +93,8 @@ public void trigerEmail(String app_ctx_path, String fid, String demographic_no, // String[] programIdsStringSplit=programIdsString.split(","); - // WaitListManager waitListManager=(WaitListManager) SpringUtils.getBean("waitListManager"); - // programDao = (ProgramDao) SpringUtils.getBean("programDao"); + // WaitListManager waitListManager=(WaitListManager) SpringUtils.getBean(WaitListManager.class); + // programDao = (ProgramDao) SpringUtils.getBean(ProgramDao.class); // for (String programIdString : programIdsStringSplit) // { diff --git a/src/main/java/org/oscarehr/PMmodule/service/AdmissionManager.java b/src/main/java/org/oscarehr/PMmodule/service/AdmissionManager.java index 51c59aaba0..d4d22ecfc8 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/AdmissionManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/AdmissionManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; import java.util.ArrayList; @@ -56,515 +58,44 @@ import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; -import oscar.log.LogAction; - -@Transactional -public class AdmissionManager { - - private AdmissionDao dao; - private ProgramDao programDao; - private ProgramQueueDao programQueueDao; - private ClientReferralDAO clientReferralDAO; - private BedDemographicManager bedDemographicManager; - private ProgramClientStatusDAO programClientStatusDAO; - private ClientRestrictionManager clientRestrictionManager; - private RoomManager roomManager; - private BedManager bedManager; - private RoomDemographicManager roomDemographicManager; - - public List getAdmissions_archiveView(String programId, Integer demographicNo) { - return dao.getAdmissions_archiveView(Integer.valueOf(programId), demographicNo); - } - - public Admission getAdmission(String programId, Integer demographicNo) { - return dao.getAdmission(Integer.valueOf(programId), demographicNo); - } - - public Admission getCurrentAdmission(String programId, Integer demographicNo) { - return dao.getCurrentAdmission(Integer.valueOf(programId), demographicNo); - } - - public List getAdmissionsByFacility(Integer demographicNo, Integer facilityId) { - return dao.getAdmissionsByFacility(demographicNo, facilityId); - } - - public List getCurrentAdmissionsByFacility(Integer demographicNo, Integer facilityId) { - return dao.getCurrentAdmissionsByFacility(demographicNo, facilityId); - } - - public List getAdmissions() { - return dao.getAdmissions(); - } - - public List getAdmissions(Integer demographicNo) { - return dao.getAdmissions(demographicNo); - } - - public List getCurrentAdmissions(Integer demographicNo) { - return dao.getCurrentAdmissions(demographicNo); - } - - public Admission getCurrentBedProgramAdmission(Integer demographicNo) { - return dao.getCurrentBedProgramAdmission(programDao, demographicNo); - } - - public List getCurrentServiceProgramAdmission(Integer demographicNo) { - return dao.getCurrentServiceProgramAdmission(programDao, demographicNo); - } - - public Admission getCurrentExternalProgramAdmission(Integer demographicNo) { - return dao.getCurrentExternalProgramAdmission(programDao, demographicNo); - } - - public Admission getCurrentCommunityProgramAdmission(Integer demographicNo) { - return dao.getCurrentCommunityProgramAdmission(programDao, demographicNo); - } - - public List getCurrentAdmissionsByProgramId(String programId) { - return dao.getCurrentAdmissionsByProgramId(Integer.valueOf(programId)); - } - - public Admission getAdmission(Long id) { - return dao.getAdmission(id.intValue()); - } - - public Admission getAdmission(Integer id) { - return dao.getAdmission(id); - } - - public void saveAdmission(Admission admission) { - dao.saveAdmission(admission); - } - - /*public void processAdmissionToExternal(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, null, false); - } - */ - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, null, false,null); - } - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, false,null); - } - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, false,dependents); - } - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, boolean overrideRestriction) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, overrideRestriction,null); - } - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, admissionDate, false,null); - } - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, admissionDate, false,dependents); - } - - - public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, Date admissionDate, boolean overrideRestriction, List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException { - // see if there's room first - if (program.getNumOfMembers().intValue() >= program.getMaxAllowed().intValue()) { - throw new ProgramFullException(); - } - - // check if there's a service restriction in place on this individual for this program - if (!overrideRestriction) { - ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(program.getId(), demographicNo, new Date()); - if (restrInPlace != null) { - throw new ServiceRestrictionException("service restriction in place", restrInPlace); - } - } - - boolean fromTransfer=false; - boolean automaticDischarge=false; - // If admitting to bed program, discharge from old bed program - if (program.getType().equalsIgnoreCase("bed") && !tempAdmission) { - Admission fullAdmission = getCurrentBedProgramAdmission(demographicNo); - - // community? - if (fullAdmission != null) { - Program oldProgram=programDao.getProgram(fullAdmission.getProgramId()); - Program newProgram=programDao.getProgram(program.getId()); - fromTransfer=(oldProgram.getFacilityId()==newProgram.getFacilityId()); - - - //discharge from old bed program to a new bed program which is in the different facility - //This is called automatic discharge. - if(!fromTransfer) - automaticDischarge = true; - - //processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "", null, fromTransfer); - processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "", null,null, fromTransfer,automaticDischarge); - } else { - fullAdmission = getCurrentCommunityProgramAdmission(demographicNo); - if (fullAdmission != null) { - processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "0",admissionDate); - } - } - } - - // Can only be in a single temporary bed program. - if (tempAdmission && getTemporaryAdmission(demographicNo) != null) { - throw new AdmissionException("Already in a temporary program."); - } - - // Create/Save admission object - Admission newAdmission = new Admission(); - if (admissionDate != null) { - newAdmission.setAdmissionDate(admissionDate); - } else { - newAdmission.setAdmissionDate(new Date()); - } - - newAdmission.setAdmissionNotes(admissionNotes); - newAdmission.setAdmissionStatus(Admission.STATUS_CURRENT); - newAdmission.setClientId(demographicNo); - newAdmission.setProgramId(program.getId()); - newAdmission.setProviderNo(providerNo); - newAdmission.setTeamId(null); - newAdmission.setTemporaryAdmission(tempAdmission); - newAdmission.setAdmissionFromTransfer(fromTransfer); - - //keep the client status if he was in the same program with it. - Integer clientStatusId = dao.getLastClientStatusFromAdmissionByProgramIdAndClientId(Integer.valueOf(program.getId()),demographicNo); - - //check if the client status is valid/existed in program_clientStatus - if(programClientStatusDAO.getProgramClientStatus(clientStatusId.toString()) == null|| clientStatusId==0) - clientStatusId = null; - - newAdmission.setClientStatusId(clientStatusId); - - saveAdmission(newAdmission); - - // Clear them from the queue, Update their referral - ProgramQueue pq = programQueueDao.getActiveProgramQueue(program.getId().longValue(), (long) demographicNo); - if (pq != null) { - pq.setStatus(ProgramQueue.STATUS_ADMITTED); - programQueueDao.saveProgramQueue(pq); - - // is there a referral - if (pq.getReferralId() != null && pq.getReferralId().longValue() > 0) { - ClientReferral referral = clientReferralDAO.getClientReferral(pq.getReferralId()); - referral.setStatus(ClientReferral.STATUS_CURRENT); - referral.setCompletionDate(new Date()); - referral.setCompletionNotes(admissionNotes); - clientReferralDAO.saveClientReferral(referral); - if(referral.getVacancyId()!=null){ - //change vacancy's status - VacancyDao vacancyDao= SpringUtils.getBean(VacancyDao.class); - Vacancy v = vacancyDao.find(referral.getVacancyId()); - if(v!=null) { - v.setStatus("filled"); - vacancyDao.saveEntity(v); - } - } - } - } - - - //if they are in a service program linked to this bed program, discharge them from that service program - //TODO: - if(program.getType().equalsIgnoreCase("Bed")) { - List programs = programDao.getLinkedServicePrograms(newAdmission.getProgramId(),demographicNo); - for(Program p:programs) { - //discharge them from this program - this.processDischarge(p.getId(), demographicNo,"", ""); - } - } - - //For the clients dependents - if (dependents != null){ - for(Integer l : dependents){ - processAdmission(new Integer(l.intValue()), providerNo,program,dischargeNotes,admissionNotes,tempAdmission,newAdmission.getAdmissionDate(),true,null); - } - } - - //Once the patient is admitted to this program, the vacancy - } - - public void processInitialAdmission(Integer demographicNo, String providerNo, Program program, String admissionNotes, Date admissionDate) throws ProgramFullException, AlreadyAdmittedException, ServiceRestrictionException { - // see if there's room first - if (program.getNumOfMembers().intValue() >= program.getMaxAllowed().intValue()) { - throw new ProgramFullException(); - } - - // check if there's a service restriction in place on this individual for this program - ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(program.getId(), demographicNo, new Date()); - if (restrInPlace != null) { - throw new ServiceRestrictionException("service restriction in place", restrInPlace); - } - - Admission admission = getCurrentAdmission(String.valueOf(program.getId()), demographicNo); - if (admission != null) { - throw new AlreadyAdmittedException(); - } - - Admission newAdmission = new Admission(); - if (admissionDate == null) { - newAdmission.setAdmissionDate(new Date()); - } else { - newAdmission.setAdmissionDate(admissionDate); - } - newAdmission.setAdmissionNotes(admissionNotes); - newAdmission.setAdmissionStatus(Admission.STATUS_CURRENT); - newAdmission.setClientId(demographicNo); - newAdmission.setProgramId(program.getId()); - newAdmission.setProviderNo(providerNo); - newAdmission.setTeamId(null); - saveAdmission(newAdmission); - } - - public Admission getTemporaryAdmission(Integer demographicNo) { - return dao.getTemporaryAdmission(demographicNo); - } - - public List getCurrentTemporaryProgramAdmission(Integer demographicNo) { - Admission admission = dao.getTemporaryAdmission(demographicNo); - if (admission != null) { - List results = new ArrayList(); - results.add(admission); - return results; - } - return null; - } - - public boolean isDependentInDifferentProgramFromHead(Integer demographicNo, List dependentList){ - if(demographicNo == null || dependentList == null || dependentList.isEmpty()){ - return false; - } - Integer[] dependentIds = new Integer[dependentList.size()]; - for(int i=0; i < dependentList.size(); i++ ){ - dependentIds[i] = new Integer(dependentList.get(i).getClientId().intValue()); - } - - //Check whether all family members are under same bed program -> if not, display error message. - Integer headProgramId = null; - Integer dependentProgramId = null; - Admission headAdmission = getCurrentBedProgramAdmission(demographicNo); - if(headAdmission != null){ - headProgramId = headAdmission.getProgramId(); - }else{ - headProgramId = null; - } - for(int i=0; dependentIds != null && i < dependentIds.length; i++ ){ - Admission dependentAdmission = getCurrentBedProgramAdmission(dependentIds[i]); - if(dependentAdmission != null){ - dependentProgramId = dependentAdmission.getProgramId(); - }else{ - dependentProgramId = null; - } - if( headProgramId != null && dependentProgramId != null ){ - if( headProgramId.intValue() != dependentProgramId.intValue() ){ - //Display message notifying that the dependent is under different bed program than family head -> cannot assign room/bed - return true; - } - }else if(headProgramId != null && dependentProgramId == null){ - return true; - }else if(headProgramId == null){ - return true; - } - } - return false; - } - - public List search(AdmissionSearchBean searchBean) { - return dao.search(searchBean); - } - - public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason) throws AdmissionException { - processDischarge(programId, demographicNo, dischargeNotes, radioDischargeReason,null,null, false, false); - } - - public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason, Date dischargeDate) throws AdmissionException { - processDischarge(programId, demographicNo, dischargeNotes, radioDischargeReason, dischargeDate, null, false, false); - } - - public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason,Date dischargeDate, List dependents, boolean fromTransfer, boolean automaticDischarge) throws AdmissionException { - - Admission fullAdmission = getCurrentAdmission(String.valueOf(programId), demographicNo); - - Program program=programDao.getProgram(programId); - Integer facilityId=null; - if (program!=null) facilityId=(int)program.getFacilityId(); - - if (fullAdmission == null) { - throw new AdmissionException("Admission Record not found"); - } - - if(dischargeDate == null) - fullAdmission.setDischargeDate(new Date()); - else - fullAdmission.setDischargeDate(dischargeDate); - - fullAdmission.setDischargeNotes(dischargeNotes); - fullAdmission.setAdmissionStatus(Admission.STATUS_DISCHARGED); - fullAdmission.setRadioDischargeReason(radioDischargeReason); - fullAdmission.setDischargeFromTransfer(fromTransfer); - fullAdmission.setAutomaticDischarge(automaticDischarge); - - saveAdmission(fullAdmission); - - if(roomManager != null && roomManager.isRoomOfDischargeProgramAssignedToClient(demographicNo, programId)){ - if(roomDemographicManager != null){ - RoomDemographic roomDemographic = roomDemographicManager.getRoomDemographicByDemographic(demographicNo, facilityId); - if(roomDemographic != null){ - roomDemographicManager.deleteRoomDemographic(roomDemographic); - } - } - } - - if(bedManager != null && bedManager.isBedOfDischargeProgramAssignedToClient(demographicNo, programId)){ - if(bedDemographicManager != null){ - BedDemographic bedDemographic = bedDemographicManager.getBedDemographicByDemographic(demographicNo, facilityId); - if(bedDemographic != null){ - bedDemographicManager.deleteBedDemographic(bedDemographic); - } - } - } - - if (dependents != null){ - for(Integer l:dependents){ - processDischarge(programId,new Integer(l.intValue()),dischargeNotes,radioDischargeReason, dischargeDate, null, fromTransfer, automaticDischarge); - } - } - } - - public void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason, Date dischargeDate) throws AdmissionException { - processDischargeToCommunity(communityProgramId,demographicNo,providerNo,notes,radioDischargeReason,null,dischargeDate); - } - - public void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason,List dependents,Date dischargeDate) throws AdmissionException { - Admission currentBedAdmission = getCurrentBedProgramAdmission(demographicNo); - - Program program=programDao.getProgram(communityProgramId); - Integer facilityId=null; - if (program!=null) facilityId=(int)program.getFacilityId(); - - if (currentBedAdmission != null) { - processDischarge(currentBedAdmission.getProgramId(), demographicNo, notes, radioDischargeReason); - - BedDemographic bedDemographic = bedDemographicManager.getBedDemographicByDemographic(demographicNo, facilityId); - - if (bedDemographic != null) { - bedDemographicManager.deleteBedDemographic(bedDemographic); - } - } - - Admission currentCommunityAdmission = getCurrentCommunityProgramAdmission(demographicNo); - - if (currentCommunityAdmission != null) { - processDischarge(currentCommunityAdmission.getProgramId(), demographicNo, notes, radioDischargeReason); - } - - // Create and save admission object - Admission admission = new Admission(); - admission.setAdmissionDate(new Date()); - admission.setAdmissionNotes(notes); - admission.setAdmissionStatus(Admission.STATUS_CURRENT); - admission.setClientId(demographicNo); - admission.setProgramId(communityProgramId); - admission.setProviderNo(providerNo); - admission.setTeamId(null); - admission.setTemporaryAdmission(false); - admission.setRadioDischargeReason(radioDischargeReason); - admission.setClientStatusId(null); - saveAdmission(admission); - - if (dependents != null){ - for(Integer l:dependents){ - processDischargeToCommunity(communityProgramId,new Integer(l.intValue()),providerNo, notes, radioDischargeReason,null); - } - } - } - - @Required - public void setAdmissionDao(AdmissionDao dao) { - this.dao = dao; - } - - @Required - public void setProgramDao(ProgramDao programDao) { - this.programDao = programDao; - } - - @Required - public void setProgramQueueDao(ProgramQueueDao dao) { - this.programQueueDao = dao; - } - - @Required - public void setClientReferralDAO(ClientReferralDAO dao) { - this.clientReferralDAO = dao; - } - - @Required - public void setBedDemographicManager(BedDemographicManager bedDemographicManager) { - this.bedDemographicManager = bedDemographicManager; - } - - @Required - public void setProgramClientStatusDAO(ProgramClientStatusDAO programClientStatusDAO) { - this.programClientStatusDAO = programClientStatusDAO; - } - - @Required - public void setClientRestrictionManager(ClientRestrictionManager clientRestrictionManager) { - this.clientRestrictionManager = clientRestrictionManager; - } - - @Required - public void setRoomManager(RoomManager roomManager) { - this.roomManager = roomManager; - } - - @Required - public void setBedManager(BedManager bedManager) { - this.bedManager= bedManager; - } - - @Required - public void setRoomDemographicManager(RoomDemographicManager roomDemographicManager) { - this.roomDemographicManager = roomDemographicManager; - } - - public boolean isActiveInCurrentFacility(LoggedInInfo loggedInInfo, int demographicId) - { - List results=getCurrentAdmissionsByFacility(demographicId, loggedInInfo.getCurrentFacility().getId()); - if (results!=null && results.size()>0) return(true); - - return(false); - } - - public List getActiveAnonymousAdmissions() { - return dao.getActiveAnonymousAdmissions(); - } - - public boolean wasInProgram(Integer programId, Integer clientId) { - if(dao.getAdmission(programId, clientId)!=null) - return true; - else - return false; - - } - - - - public List findAdmissionsByProgramAndDate(LoggedInInfo loggedInInfo, Integer programNo, Date day, int startIndex, int numToReturn) { - List results = dao.findAdmissionsByProgramAndDate(programNo,day, startIndex, numToReturn); - - for(Admission result:results) { - LogAction.addLogSynchronous(loggedInInfo,"AdmissionManager.findAdmissionsByProgramAndDate", "admission id=" + result.getId()); - } - return results; - } - - public Integer findAdmissionsByProgramAndDateAsCount(LoggedInInfo loggedInInfo, Integer programNo, Date day) { - Integer count= dao.findAdmissionsByProgramAndDateAsCount(programNo,day); - - return count; - } +public interface AdmissionManager { + + List getAdmissions_archiveView(String programId, Integer demographicNo); + Admission getAdmission(String programId, Integer demographicNo); + Admission getCurrentAdmission(String programId, Integer demographicNo); + List getAdmissionsByFacility(Integer demographicNo, Integer facilityId); + List getCurrentAdmissionsByFacility(Integer demographicNo, Integer facilityId); + List getAdmissions(); + List getAdmissions(Integer demographicNo); + List getCurrentAdmissions(Integer demographicNo); + Admission getCurrentBedProgramAdmission(Integer demographicNo); + List getCurrentServiceProgramAdmission(Integer demographicNo); + Admission getCurrentExternalProgramAdmission(Integer demographicNo); + Admission getCurrentCommunityProgramAdmission(Integer demographicNo); + List getCurrentAdmissionsByProgramId(String programId); + Admission getAdmission(Long id); + Admission getAdmission(Integer id); + void saveAdmission(Admission admission); + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, boolean overrideRestriction) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, Date admissionDate, boolean overrideRestriction, List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException; + void processInitialAdmission(Integer demographicNo, String providerNo, Program program, String admissionNotes, Date admissionDate) throws ProgramFullException, AlreadyAdmittedException, ServiceRestrictionException; + Admission getTemporaryAdmission(Integer demographicNo); + List getCurrentTemporaryProgramAdmission(Integer demographicNo); + boolean isDependentInDifferentProgramFromHead(Integer demographicNo, List dependentList); + List search(AdmissionSearchBean searchBean); + void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason) throws AdmissionException; + void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason, Date dischargeDate) throws AdmissionException; + void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason,Date dischargeDate, List dependents, boolean fromTransfer, boolean automaticDischarge) throws AdmissionException; + void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason,Date dischargeDate) throws AdmissionException; + void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason,List dependents,Date dischargeDate) throws AdmissionException; + boolean isActiveInCurrentFacility(LoggedInInfo loggedInInfo, int demographicId); + List getActiveAnonymousAdmissions(); + boolean wasInProgram(Integer programId, Integer clientId); + List findAdmissionsByProgramAndDate(LoggedInInfo loggedInInfo, Integer programNo, Date day, int startIndex, int numToReturn); + Integer findAdmissionsByProgramAndDateAsCount(LoggedInInfo loggedInInfo, Integer programNo, Date day); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/AdmissionManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/AdmissionManagerImpl.java new file mode 100644 index 0000000000..3e96ca6edb --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/AdmissionManagerImpl.java @@ -0,0 +1,573 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.oscarehr.PMmodule.service; + + import java.util.ArrayList; + import java.util.Date; + import java.util.List; + + import org.oscarehr.PMmodule.dao.ClientReferralDAO; + import org.oscarehr.PMmodule.dao.ProgramClientStatusDAO; + import org.oscarehr.PMmodule.dao.ProgramDao; + import org.oscarehr.PMmodule.dao.ProgramQueueDao; + import org.oscarehr.PMmodule.dao.VacancyDao; + import org.oscarehr.PMmodule.exception.AdmissionException; + import org.oscarehr.PMmodule.exception.AlreadyAdmittedException; + import org.oscarehr.PMmodule.exception.ProgramFullException; + import org.oscarehr.PMmodule.exception.ServiceRestrictionException; + import org.oscarehr.PMmodule.model.AdmissionSearchBean; + import org.oscarehr.PMmodule.model.ClientReferral; + import org.oscarehr.PMmodule.model.Program; + import org.oscarehr.PMmodule.model.ProgramClientRestriction; + import org.oscarehr.PMmodule.model.ProgramQueue; + import org.oscarehr.PMmodule.model.Vacancy; + import org.oscarehr.common.dao.AdmissionDao; + import org.oscarehr.common.model.Admission; + import org.oscarehr.common.model.BedDemographic; + import org.oscarehr.common.model.JointAdmission; + import org.oscarehr.common.model.RoomDemographic; + import org.oscarehr.managers.BedManager; + import org.oscarehr.managers.BedDemographicManager; + import org.oscarehr.managers.RoomManager; + import org.oscarehr.managers.RoomDemographicManager; + import org.oscarehr.util.LoggedInInfo; + import org.oscarehr.util.SpringUtils; + import org.springframework.beans.factory.annotation.Required; + import org.springframework.transaction.annotation.Transactional; + + import oscar.log.LogAction; + + @Transactional + public class AdmissionManagerImpl implements AdmissionManager{ + + private AdmissionDao dao; + private ProgramDao programDao; + private ProgramQueueDao programQueueDao; + private ClientReferralDAO clientReferralDAO; + private BedDemographicManager bedDemographicManager; + private ProgramClientStatusDAO programClientStatusDAO; + private ClientRestrictionManager clientRestrictionManager; + private RoomManager roomManager; + private BedManager bedManager; + private RoomDemographicManager roomDemographicManager; + + public List getAdmissions_archiveView(String programId, Integer demographicNo) { + return dao.getAdmissions_archiveView(Integer.valueOf(programId), demographicNo); + } + + public Admission getAdmission(String programId, Integer demographicNo) { + return dao.getAdmission(Integer.valueOf(programId), demographicNo); + } + + public Admission getCurrentAdmission(String programId, Integer demographicNo) { + return dao.getCurrentAdmission(Integer.valueOf(programId), demographicNo); + } + + public List getAdmissionsByFacility(Integer demographicNo, Integer facilityId) { + return dao.getAdmissionsByFacility(demographicNo, facilityId); + } + + public List getCurrentAdmissionsByFacility(Integer demographicNo, Integer facilityId) { + return dao.getCurrentAdmissionsByFacility(demographicNo, facilityId); + } + + public List getAdmissions() { + return dao.getAdmissions(); + } + + public List getAdmissions(Integer demographicNo) { + return dao.getAdmissions(demographicNo); + } + + public List getCurrentAdmissions(Integer demographicNo) { + return dao.getCurrentAdmissions(demographicNo); + } + + public Admission getCurrentBedProgramAdmission(Integer demographicNo) { + return dao.getCurrentBedProgramAdmission(programDao, demographicNo); + } + + public List getCurrentServiceProgramAdmission(Integer demographicNo) { + return dao.getCurrentServiceProgramAdmission(programDao, demographicNo); + } + + public Admission getCurrentExternalProgramAdmission(Integer demographicNo) { + return dao.getCurrentExternalProgramAdmission(programDao, demographicNo); + } + + public Admission getCurrentCommunityProgramAdmission(Integer demographicNo) { + return dao.getCurrentCommunityProgramAdmission(programDao, demographicNo); + } + + public List getCurrentAdmissionsByProgramId(String programId) { + return dao.getCurrentAdmissionsByProgramId(Integer.valueOf(programId)); + } + + public Admission getAdmission(Long id) { + return dao.getAdmission(id.intValue()); + } + + public Admission getAdmission(Integer id) { + return dao.getAdmission(id); + } + + public void saveAdmission(Admission admission) { + dao.saveAdmission(admission); + } + + /*public void processAdmissionToExternal(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, null, false); + } + */ + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, null, false,null); + } + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, false,null); + } + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, false,dependents); + } + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, boolean overrideRestriction) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, null, overrideRestriction,null); + } + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, false, admissionDate, false,null); + } + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission,List dependents, Date admissionDate) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + processAdmission(demographicNo, providerNo, program, dischargeNotes, admissionNotes, tempAdmission, admissionDate, false,dependents); + } + + + public void processAdmission(Integer demographicNo, String providerNo, Program program, String dischargeNotes, String admissionNotes, boolean tempAdmission, Date admissionDate, boolean overrideRestriction, List dependents) throws ProgramFullException, AdmissionException, ServiceRestrictionException { + // see if there's room first + if (program.getNumOfMembers().intValue() >= program.getMaxAllowed().intValue()) { + throw new ProgramFullException(); + } + + // check if there's a service restriction in place on this individual for this program + if (!overrideRestriction) { + ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(program.getId(), demographicNo, new Date()); + if (restrInPlace != null) { + throw new ServiceRestrictionException("service restriction in place", restrInPlace); + } + } + + boolean fromTransfer=false; + boolean automaticDischarge=false; + // If admitting to bed program, discharge from old bed program + if (program.getType().equalsIgnoreCase("bed") && !tempAdmission) { + Admission fullAdmission = getCurrentBedProgramAdmission(demographicNo); + + // community? + if (fullAdmission != null) { + Program oldProgram=programDao.getProgram(fullAdmission.getProgramId()); + Program newProgram=programDao.getProgram(program.getId()); + fromTransfer=(oldProgram.getFacilityId()==newProgram.getFacilityId()); + + + //discharge from old bed program to a new bed program which is in the different facility + //This is called automatic discharge. + if(!fromTransfer) + automaticDischarge = true; + + //processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "", null, fromTransfer); + processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "", null,null, fromTransfer,automaticDischarge); + } else { + fullAdmission = getCurrentCommunityProgramAdmission(demographicNo); + if (fullAdmission != null) { + processDischarge(new Integer(fullAdmission.getProgramId().intValue()), new Integer(demographicNo), dischargeNotes, "0",admissionDate); + } + } + } + + // Can only be in a single temporary bed program. + if (tempAdmission && getTemporaryAdmission(demographicNo) != null) { + throw new AdmissionException("Already in a temporary program."); + } + + // Create/Save admission object + Admission newAdmission = new Admission(); + if (admissionDate != null) { + newAdmission.setAdmissionDate(admissionDate); + } else { + newAdmission.setAdmissionDate(new Date()); + } + + newAdmission.setAdmissionNotes(admissionNotes); + newAdmission.setAdmissionStatus(Admission.STATUS_CURRENT); + newAdmission.setClientId(demographicNo); + newAdmission.setProgramId(program.getId()); + newAdmission.setProviderNo(providerNo); + newAdmission.setTeamId(null); + newAdmission.setTemporaryAdmission(tempAdmission); + newAdmission.setAdmissionFromTransfer(fromTransfer); + + //keep the client status if he was in the same program with it. + Integer clientStatusId = dao.getLastClientStatusFromAdmissionByProgramIdAndClientId(Integer.valueOf(program.getId()),demographicNo); + + //check if the client status is valid/existed in program_clientStatus + if(programClientStatusDAO.getProgramClientStatus(clientStatusId.toString()) == null|| clientStatusId==0) + clientStatusId = null; + + newAdmission.setClientStatusId(clientStatusId); + + saveAdmission(newAdmission); + + // Clear them from the queue, Update their referral + ProgramQueue pq = programQueueDao.getActiveProgramQueue(program.getId().longValue(), (long) demographicNo); + if (pq != null) { + pq.setStatus(ProgramQueue.STATUS_ADMITTED); + programQueueDao.saveProgramQueue(pq); + + // is there a referral + if (pq.getReferralId() != null && pq.getReferralId().longValue() > 0) { + ClientReferral referral = clientReferralDAO.getClientReferral(pq.getReferralId()); + referral.setStatus(ClientReferral.STATUS_CURRENT); + referral.setCompletionDate(new Date()); + referral.setCompletionNotes(admissionNotes); + clientReferralDAO.saveClientReferral(referral); + if(referral.getVacancyId()!=null){ + //change vacancy's status + VacancyDao vacancyDao= SpringUtils.getBean(VacancyDao.class); + Vacancy v = vacancyDao.find(referral.getVacancyId()); + if(v!=null) { + v.setStatus("filled"); + vacancyDao.saveEntity(v); + } + } + } + } + + + //if they are in a service program linked to this bed program, discharge them from that service program + //TODO: + if(program.getType().equalsIgnoreCase("Bed")) { + List programs = programDao.getLinkedServicePrograms(newAdmission.getProgramId(),demographicNo); + for(Program p:programs) { + //discharge them from this program + this.processDischarge(p.getId(), demographicNo,"", ""); + } + } + + //For the clients dependents + if (dependents != null){ + for(Integer l : dependents){ + processAdmission(new Integer(l.intValue()), providerNo,program,dischargeNotes,admissionNotes,tempAdmission,newAdmission.getAdmissionDate(),true,null); + } + } + + //Once the patient is admitted to this program, the vacancy + } + + public void processInitialAdmission(Integer demographicNo, String providerNo, Program program, String admissionNotes, Date admissionDate) throws ProgramFullException, AlreadyAdmittedException, ServiceRestrictionException { + // see if there's room first + if (program.getNumOfMembers().intValue() >= program.getMaxAllowed().intValue()) { + throw new ProgramFullException(); + } + + // check if there's a service restriction in place on this individual for this program + ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(program.getId(), demographicNo, new Date()); + if (restrInPlace != null) { + throw new ServiceRestrictionException("service restriction in place", restrInPlace); + } + + Admission admission = getCurrentAdmission(String.valueOf(program.getId()), demographicNo); + if (admission != null) { + throw new AlreadyAdmittedException(); + } + + Admission newAdmission = new Admission(); + if (admissionDate == null) { + newAdmission.setAdmissionDate(new Date()); + } else { + newAdmission.setAdmissionDate(admissionDate); + } + newAdmission.setAdmissionNotes(admissionNotes); + newAdmission.setAdmissionStatus(Admission.STATUS_CURRENT); + newAdmission.setClientId(demographicNo); + newAdmission.setProgramId(program.getId()); + newAdmission.setProviderNo(providerNo); + newAdmission.setTeamId(null); + saveAdmission(newAdmission); + } + + public Admission getTemporaryAdmission(Integer demographicNo) { + return dao.getTemporaryAdmission(demographicNo); + } + + public List getCurrentTemporaryProgramAdmission(Integer demographicNo) { + Admission admission = dao.getTemporaryAdmission(demographicNo); + if (admission != null) { + List results = new ArrayList(); + results.add(admission); + return results; + } + return null; + } + + public boolean isDependentInDifferentProgramFromHead(Integer demographicNo, List dependentList){ + if(demographicNo == null || dependentList == null || dependentList.isEmpty()){ + return false; + } + Integer[] dependentIds = new Integer[dependentList.size()]; + for(int i=0; i < dependentList.size(); i++ ){ + dependentIds[i] = new Integer(dependentList.get(i).getClientId().intValue()); + } + + //Check whether all family members are under same bed program -> if not, display error message. + Integer headProgramId = null; + Integer dependentProgramId = null; + Admission headAdmission = getCurrentBedProgramAdmission(demographicNo); + if(headAdmission != null){ + headProgramId = headAdmission.getProgramId(); + }else{ + headProgramId = null; + } + for(int i=0; dependentIds != null && i < dependentIds.length; i++ ){ + Admission dependentAdmission = getCurrentBedProgramAdmission(dependentIds[i]); + if(dependentAdmission != null){ + dependentProgramId = dependentAdmission.getProgramId(); + }else{ + dependentProgramId = null; + } + if( headProgramId != null && dependentProgramId != null ){ + if( headProgramId.intValue() != dependentProgramId.intValue() ){ + //Display message notifying that the dependent is under different bed program than family head -> cannot assign room/bed + return true; + } + }else if(headProgramId != null && dependentProgramId == null){ + return true; + }else if(headProgramId == null){ + return true; + } + } + return false; + } + + public List search(AdmissionSearchBean searchBean) { + return dao.search(searchBean); + } + + public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason) throws AdmissionException { + processDischarge(programId, demographicNo, dischargeNotes, radioDischargeReason,null,null, false, false); + } + + public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason, Date dischargeDate) throws AdmissionException { + processDischarge(programId, demographicNo, dischargeNotes, radioDischargeReason, dischargeDate, null, false, false); + } + + public void processDischarge(Integer programId, Integer demographicNo, String dischargeNotes, String radioDischargeReason,Date dischargeDate, List dependents, boolean fromTransfer, boolean automaticDischarge) throws AdmissionException { + + Admission fullAdmission = getCurrentAdmission(String.valueOf(programId), demographicNo); + + Program program=programDao.getProgram(programId); + Integer facilityId=null; + if (program!=null) facilityId=(int)program.getFacilityId(); + + if (fullAdmission == null) { + throw new AdmissionException("Admission Record not found"); + } + + if(dischargeDate == null) + fullAdmission.setDischargeDate(new Date()); + else + fullAdmission.setDischargeDate(dischargeDate); + + fullAdmission.setDischargeNotes(dischargeNotes); + fullAdmission.setAdmissionStatus(Admission.STATUS_DISCHARGED); + fullAdmission.setRadioDischargeReason(radioDischargeReason); + fullAdmission.setDischargeFromTransfer(fromTransfer); + fullAdmission.setAutomaticDischarge(automaticDischarge); + + saveAdmission(fullAdmission); + + if(roomManager != null && roomManager.isRoomOfDischargeProgramAssignedToClient(demographicNo, programId)){ + if(roomDemographicManager != null){ + RoomDemographic roomDemographic = roomDemographicManager.getRoomDemographicByDemographic(demographicNo, facilityId); + if(roomDemographic != null){ + roomDemographicManager.deleteRoomDemographic(roomDemographic); + } + } + } + + if(bedManager != null && bedManager.isBedOfDischargeProgramAssignedToClient(demographicNo, programId)){ + if(bedDemographicManager != null){ + BedDemographic bedDemographic = bedDemographicManager.getBedDemographicByDemographic(demographicNo, facilityId); + if(bedDemographic != null){ + bedDemographicManager.deleteBedDemographic(bedDemographic); + } + } + } + + if (dependents != null){ + for(Integer l:dependents){ + processDischarge(programId,new Integer(l.intValue()),dischargeNotes,radioDischargeReason, dischargeDate, null, fromTransfer, automaticDischarge); + } + } + } + + public void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason, Date dischargeDate) throws AdmissionException { + processDischargeToCommunity(communityProgramId,demographicNo,providerNo,notes,radioDischargeReason,null,dischargeDate); + } + + public void processDischargeToCommunity(Integer communityProgramId, Integer demographicNo, String providerNo, String notes, String radioDischargeReason,List dependents,Date dischargeDate) throws AdmissionException { + Admission currentBedAdmission = getCurrentBedProgramAdmission(demographicNo); + + Program program=programDao.getProgram(communityProgramId); + Integer facilityId=null; + if (program!=null) facilityId=(int)program.getFacilityId(); + + if (currentBedAdmission != null) { + processDischarge(currentBedAdmission.getProgramId(), demographicNo, notes, radioDischargeReason); + + BedDemographic bedDemographic = bedDemographicManager.getBedDemographicByDemographic(demographicNo, facilityId); + + if (bedDemographic != null) { + bedDemographicManager.deleteBedDemographic(bedDemographic); + } + } + + Admission currentCommunityAdmission = getCurrentCommunityProgramAdmission(demographicNo); + + if (currentCommunityAdmission != null) { + processDischarge(currentCommunityAdmission.getProgramId(), demographicNo, notes, radioDischargeReason); + } + + // Create and save admission object + Admission admission = new Admission(); + admission.setAdmissionDate(new Date()); + admission.setAdmissionNotes(notes); + admission.setAdmissionStatus(Admission.STATUS_CURRENT); + admission.setClientId(demographicNo); + admission.setProgramId(communityProgramId); + admission.setProviderNo(providerNo); + admission.setTeamId(null); + admission.setTemporaryAdmission(false); + admission.setRadioDischargeReason(radioDischargeReason); + admission.setClientStatusId(null); + saveAdmission(admission); + + if (dependents != null){ + for(Integer l:dependents){ + processDischargeToCommunity(communityProgramId,new Integer(l.intValue()),providerNo, notes, radioDischargeReason,null); + } + } + } + + @Required + public void setAdmissionDao(AdmissionDao dao) { + this.dao = dao; + } + + @Required + public void setProgramDao(ProgramDao programDao) { + this.programDao = programDao; + } + + @Required + public void setProgramQueueDao(ProgramQueueDao dao) { + this.programQueueDao = dao; + } + + @Required + public void setClientReferralDAO(ClientReferralDAO dao) { + this.clientReferralDAO = dao; + } + + @Required + public void setBedDemographicManager(BedDemographicManager bedDemographicManager) { + this.bedDemographicManager = bedDemographicManager; + } + + @Required + public void setProgramClientStatusDAO(ProgramClientStatusDAO programClientStatusDAO) { + this.programClientStatusDAO = programClientStatusDAO; + } + + @Required + public void setClientRestrictionManager(ClientRestrictionManager clientRestrictionManager) { + this.clientRestrictionManager = clientRestrictionManager; + } + + @Required + public void setRoomManager(RoomManager roomManager) { + this.roomManager = roomManager; + } + + @Required + public void setBedManager(BedManager bedManager) { + this.bedManager= bedManager; + } + + @Required + public void setRoomDemographicManager(RoomDemographicManager roomDemographicManager) { + this.roomDemographicManager = roomDemographicManager; + } + + public boolean isActiveInCurrentFacility(LoggedInInfo loggedInInfo, int demographicId) + { + List results=getCurrentAdmissionsByFacility(demographicId, loggedInInfo.getCurrentFacility().getId()); + if (results!=null && results.size()>0) return(true); + + return(false); + } + + public List getActiveAnonymousAdmissions() { + return dao.getActiveAnonymousAdmissions(); + } + + public boolean wasInProgram(Integer programId, Integer clientId) { + if(dao.getAdmission(programId, clientId)!=null) + return true; + else + return false; + + } + + + + public List findAdmissionsByProgramAndDate(LoggedInInfo loggedInInfo, Integer programNo, Date day, int startIndex, int numToReturn) { + List results = dao.findAdmissionsByProgramAndDate(programNo,day, startIndex, numToReturn); + + for(Admission result:results) { + LogAction.addLogSynchronous(loggedInInfo,"AdmissionManager.findAdmissionsByProgramAndDate", "admission id=" + result.getId()); + } + return results; + } + + public Integer findAdmissionsByProgramAndDateAsCount(LoggedInInfo loggedInInfo, Integer programNo, Date day) { + Integer count= dao.findAdmissionsByProgramAndDateAsCount(programNo,day); + + return count; + } + } \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/service/AgencyManager.java b/src/main/java/org/oscarehr/PMmodule/service/AgencyManager.java index 8e0e0c964a..deb2c4005f 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/AgencyManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/AgencyManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,29 +20,14 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; -import org.oscarehr.PMmodule.dao.AgencyDao; import org.oscarehr.PMmodule.model.Agency; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class AgencyManager { - - private AgencyDao dao; - - public void setAgencyDao(AgencyDao dao) { - this.dao = dao; - } - - public Agency getLocalAgency() { - Agency agency = dao.getLocalAgency(); - return agency; - } - public void saveAgency(Agency agency) { - dao.saveAgency(agency); - } +public interface AgencyManager { + Agency getLocalAgency(); + void saveAgency(Agency agency); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/AgencyManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/AgencyManagerImpl.java new file mode 100644 index 0000000000..98733efb10 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/AgencyManagerImpl.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.service; + +import org.oscarehr.PMmodule.dao.AgencyDao; +import org.oscarehr.PMmodule.model.Agency; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class AgencyManagerImpl implements AgencyManager { + + private AgencyDao dao; + + public void setAgencyDao(AgencyDao dao) { + this.dao = dao; + } + + @Override + public Agency getLocalAgency() { + Agency agency = dao.getLocalAgency(); + return agency; + } + + @Override + public void saveAgency(Agency agency) { + dao.saveAgency(agency); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/ClientManager.java b/src/main/java/org/oscarehr/PMmodule/service/ClientManager.java index e8f3387e2c..4b50c48da3 100755 --- a/src/main/java/org/oscarehr/PMmodule/service/ClientManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/ClientManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,11 +20,11 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; -import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -45,266 +46,69 @@ import org.springframework.beans.factory.annotation.Required; import org.springframework.transaction.annotation.Transactional; -@Transactional -public class ClientManager { - - private DemographicDao dao; - private DemographicExtDao demographicExtDao; - private ClientReferralDAO referralDAO; - private JointAdmissionDao jointAdmissionDao; - private ProgramQueueManager queueManager; - private AdmissionManager admissionManager; - private ClientRestrictionManager clientRestrictionManager; - - private boolean outsideOfDomainEnabled; - - public boolean isOutsideOfDomainEnabled() { - return outsideOfDomainEnabled; - } - - public Demographic getClientByDemographicNo(String demographicNo) { - if (demographicNo == null || demographicNo.length() == 0) { - return null; - } - return dao.getClientByDemographicNo(Integer.valueOf(demographicNo)); - } - - public List getClients() { - return dao.getClients(); - } - - public List search(ClientSearchFormBean criteria, boolean returnOptinsOnly,boolean excludeMerged) { - return dao.search(criteria, returnOptinsOnly,excludeMerged); - } - public List search(ClientSearchFormBean criteria) { - return dao.search(criteria); - } - - public List getReferrals() { - return referralDAO.getReferrals(); - } - - public List getReferrals(String clientId) { - return referralDAO.getReferrals(Long.valueOf(clientId)); - } - - public List getReferralsByFacility(Integer clientId, Integer facilityId) { - return referralDAO.getReferralsByFacility(clientId.longValue(), facilityId); - } - - public List getActiveReferrals(String clientId, String sourceFacilityId) { - List results = referralDAO.getActiveReferrals(Long.valueOf(clientId), Integer.parseInt(sourceFacilityId)); - - return results; - } - - public ClientReferral getClientReferral(String id) { - return referralDAO.getClientReferral(Long.valueOf(id)); - } - - /* - * This should always be a new one. add the queue to the program. - */ - public void saveClientReferral(ClientReferral referral) { - - referralDAO.saveClientReferral(referral); - addClientReferralToProgramQueue(referral); - } - - - public void addClientReferralToProgramQueue(ClientReferral referral) { - if (referral.getStatus().equalsIgnoreCase(ClientReferral.STATUS_ACTIVE)) { - ProgramQueue queue = new ProgramQueue(); - queue.setClientId(referral.getClientId()); - queue.setNotes(referral.getNotes()); - queue.setProgramId(referral.getProgramId()); - queue.setProviderNo(Long.parseLong(referral.getProviderNo())); - queue.setReferralDate(referral.getReferralDate()); - queue.setStatus(ProgramQueue.STATUS_ACTIVE); - queue.setReferralId(referral.getId()); - queue.setTemporaryAdmission(referral.isTemporaryAdmission()); - queue.setPresentProblems(referral.getPresentProblems()); - queue.setVacancyName(referral.getSelectVacancy()); - - queueManager.saveProgramQueue(queue); - } - } - - public List searchReferrals(ClientReferral referral) { - return referralDAO.search(referral); - } - - public void saveJointAdmission(JointAdmission admission) { - if (admission == null) { - throw new IllegalArgumentException(); - } - - jointAdmissionDao.persist(admission); - } - - public List getDependents(Integer clientId) { - return jointAdmissionDao.getSpouseAndDependents(clientId); - } - - public List getDependentsList(Integer clientId) { - List list = new ArrayList(); - List jadms = jointAdmissionDao.getSpouseAndDependents(clientId); - for (JointAdmission jadm : jadms) { - list.add(jadm.getClientId()); - } - return list; - } - - public JointAdmission getJointAdmission(Integer clientId) { - return jointAdmissionDao.getJointAdmission(clientId); - } - - public boolean isClientDependentOfFamily(Integer clientId){ - - JointAdmission clientsJadm = null; - if(clientId != null){ - clientsJadm = getJointAdmission(Integer.valueOf(clientId.toString())); - } - if (clientsJadm != null && clientsJadm.getHeadClientId() != null) { - return true; - } - return false; - } - - - public boolean isClientFamilyHead(Integer clientId){ - - List dependentList = getDependents(Integer.valueOf(clientId.toString())); - if(dependentList != null && dependentList.size() > 0){ - return true; - } - return false; - } - - public void removeJointAdmission(Integer clientId, String providerNo) { - jointAdmissionDao.removeJointAdmission(clientId, providerNo); - } - - public void removeJointAdmission(JointAdmission admission) { - jointAdmissionDao.removeJointAdmission(admission); - } - - public void processReferral(ClientReferral referral) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException { - processReferral(referral, false); - } - - public void processReferral(ClientReferral referral, boolean override) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException { - if (!override) { - // check if there's a service restriction in place on this individual for this program - ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(referral.getProgramId().intValue(), referral.getClientId().intValue(), new Date()); - if (restrInPlace != null) { - throw new ServiceRestrictionException("service restriction in place", restrInPlace); - } - } - - Admission currentAdmission = admissionManager.getCurrentAdmission(String.valueOf(referral.getProgramId()), referral.getClientId().intValue()); - if (currentAdmission != null) { - referral.setStatus(ClientReferral.STATUS_REJECTED); - referral.setCompletionNotes("Client currently admitted"); - referral.setCompletionDate(new Date()); - - //saveClientReferral(referral); //???what's the point to save it if it's already admitted - throw new AlreadyAdmittedException(); - } - - ProgramQueue queue = queueManager.getActiveProgramQueue(String.valueOf(referral.getProgramId()), String.valueOf(referral.getClientId())); - if (queue != null) { - referral.setStatus(ClientReferral.STATUS_REJECTED); - referral.setCompletionNotes("Client already in queue"); - referral.setCompletionDate(new Date()); - - //saveClientReferral(referral); //???what's the point to save it if's already in queue - throw new AlreadyQueuedException(); - } - - saveClientReferral(referral); - List dependents = getDependents(new Long(referral.getClientId()).intValue()); - for (JointAdmission jadm : dependents) { - referral.setClientId(new Long(jadm.getClientId())); - saveClientReferral(referral); - } - - } - - public void saveClient(Demographic client) { - dao.saveClient(client); - } - - public DemographicExt getDemographicExt(String id) { - return demographicExtDao.getDemographicExt(Integer.valueOf(id)); - } - - public List getDemographicExtByDemographicNo(int demographicNo) { - return demographicExtDao.getDemographicExtByDemographicNo(demographicNo); - } - - public DemographicExt getDemographicExt(int demographicNo, String key) { - return demographicExtDao.getDemographicExt(demographicNo, key); - } - - public void updateDemographicExt(DemographicExt de) { - demographicExtDao.updateDemographicExt(de); - } - - public void saveDemographicExt(int demographicNo, String key, String value) { - demographicExtDao.saveDemographicExt(demographicNo, key, value); - } - - public void removeDemographicExt(String id) { - demographicExtDao.removeDemographicExt(Integer.valueOf(id)); - } - - public void removeDemographicExt(int demographicNo, String key) { - demographicExtDao.removeDemographicExt(demographicNo, key); - } - - public void setJointAdmissionDao(JointAdmissionDao jointAdmissionDao) { - this.jointAdmissionDao = jointAdmissionDao; - } - - @Required - public void setDemographicDao(DemographicDao dao) { - this.dao = dao; - } - - @Required - public void setDemographicExtDao(DemographicExtDao dao) { - this.demographicExtDao = dao; - } - - @Required - public void setClientReferralDAO(ClientReferralDAO dao) { - this.referralDAO = dao; - } - - @Required - public void setProgramQueueManager(ProgramQueueManager mgr) { - this.queueManager = mgr; - } - - @Required - public void setAdmissionManager(AdmissionManager mgr) { - this.admissionManager = mgr; - } - - @Required - public void setClientRestrictionManager(ClientRestrictionManager clientRestrictionManager) { - this.clientRestrictionManager = clientRestrictionManager; - } - - @Required - public void setOutsideOfDomainEnabled(boolean outsideOfDomainEnabled) { - this.outsideOfDomainEnabled = outsideOfDomainEnabled; - } - - - public boolean checkHealthCardExists(String hin, String hcType) { - List results = this.dao.searchByHealthCard(hin,hcType); - return (results.size()>0)?true:false; - } +public interface ClientManager { + + boolean isOutsideOfDomainEnabled(); + + Demographic getClientByDemographicNo(String demographicNo); + + List getClients(); + + List search(ClientSearchFormBean criteria, boolean returnOptinsOnly,boolean excludeMerged); + + List search(ClientSearchFormBean criteria); + + List getReferrals(); + + List getReferrals(String clientId); + + List getReferralsByFacility(Integer clientId, Integer facilityId); + + List getActiveReferrals(String clientId, String sourceFacilityId); + + ClientReferral getClientReferral(String id); + + void saveClientReferral(ClientReferral referral); + + void addClientReferralToProgramQueue(ClientReferral referral); + + List searchReferrals(ClientReferral referral); + + void saveJointAdmission(JointAdmission admission); + + List getDependents(Integer clientId); + + List getDependentsList(Integer clientId); + + JointAdmission getJointAdmission(Integer clientId); + + boolean isClientDependentOfFamily(Integer clientId); + + boolean isClientFamilyHead(Integer clientId); + + void removeJointAdmission(Integer clientId, String providerNo); + + void removeJointAdmission(JointAdmission admission); + + void processReferral(ClientReferral referral) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException; + + void processReferral(ClientReferral referral, boolean override) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException; + + void saveClient(Demographic client); + + DemographicExt getDemographicExt(String id); + + List getDemographicExtByDemographicNo(int demographicNo); + + DemographicExt getDemographicExt(int demographicNo, String key); + + void updateDemographicExt(DemographicExt de); + + void saveDemographicExt(int demographicNo, String key, String value); + + void removeDemographicExt(String id); + + void removeDemographicExt(int demographicNo, String key); + + boolean checkHealthCardExists(String hin, String hcType); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/ClientManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/ClientManagerImpl.java new file mode 100644 index 0000000000..e23c23ba55 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/ClientManagerImpl.java @@ -0,0 +1,313 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.oscarehr.PMmodule.service; + + import java.util.ArrayList; + import java.util.Date; + import java.util.List; + + import org.oscarehr.PMmodule.dao.ClientReferralDAO; + import org.oscarehr.PMmodule.exception.AlreadyAdmittedException; + import org.oscarehr.PMmodule.exception.AlreadyQueuedException; + import org.oscarehr.PMmodule.exception.ServiceRestrictionException; + import org.oscarehr.PMmodule.model.ClientReferral; + import org.oscarehr.PMmodule.model.ProgramClientRestriction; + import org.oscarehr.PMmodule.model.ProgramQueue; + import org.oscarehr.PMmodule.web.formbean.ClientSearchFormBean; + import org.oscarehr.common.dao.DemographicDao; + import org.oscarehr.common.dao.DemographicExtDao; + import org.oscarehr.common.dao.JointAdmissionDao; + import org.oscarehr.common.model.Admission; + import org.oscarehr.common.model.Demographic; + import org.oscarehr.common.model.DemographicExt; + import org.oscarehr.common.model.JointAdmission; + import org.springframework.beans.factory.annotation.Required; + import org.springframework.transaction.annotation.Transactional; + + @Transactional + public class ClientManagerImpl implements ClientManager{ + + private DemographicDao dao; + private DemographicExtDao demographicExtDao; + private ClientReferralDAO referralDAO; + private JointAdmissionDao jointAdmissionDao; + private ProgramQueueManager queueManager; + private AdmissionManager admissionManager; + private ClientRestrictionManager clientRestrictionManager; + + private boolean outsideOfDomainEnabled; + + public boolean isOutsideOfDomainEnabled() { + return outsideOfDomainEnabled; + } + + public Demographic getClientByDemographicNo(String demographicNo) { + if (demographicNo == null || demographicNo.length() == 0) { + return null; + } + return dao.getClientByDemographicNo(Integer.valueOf(demographicNo)); + } + + public List getClients() { + return dao.getClients(); + } + + public List search(ClientSearchFormBean criteria, boolean returnOptinsOnly,boolean excludeMerged) { + return dao.search(criteria, returnOptinsOnly,excludeMerged); + } + public List search(ClientSearchFormBean criteria) { + return dao.search(criteria); + } + + public List getReferrals() { + return referralDAO.getReferrals(); + } + + public List getReferrals(String clientId) { + return referralDAO.getReferrals(Long.valueOf(clientId)); + } + + public List getReferralsByFacility(Integer clientId, Integer facilityId) { + return referralDAO.getReferralsByFacility(clientId.longValue(), facilityId); + } + + public List getActiveReferrals(String clientId, String sourceFacilityId) { + List results = referralDAO.getActiveReferrals(Long.valueOf(clientId), Integer.parseInt(sourceFacilityId)); + + return results; + } + + public ClientReferral getClientReferral(String id) { + return referralDAO.getClientReferral(Long.valueOf(id)); + } + + /* + * This should always be a new one. add the queue to the program. + */ + public void saveClientReferral(ClientReferral referral) { + + referralDAO.saveClientReferral(referral); + addClientReferralToProgramQueue(referral); + } + + + public void addClientReferralToProgramQueue(ClientReferral referral) { + if (referral.getStatus().equalsIgnoreCase(ClientReferral.STATUS_ACTIVE)) { + ProgramQueue queue = new ProgramQueue(); + queue.setClientId(referral.getClientId()); + queue.setNotes(referral.getNotes()); + queue.setProgramId(referral.getProgramId()); + queue.setProviderNo(Long.parseLong(referral.getProviderNo())); + queue.setReferralDate(referral.getReferralDate()); + queue.setStatus(ProgramQueue.STATUS_ACTIVE); + queue.setReferralId(referral.getId()); + queue.setTemporaryAdmission(referral.isTemporaryAdmission()); + queue.setPresentProblems(referral.getPresentProblems()); + queue.setVacancyName(referral.getSelectVacancy()); + + queueManager.saveProgramQueue(queue); + } + } + + public List searchReferrals(ClientReferral referral) { + return referralDAO.search(referral); + } + + public void saveJointAdmission(JointAdmission admission) { + if (admission == null) { + throw new IllegalArgumentException(); + } + + jointAdmissionDao.persist(admission); + } + + public List getDependents(Integer clientId) { + return jointAdmissionDao.getSpouseAndDependents(clientId); + } + + public List getDependentsList(Integer clientId) { + List list = new ArrayList(); + List jadms = jointAdmissionDao.getSpouseAndDependents(clientId); + for (JointAdmission jadm : jadms) { + list.add(jadm.getClientId()); + } + return list; + } + + public JointAdmission getJointAdmission(Integer clientId) { + return jointAdmissionDao.getJointAdmission(clientId); + } + + public boolean isClientDependentOfFamily(Integer clientId){ + + JointAdmission clientsJadm = null; + if(clientId != null){ + clientsJadm = getJointAdmission(Integer.valueOf(clientId.toString())); + } + if (clientsJadm != null && clientsJadm.getHeadClientId() != null) { + return true; + } + return false; + } + + + public boolean isClientFamilyHead(Integer clientId){ + + List dependentList = getDependents(Integer.valueOf(clientId.toString())); + if(dependentList != null && dependentList.size() > 0){ + return true; + } + return false; + } + + public void removeJointAdmission(Integer clientId, String providerNo) { + jointAdmissionDao.removeJointAdmission(clientId, providerNo); + } + + public void removeJointAdmission(JointAdmission admission) { + jointAdmissionDao.removeJointAdmission(admission); + } + + public void processReferral(ClientReferral referral) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException { + processReferral(referral, false); + } + + public void processReferral(ClientReferral referral, boolean override) throws AlreadyAdmittedException, AlreadyQueuedException, ServiceRestrictionException { + if (!override) { + // check if there's a service restriction in place on this individual for this program + ProgramClientRestriction restrInPlace = clientRestrictionManager.checkClientRestriction(referral.getProgramId().intValue(), referral.getClientId().intValue(), new Date()); + if (restrInPlace != null) { + throw new ServiceRestrictionException("service restriction in place", restrInPlace); + } + } + + Admission currentAdmission = admissionManager.getCurrentAdmission(String.valueOf(referral.getProgramId()), referral.getClientId().intValue()); + if (currentAdmission != null) { + referral.setStatus(ClientReferral.STATUS_REJECTED); + referral.setCompletionNotes("Client currently admitted"); + referral.setCompletionDate(new Date()); + + //saveClientReferral(referral); //???what's the point to save it if it's already admitted + throw new AlreadyAdmittedException(); + } + + ProgramQueue queue = queueManager.getActiveProgramQueue(String.valueOf(referral.getProgramId()), String.valueOf(referral.getClientId())); + if (queue != null) { + referral.setStatus(ClientReferral.STATUS_REJECTED); + referral.setCompletionNotes("Client already in queue"); + referral.setCompletionDate(new Date()); + + //saveClientReferral(referral); //???what's the point to save it if's already in queue + throw new AlreadyQueuedException(); + } + + saveClientReferral(referral); + List dependents = getDependents(new Long(referral.getClientId()).intValue()); + for (JointAdmission jadm : dependents) { + referral.setClientId(new Long(jadm.getClientId())); + saveClientReferral(referral); + } + + } + + public void saveClient(Demographic client) { + dao.saveClient(client); + } + + public DemographicExt getDemographicExt(String id) { + return demographicExtDao.getDemographicExt(Integer.valueOf(id)); + } + + public List getDemographicExtByDemographicNo(int demographicNo) { + return demographicExtDao.getDemographicExtByDemographicNo(demographicNo); + } + + public DemographicExt getDemographicExt(int demographicNo, String key) { + return demographicExtDao.getDemographicExt(demographicNo, key); + } + + public void updateDemographicExt(DemographicExt de) { + demographicExtDao.updateDemographicExt(de); + } + + public void saveDemographicExt(int demographicNo, String key, String value) { + demographicExtDao.saveDemographicExt(demographicNo, key, value); + } + + public void removeDemographicExt(String id) { + demographicExtDao.removeDemographicExt(Integer.valueOf(id)); + } + + public void removeDemographicExt(int demographicNo, String key) { + demographicExtDao.removeDemographicExt(demographicNo, key); + } + + public void setJointAdmissionDao(JointAdmissionDao jointAdmissionDao) { + this.jointAdmissionDao = jointAdmissionDao; + } + + @Required + public void setDemographicDao(DemographicDao dao) { + this.dao = dao; + } + + @Required + public void setDemographicExtDao(DemographicExtDao dao) { + this.demographicExtDao = dao; + } + + @Required + public void setClientReferralDAO(ClientReferralDAO dao) { + this.referralDAO = dao; + } + + @Required + public void setProgramQueueManager(ProgramQueueManager mgr) { + this.queueManager = mgr; + } + + @Required + public void setAdmissionManager(AdmissionManager mgr) { + this.admissionManager = mgr; + } + + @Required + public void setClientRestrictionManager(ClientRestrictionManager clientRestrictionManager) { + this.clientRestrictionManager = clientRestrictionManager; + } + + @Required + public void setOutsideOfDomainEnabled(boolean outsideOfDomainEnabled) { + this.outsideOfDomainEnabled = outsideOfDomainEnabled; + } + + + public boolean checkHealthCardExists(String hin, String hcType) { + List results = this.dao.searchByHealthCard(hin,hcType); + return (results.size()>0)?true:false; + } + } \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManager.java b/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManager.java index 363eb786d7..76e5ecc6c4 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,150 +20,35 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; -import java.util.ArrayList; -import java.util.Collection; import java.util.Date; import java.util.List; - -import org.oscarehr.PMmodule.dao.ProgramClientRestrictionDAO; -import org.oscarehr.PMmodule.exception.ClientAlreadyRestrictedException; import org.oscarehr.PMmodule.model.ProgramClientRestriction; -import org.springframework.beans.factory.annotation.Required; -import org.springframework.transaction.annotation.Transactional; - -/** - * Manage client restrictions - */ -@Transactional -public class ClientRestrictionManager { - - private ProgramClientRestrictionDAO programClientRestrictionDAO; - - public List getActiveRestrictionsForProgram(int programId, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.findForProgram(programId); - List returnPcrs = new ArrayList(); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); - } - } - return returnPcrs; - } - - public List getDisabledRestrictionsForProgram(Integer programId, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.findDisabledForProgram(programId); - List returnPcrs = new ArrayList(); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); - } - } - return returnPcrs; - } - - public List getActiveRestrictionsForClient(int demographicNo, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.findForClient(demographicNo); - List returnPcrs = new ArrayList(); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); - } - } - return returnPcrs; - } - - public List getActiveRestrictionsForClient(int demographicNo, int facilityId, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.findForClient(demographicNo, facilityId); - List returnPcrs = new ArrayList(); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); - } - } - return returnPcrs; - } +import org.oscarehr.PMmodule.exception.ClientAlreadyRestrictedException; - public List getDisabledRestrictionsForClient(int demographicNo, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.findDisabledForClient(demographicNo); - List returnPcrs = new ArrayList(); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); - } - } - return returnPcrs; - } +public interface ClientRestrictionManager { - public ProgramClientRestriction checkClientRestriction(int programId, int demographicNo, Date asOfDate) { - // check dao for restriction - Collection pcrs = programClientRestrictionDAO.find(programId, demographicNo); - if (pcrs != null && !pcrs.isEmpty()) { - for (ProgramClientRestriction pcr : pcrs) { - if (pcr.getStartDate().getTime() <= asOfDate.getTime() && asOfDate.getTime() <= pcr.getEndDate().getTime()) return pcr; - } - } - return null; - } + List getActiveRestrictionsForProgram(int programId, Date asOfDate); - public void saveClientRestriction(ProgramClientRestriction restriction) throws ClientAlreadyRestrictedException { - if (restriction.getId() == null) { - ProgramClientRestriction result = checkClientRestriction(restriction.getProgramId(), restriction.getDemographicNo(), new Date()); - if (result != null) throw new ClientAlreadyRestrictedException("the client has already been service restricted in this program"); - } + List getDisabledRestrictionsForProgram(Integer programId, Date asOfDate); - programClientRestrictionDAO.save(restriction); - } + List getActiveRestrictionsForClient(int demographicNo, Date asOfDate); - public void terminateEarly(int programClientRestrictionId, String providerNo) { - ProgramClientRestriction x = programClientRestrictionDAO.find(programClientRestrictionId); + List getActiveRestrictionsForClient(int demographicNo, int facilityId, Date asOfDate); - if (x != null) { - x.setEarlyTerminationProvider(providerNo); - x.setEndDate(new Date()); - programClientRestrictionDAO.save(x); - } - } + List getDisabledRestrictionsForClient(int demographicNo, Date asOfDate); - public void disableClientRestriction(int restrictionId) { - ProgramClientRestriction pcr = programClientRestrictionDAO.find(restrictionId); - pcr.setEnabled(false); - try { - saveClientRestriction(pcr); - } - catch (ClientAlreadyRestrictedException e) { - // this exception should not happen here, so toss it up as a runtime exception to be caught higher up - throw new RuntimeException(e); - } - } + ProgramClientRestriction checkClientRestriction(int programId, int demographicNo, Date asOfDate); - public void enableClientRestriction(Integer restrictionId) { - ProgramClientRestriction pcr = programClientRestrictionDAO.find(restrictionId); - pcr.setEnabled(true); - try { - saveClientRestriction(pcr); - } - catch (ClientAlreadyRestrictedException e) { - // this exception should not happen here, so toss it up as a runtime exception to be caught higher up - throw new RuntimeException(e); - } - } + void saveClientRestriction(ProgramClientRestriction restriction) throws ClientAlreadyRestrictedException; - public ProgramClientRestrictionDAO getProgramClientRestrictionDAO() { - return programClientRestrictionDAO; - } + void terminateEarly(int programClientRestrictionId, String providerNo); - @Required - public void setProgramClientRestrictionDAO(ProgramClientRestrictionDAO programClientRestrictionDAO) { - this.programClientRestrictionDAO = programClientRestrictionDAO; - } + void disableClientRestriction(int restrictionId); + void enableClientRestriction(Integer restrictionId); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManagerImpl.java new file mode 100644 index 0000000000..4d6c8cde81 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/ClientRestrictionManagerImpl.java @@ -0,0 +1,167 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.service; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; + +import org.oscarehr.PMmodule.dao.ProgramClientRestrictionDAO; +import org.oscarehr.PMmodule.exception.ClientAlreadyRestrictedException; +import org.oscarehr.PMmodule.model.ProgramClientRestriction; +import org.springframework.beans.factory.annotation.Required; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class ClientRestrictionManagerImpl implements ClientRestrictionManager { + + private ProgramClientRestrictionDAO programClientRestrictionDAO; + + @Override + public List getActiveRestrictionsForProgram(int programId, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.findForProgram(programId); + List returnPcrs = new ArrayList(); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); + } + } + return returnPcrs; + } + + public List getDisabledRestrictionsForProgram(Integer programId, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.findDisabledForProgram(programId); + List returnPcrs = new ArrayList(); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); + } + } + return returnPcrs; + } + + public List getActiveRestrictionsForClient(int demographicNo, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.findForClient(demographicNo); + List returnPcrs = new ArrayList(); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); + } + } + return returnPcrs; + } + + public List getActiveRestrictionsForClient(int demographicNo, int facilityId, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.findForClient(demographicNo, facilityId); + List returnPcrs = new ArrayList(); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); + } + } + return returnPcrs; + } + + public List getDisabledRestrictionsForClient(int demographicNo, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.findDisabledForClient(demographicNo); + List returnPcrs = new ArrayList(); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && pcr.getEndDate().getTime() <= pcr.getEndDate().getTime()) returnPcrs.add(pcr); + } + } + return returnPcrs; + } + + public ProgramClientRestriction checkClientRestriction(int programId, int demographicNo, Date asOfDate) { + // check dao for restriction + Collection pcrs = programClientRestrictionDAO.find(programId, demographicNo); + if (pcrs != null && !pcrs.isEmpty()) { + for (ProgramClientRestriction pcr : pcrs) { + if (pcr.getStartDate().getTime() <= asOfDate.getTime() && asOfDate.getTime() <= pcr.getEndDate().getTime()) return pcr; + } + } + return null; + } + + public void saveClientRestriction(ProgramClientRestriction restriction) throws ClientAlreadyRestrictedException { + if (restriction.getId() == null) { + ProgramClientRestriction result = checkClientRestriction(restriction.getProgramId(), restriction.getDemographicNo(), new Date()); + if (result != null) throw new ClientAlreadyRestrictedException("the client has already been service restricted in this program"); + } + + programClientRestrictionDAO.save(restriction); + } + + public void terminateEarly(int programClientRestrictionId, String providerNo) { + ProgramClientRestriction x = programClientRestrictionDAO.find(programClientRestrictionId); + + if (x != null) { + x.setEarlyTerminationProvider(providerNo); + x.setEndDate(new Date()); + programClientRestrictionDAO.save(x); + } + } + + public void disableClientRestriction(int restrictionId) { + ProgramClientRestriction pcr = programClientRestrictionDAO.find(restrictionId); + pcr.setEnabled(false); + try { + saveClientRestriction(pcr); + } + catch (ClientAlreadyRestrictedException e) { + // this exception should not happen here, so toss it up as a runtime exception to be caught higher up + throw new RuntimeException(e); + } + } + + public void enableClientRestriction(Integer restrictionId) { + ProgramClientRestriction pcr = programClientRestrictionDAO.find(restrictionId); + pcr.setEnabled(true); + try { + saveClientRestriction(pcr); + } + catch (ClientAlreadyRestrictedException e) { + // this exception should not happen here, so toss it up as a runtime exception to be caught higher up + throw new RuntimeException(e); + } + } + + public ProgramClientRestrictionDAO getProgramClientRestrictionDAO() { + return programClientRestrictionDAO; + } + + @Required + public void setProgramClientRestrictionDAO(ProgramClientRestrictionDAO programClientRestrictionDAO) { + this.programClientRestrictionDAO = programClientRestrictionDAO; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManager.java b/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManager.java index 0da68e9c24..b0eb1beb71 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,849 +20,159 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.service; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.apache.logging.log4j.Logger; -import org.oscarehr.PMmodule.dao.GenericIntakeDAO; -import org.oscarehr.PMmodule.dao.GenericIntakeNodeDAO; -import org.oscarehr.PMmodule.dao.ProgramDao; -import org.oscarehr.PMmodule.model.Agency; -import org.oscarehr.PMmodule.model.Intake; -import org.oscarehr.PMmodule.model.IntakeAnswer; -import org.oscarehr.PMmodule.model.IntakeAnswerElement; -import org.oscarehr.PMmodule.model.IntakeNode; -import org.oscarehr.PMmodule.model.IntakeNodeJavascript; -import org.oscarehr.PMmodule.model.IntakeNodeLabel; -import org.oscarehr.PMmodule.model.IntakeNodeTemplate; -import org.oscarehr.PMmodule.model.Program; -import org.oscarehr.PMmodule.web.adapter.IntakeNodeHtmlAdapter; -import org.oscarehr.PMmodule.web.adapter.ocan.OcanXmlAdapterFactory; -import org.oscarehr.common.dao.AdmissionDao; -import org.oscarehr.common.model.Admission; -import org.oscarehr.common.model.ReportStatistic; -import org.oscarehr.util.MiscUtils; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class GenericIntakeManager { - - private GenericIntakeNodeDAO genericIntakeNodeDAO; - private GenericIntakeDAO genericIntakeDAO; - private ProgramDao programDao; - private AdmissionDao admissionDao; - private OcanXmlAdapterFactory adapterFactory = new OcanXmlAdapterFactory(); - - private static Logger logger = MiscUtils.getLogger(); - - public void setGenericIntakeNodeDAO( - GenericIntakeNodeDAO genericIntakeNodeDAO) { - this.genericIntakeNodeDAO = genericIntakeNodeDAO; - } - - public void setGenericIntakeDAO(GenericIntakeDAO genericIntakeDAO) { - this.genericIntakeDAO = genericIntakeDAO; - } - - public void setProgramDao(ProgramDao programDao) { - this.programDao = programDao; - } - - public void setAdmissionDao(AdmissionDao admissionDao) { - this.admissionDao = admissionDao; - } - - // Copy - - public Intake copyQuickIntake(Integer clientId, String staffId, - Integer facilityId) { - // return copyIntake(getQuickIntakeNode(), clientId, null, staffId); - return copyIntakeWithId(getQuickIntakeNode(), clientId, null, staffId, - facilityId); - } - - public Intake copyRegIntake(Integer clientId, String staffId, - Integer facilityId) { - // return copyIntake(getQuickIntakeNode(), clientId, null, staffId); - IntakeNode latestInode = getLatestRegIntakeNodes(clientId); - Intake intake = this.genericIntakeDAO.getLatestIntakeByFacility( - latestInode, clientId, null, facilityId); - if (intake != null) { - return copyIntakeWithId(latestInode, clientId, null, staffId, - facilityId); - } else { - IntakeNode qin = this.getQuickIntakeNode(); - if (qin.getLabel() == null) { - return null; - } - List previousIntakeNodes = genericIntakeNodeDAO - .getPublishedIntakeNodesByName(qin.getLabel().getLabel()); - for (IntakeNode in : previousIntakeNodes) { - intake = genericIntakeDAO.getLatestIntakeByFacility(in, - clientId, null, facilityId); - if (intake != null) - return copyOldIntake(latestInode, intake, clientId, null, - staffId, facilityId); - } - } - return null; - } - - public Intake copyIndepthIntake(Integer clientId, String staffId, - Integer facilityId) { - // return copyIntake(getIndepthIntakeNode(), clientId, null, staffId); - return copyIntakeWithId(getIndepthIntakeNode(), clientId, null, - staffId, facilityId); - } - - public Intake copyProgramIntake(Integer clientId, Integer programId, - String staffId, Integer facilityId) { - // return copyIntake(getProgramIntakeNode(programId), clientId, - // programId, staffId); - return copyIntakeWithId(getProgramIntakeNode(programId), clientId, - programId, staffId, facilityId); - } - - // Create - - public Intake createQuickIntake(String providerNo) { - return createIntake(getQuickIntakeNode(), null, null, providerNo); - } - - public Intake createIndepthIntake(String providerNo) { - return createIntake(getIndepthIntakeNode(), null, null, providerNo); - } - - public Intake createIntake(IntakeNode node, String providerNo) { - return createIntake(node, null, null, providerNo); - } - - public Intake createProgramIntake(Integer programId, String providerNo) { - return createIntake(getProgramIntakeNode(programId), null, programId, - providerNo); - } - - // Get - - public Intake getMostRecentQuickIntakeByFacility(Integer clientId, - Integer facilityId) { - IntakeNode regIntakeNode = getQuickIntakeNode(); - Intake intake = genericIntakeDAO.getLatestIntakeByFacility( - regIntakeNode, clientId, null, facilityId); - - if (intake == null && regIntakeNode.getLabel() != null) { - /* - * search old registration intakes in proper order to make sure we - * return the latest one - */ - List previousIntakeNodes = genericIntakeNodeDAO - .getPublishedIntakeNodesByName(regIntakeNode.getLabel() - .getLabel()); - for (IntakeNode in : previousIntakeNodes) { - logger.info("searching for intakes for node version: " - + in.getForm_version()); - intake = genericIntakeDAO.getLatestIntakeByFacility(in, - clientId, null, facilityId); - if (intake != null) - break; - } - } - - return intake; - } - - public Intake getMostRecentQuickIntake(Integer clientId, Integer facilityId) { - return genericIntakeDAO.getLatestIntake(getQuickIntakeNode(), clientId, - null, facilityId); - } - - public Intake getRegIntakeById(Integer intakeId, Integer facilityId) { - return genericIntakeDAO.getIntakeById( - getIntakeNodeByIntakeId(intakeId), intakeId, null, facilityId); - } - - public Intake getMostRecentIndepthIntake(Integer clientId, - Integer facilityId) { - return genericIntakeDAO.getLatestIntake(getIndepthIntakeNode(), - clientId, null, facilityId); - } - - public Intake getMostRecentProgramIntake(Integer clientId, - Integer programId, Integer facilityId) { - return genericIntakeDAO.getLatestIntake( - getProgramIntakeNode(programId), clientId, programId, - facilityId); - } - - public List getQuickIntakes(Integer clientId, Integer facilityId) { - return genericIntakeDAO.getIntakes(getQuickIntakeNode(), clientId, - null, facilityId); - } - - public List getRegIntakes(Integer clientId, Integer facilityId) { - return genericIntakeDAO.getRegIntakes(getRegIntakeNodes(clientId), - clientId, null, facilityId); - } - - public List getIntakeClientsByFacilityId(Integer facilityId) { - return genericIntakeDAO.getIntakeClientsByFacilityId(facilityId); - } - - public List getIntakeFacilityIds() { - return genericIntakeDAO.getIntakeFacilityIds(); - } - - public List getIndepthIntakes(Integer clientId, Integer facilityId) { - return genericIntakeDAO.getIntakes(getIndepthIntakeNode(), clientId, - null, facilityId); - } - - public List getProgramIntakes(Integer clientId, Integer facilityId) { - List programIntakes = new ArrayList(); - - for (Program program : getProgramsWithIntake(clientId)) { - programIntakes.addAll(genericIntakeDAO.getIntakes( - getProgramIntakeNode(program), clientId, program.getId(), - facilityId)); - } - - return programIntakes; - } - - public List getIntakesByType(Integer clientId, Integer facilityId, Integer formType) { - return genericIntakeDAO.getIntakesByType(formType, clientId, - null, facilityId); - } - - public List getProgramsWithIntake(Integer clientId) { - List programsWithIntake = new ArrayList(); - - List serviceProgramAdmissions = admissionDao - .getCurrentServiceProgramAdmission(programDao, clientId); - if (serviceProgramAdmissions != null) { - for (Object o : serviceProgramAdmissions) { - Admission admission = (Admission) o; - Program program = programDao.getProgram(admission - .getProgramId()); - - if (program != null && program.getIntakeProgram() != null) { - programsWithIntake.add(program); - } - } - } - - return programsWithIntake; - } - - // Save - - public Integer saveIntake(Intake intake) { - return genericIntakeDAO.saveIntake(intake); - } - - // Save Or Update - - public void saveUpdateIntake(Intake intake) { - genericIntakeDAO.saveUpdateIntake(intake); - } - - // Report - - public GenericIntakeDAO.GenericIntakeReportStatistics getQuestionStatistics2( - String intakeType, Integer programId, Date startDate, Date endDate) - throws SQLException { - - // get node - IntakeNode node = null; - - if (Intake.QUICK.equalsIgnoreCase(intakeType)) { - node = getQuickIntakeNode(); - } else if (Intake.INDEPTH.equalsIgnoreCase(intakeType)) { - node = getIndepthIntakeNode(); - } else if (Intake.PROGRAM.equalsIgnoreCase(intakeType)) { - node = getProgramIntakeNode(programId); - } - - Calendar endCal = Calendar.getInstance(); - endCal.setTime(endDate); - endCal.add(Calendar.DAY_OF_YEAR, 1); - List intakeIds = genericIntakeDAO.getIntakeIds2(node.getId(), - startDate, endCal.getTime()); - Set choiceAnswerIds = node.getChoiceAnswerIds(); - - GenericIntakeDAO.GenericIntakeReportStatistics reportStatistics = genericIntakeDAO - .getReportStatistics2(intakeIds, choiceAnswerIds); - - return reportStatistics; - } - - public Map> getQuestionStatistics( - String nodeId, String intakeType, Integer programId, Date startDate, Date endDate, - boolean includePast) throws SQLException { - Map> questionStatistics = new LinkedHashMap>(); - - // get node - IntakeNode node = null; - - if (Intake.QUICK.equalsIgnoreCase(intakeType)) { - node = getQuickIntakeNode(); - } else if (Intake.INDEPTH.equalsIgnoreCase(intakeType)) { - node = getIndepthIntakeNode(); - } else if (Intake.PROGRAM.equalsIgnoreCase(intakeType)) { - node = getProgramIntakeNode(programId); - } else { - node = getIntakeNode(Integer.valueOf(nodeId)); - } - - if(node==null) { - logger.info("No node found with given parameters"); - return questionStatistics; - } - // get report statistics - List nodeList = getEqIntakeNodes(node, includePast); - Hashtable choiceAnswerIds = new Hashtable(); - SortedSet latestIntakeIds = new TreeSet(); - for (IntakeNode iN : nodeList) { - choiceAnswerIds.putAll(getEqAnswerIds(iN.getChoiceAnswerIds(), - includePast)); - latestIntakeIds.addAll(genericIntakeDAO.getLatestIntakeIds(iN - .getId(), startDate, endDate)); - } - if (includePast) - buildlastIndex(choiceAnswerIds); - - SortedMap> reportStatistics = genericIntakeDAO - .getReportStatistics(choiceAnswerIds, latestIntakeIds); - // populate map - if (!reportStatistics.isEmpty()) { - List questionList = new ArrayList(); - for (IntakeNode n : nodeList) { - questionList.addAll(n.getQuestionsWithChoiceAnswers()); - } - Hashtable questionIds = getEqQuestionIds( - questionList, includePast); - if (includePast) - buildlastIndex(questionIds); - - List nodeIds = new ArrayList(); - List counts = new ArrayList(); - List totals = new ArrayList(); - List labels = new ArrayList(); - List keys = new ArrayList(); - for (IntakeNode question : questionList) { - for (IntakeNode answer : question.getChoiceAnswers()) { - SortedMap valueStatistics = reportStatistics - .get(answer.getId()); - - if (valueStatistics != null) { - int total = 0; - for (Entry valueStatistic : valueStatistics - .entrySet()) { - ReportStatistic statistic = valueStatistic - .getValue(); - nodeIds.add(answer.getId()); - counts.add(statistic.getCount()); - total += statistic.getCount(); - labels.add(answer.getLabelStr()); - keys.add(valueStatistic.getKey()); - } - for (int i = totals.size(); i < counts.size(); i++) { - totals.add(total); - } - } - } - } - - if (includePast) { - List chngttl = new ArrayList(); - int maxttl = 0; - for (int id : choiceAnswerIds.keySet()) { - int cid = choiceAnswerIds.get(id); - if (id == cid) - continue; - - int x = nodeIds.indexOf(cid), idx_t = -1, idx_f = -1, cnt_t = 0, cnt_f = 0, ttl_t = 0, ttl_f = 0; - for (int i = 0; i < nodeIds.size(); i++) { - int nid = nodeIds.get(i); - if (nid != id && nid != cid) - continue; - if (counts.get(i).equals(-1)) - continue; - - if (nid == id) { - nodeIds.set(i, cid); - if (x != -1) - labels.set(i, labels.get(x)); - } - if (keys.get(i).equals("T")) { - cnt_t += counts.get(i); - ttl_t += totals.get(i); - idx_t = i; - } else { - cnt_f += counts.get(i); - ttl_f += totals.get(i); - idx_f = i; - } - counts.set(i, -1); - chngttl.add(i); - } - if (idx_t != -1) { - counts.set(idx_t, cnt_t); - totals.set(idx_t, ttl_t); - } - if (idx_f != -1) { - counts.set(idx_f, cnt_f); - totals.set(idx_f, ttl_f); - } - maxttl = ttl_t > maxttl ? ttl_t : maxttl; - maxttl = ttl_f > maxttl ? ttl_f : maxttl; - } - for (int i : chngttl) - totals.set(i, maxttl); - } - - List missResponses = new ArrayList(); - List missResponseIds = new ArrayList(); - for (IntakeNode question : questionList) { - SortedSet statistics = new TreeSet(); - Integer eqQuestionId = questionIds.get(question.getId()); - boolean showQuestion = false; - if (eqQuestionId.equals(question.getId())) - showQuestion = true; - - for (IntakeNode answer : question.getChoiceAnswers()) { - for (int i = 0; i < nodeIds.size(); i++) { - if (!nodeIds.get(i).equals(answer.getId())) - continue; - if (counts.get(i).equals(-1)) - continue; - - ReportStatistic statistic = new ReportStatistic(counts - .get(i), totals.get(i)); - if (showQuestion) { - statistic.setLabel(createStatisticLabel(labels - .get(i), keys.get(i))); - statistics.add(statistic); - } else { - statistic.setLabel(createStatisticLabel(labels - .get(i) - + " (missing responses)", keys.get(i))); - missResponseIds.add(eqQuestionId); - missResponses.add(statistic); - } - } - } - - if (showQuestion) { - for (int i = 0; i < missResponseIds.size(); i++) { - if (!missResponseIds.get(i).equals(question.getId())) - continue; - - statistics.add(missResponses.get(i)); - missResponseIds.set(i, -1); - } - questionStatistics.put(question.getLabelStr(), statistics); - } - } - } - return questionStatistics; - } - - private Intake createIntake(IntakeNode node, Integer clientId, - Integer programId, String staffId) { - Intake intake = Intake.create(node, clientId, programId, staffId); - createAnswers(intake, intake.getNode().getChildren()); - - return intake; - } - - public Intake copyIntakeWithId(IntakeNode node, Integer clientId, - Integer programId, String staffId, Integer facilityId) { - Intake source = genericIntakeDAO.getLatestIntake(node, clientId, - programId, facilityId); - - // Intake dest = createIntakeWithId(node, clientId, programId, - // staffId,source.getId(),source.getIntakeLocation()); - Intake dest = null; - - if (source != null) { - dest = createIntakeWithId(node, clientId, programId, staffId, - source.getId(), source.getIntakeLocation()); - - for (IntakeAnswer answer : source.getAnswers()) { - if(answer.getNode().getRepeating()) { - dest.getRepeatingAnswerMapped(answer.getNode().getIdStr(), answer.getIndex()).setValue(answer.getValue()); - } else { - dest.getAnswerMapped(answer.getNode().getIdStr()).setValue( answer.getValue()); - } - } - } - - return dest; - } - - private Intake copyOldIntake(IntakeNode sourceNode, Intake source, - Integer clientId, Integer programId, String staffId, - Integer facilityId) { - Intake dest = null; - IntakeNode destNode = getQuickIntakeNode(); - - if (source != null) { - dest = createIntake(destNode, clientId, programId, staffId); - - for (IntakeAnswer ia : dest.getAnswers()) { - if (ia.isAnswerScalar()) { - if (ia.getNode().getId().intValue() != ia.getNode() - .getEq_to_id().intValue()) { - try { - String value = source.getAnswerMapped( - String.valueOf(ia.getNode().getEq_to_id())) - .getValue(); - - ia.setValue(value); - } catch (IllegalStateException e) { - logger.warn("Warning", e); - } - } - } - } - } - - return dest; - } - - private Intake createIntakeWithId(IntakeNode node, Integer clientId, - Integer programId, String staffId, Integer intakeId, - Integer intakeLocation) { - Intake intake = Intake.create(node, clientId, programId, staffId, - intakeId, intakeLocation); - createAnswers(intake, intake.getNode().getChildren()); - - return intake; - } - - private void createAnswers(Intake intake, List children) { - for (IntakeNode child : children) { - if (child != null) { - if (child.isAnswerScalar()) { - intake.addToanswers(IntakeAnswer.create(child)); - } - - createAnswers(intake, child.getChildren()); - } - } - } - - private IntakeNode getQuickIntakeNode() { - Agency agency = Agency.getLocalAgency(); - Integer quickIntakeNodeId = (agency != null) ? agency.getIntakeQuick() - : null; - - return getIntakeNode(quickIntakeNodeId); - } - - private IntakeNode getIntakeNodeByIntakeId(Integer intakeId) { - Integer intakeNodeId = genericIntakeDAO - .getIntakeNodeIdByIntakeId(intakeId); - return getIntakeNode(intakeNodeId); - } - - private List getRegIntakeNodes(Integer clientId) { - List nodeIds = genericIntakeDAO - .getIntakeNodesIdByClientId(clientId,1); - List nodeList = new ArrayList(); - if (nodeIds.size() > 0) { - for (Integer i : nodeIds) { - nodeList.add(getIntakeNode(i)); - } - } else { - nodeList.add(getQuickIntakeNode()); - } - return nodeList; - } - - private IntakeNode getLatestRegIntakeNodes(Integer clientId) { - // List nodeIds = - // genericIntakeDAO.getIntakeNodesIdByClientId(clientId); - - // IntakeNode node = getIntakeNode(nodeIds.get(0)); - // return node; - - Agency agency = Agency.getLocalAgency(); - Integer quickIntakeNodeId = (agency != null) ? agency.getIntakeQuick() - : null; - return getIntakeNode(quickIntakeNodeId); - } - - private IntakeNode getIndepthIntakeNode() { - Agency agency = Agency.getLocalAgency(); - Integer indepthIntakeNodeId = (agency != null) ? agency - .getIntakeIndepth() : null; - - return getIntakeNode(indepthIntakeNodeId); - } - - private IntakeNode getProgramIntakeNode(Integer programId) { - return getProgramIntakeNode(programDao.getProgram(programId)); - } - - private IntakeNode getProgramIntakeNode(Program program) { - Integer programIntakeNodeId = (program != null) ? program - .getIntakeProgram() : null; - - return getIntakeNode(programIntakeNodeId); - } - - private List getEqIntakeNodes(IntakeNode iNode, boolean incpast) - throws SQLException { - if (incpast) { - return genericIntakeNodeDAO.getIntakeNodeByEqToId(iNode - .getEq_to_id()); - } - List iNodeList = new ArrayList(); - iNodeList.add(iNode); - return iNodeList; - } - - private Hashtable getEqAnswerIds(Set caIds, - boolean incpast) throws SQLException { - Hashtable eqNodeIdsHash = new Hashtable(); - - for (Integer Id : caIds) { - if (incpast) { - for (Integer nodeId : genericIntakeNodeDAO - .getEqToIdByIntakeNodeId(Id)) { - eqNodeIdsHash.put(Id, nodeId); - } - } else { - eqNodeIdsHash.put(Id, Id); - } - } - return eqNodeIdsHash; - } - - private Hashtable getEqQuestionIds( - List qNodes, boolean incpast) throws SQLException { - Hashtable eqNodeIdsHash = new Hashtable(); - - for (IntakeNode qNode : qNodes) { - if (incpast) { - for (Integer nodeId : genericIntakeNodeDAO - .getEqToIdByIntakeNodeId(qNode.getId())) { - eqNodeIdsHash.put(qNode.getId(), nodeId); - } - } else { - eqNodeIdsHash.put(qNode.getId(), qNode.getId()); - } - } - return eqNodeIdsHash; - } - - private void buildlastIndex(Hashtable eqNodeIds) { - Hashtable eqNodeIdsLastIdx = new Hashtable(); - - for (Integer i : eqNodeIds.keySet()) { - int nid = -1; - for (Integer j : eqNodeIds.keySet()) { - if (i == j) - continue; - if (eqNodeIds.get(i) == eqNodeIds.get(j)) { - nid = i > j ? i : j; - } - } - nid = nid == -1 ? i : nid; - eqNodeIdsLastIdx.put(i, nid); - } - eqNodeIds.clear(); - eqNodeIds.putAll(eqNodeIdsLastIdx); - } - - public List getIntakeNodes() { - return genericIntakeNodeDAO.getIntakeNodes(); - } - - public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel) { - genericIntakeNodeDAO.saveNodeLabel(intakeNodeLabel); - } - - public void saveIntakeNode(IntakeNode intakeNode) { - genericIntakeNodeDAO.saveIntakeNode(intakeNode); - } - - public void deleteIntakeForm(IntakeNode intakeNode) { - genericIntakeNodeDAO.deleteIntakeNode(intakeNode); - } - - public void updateIntakeNode(IntakeNode intakeNode) { - genericIntakeNodeDAO.updateIntakeNode(intakeNode); - } - - public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate) { - genericIntakeNodeDAO.saveIntakeNodeTemplate(intakeNodeTemplate); - } - - public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement) { - genericIntakeNodeDAO.saveIntakeAnswerElement(intakeAnswerElement); - } - - // / - public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel) { - genericIntakeNodeDAO.updateNodeLabel(intakeNodeLabel); - } - - public void updateAgencyIntakeQuick(Integer intakeNodeId) { - Agency agency = Agency.getLocalAgency(); - agency.setIntakeQuick(intakeNodeId); - genericIntakeNodeDAO.updateAgencyIntakeQuick(agency); - } - - public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId) { - return genericIntakeNodeDAO.getIntakeNodeLabel(intakeNodeLabelId); - } - - public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId) { - return genericIntakeNodeDAO.getIntakeNodeTemplate(intakeNodeTemplateId); - } - - public IntakeNode getIntakeNode(Integer nodeId) { - if (nodeId == null) { - throw new IllegalArgumentException( - "Parameter nodeId must be non-null"); - } - - IntakeNode node = genericIntakeNodeDAO.getIntakeNode(nodeId); - - if (!node.isIntake()) { - throw new IllegalStateException("node with id : " + nodeId - + " is not an intake"); - } - - return node; - } - - private String createStatisticLabel(String answerLabel, String answerElement) { - StringBuilder builder = new StringBuilder(); - - builder.append(answerLabel); - - if (builder.length() > 0) { - builder.append(":"); - } - - builder.append(answerElement); - - return builder.toString(); - } - - public List getIntakeNodesByType(Integer formType) { - return genericIntakeDAO.getIntakeNodesByType(formType); - } - - public List> getIntakeListforOcan(Calendar after) { - Map> pairs = new HashMap>(); - - List triads = genericIntakeDAO.getOcanIntakesAfterDate(after); - for (Object[] triad : triads) { - Intake i = (Intake) triad[0]; - IntakeNode n = (IntakeNode) triad[1]; - IntakeNodeLabel l = (IntakeNodeLabel) triad[2]; - String key = l.getLabel().indexOf("Client") > -1 ? "client" : "staff"; - i.setNode(n); - if (!pairs.containsKey(i.getClientId())) { - // new client - Map pair = new HashMap(); - pair.put(key, i); - pairs.put(i.getClientId(), pair); - } else if (!pairs.get(i.getClientId()).containsKey(key)) { - // new key - Map pair = pairs.get(i.getClientId()); - pair.put(key, i); - } - } - - List> list = new ArrayList>(); - - for (Integer clientId : pairs.keySet()) { - Map pair = pairs.get(clientId); - if (pair.size() == 2) { - // need both client and staff - Map entry = new HashMap(); - entry.put("clientId", clientId.toString()); - entry.put("client", toXml(pair, "client")); - entry.put("staff", toXml(pair, "staff")); - list.add(entry); - } - } - - return list; - } - - private String toXml(Map intakeMap, String type) { - StringBuilder xml = new StringBuilder(); - Intake intake = intakeMap.get(type); - if ("client".equals(type)) { - toClientXml(xml, intake, intake.getNode()); - } else { - toStaffXml(xml, intake, intake.getNode()); - } - return xml.toString(); - } - - private void toClientXml(StringBuilder builder, Intake intake, IntakeNode node) { - if (node == null) - return; - IntakeNodeHtmlAdapter htmlAdapter = adapterFactory.getOcanClientXmlAdapter(0, node, intake); - - builder.append(htmlAdapter.getPreBuilder()); - - for (IntakeNode child : node.getChildren()) { - toClientXml(builder, intake, child); - } - - builder.append(htmlAdapter.getPostBuilder()); - } - - private void toStaffXml(StringBuilder builder, Intake intake, IntakeNode node) { - if (node == null) - return; - IntakeNodeHtmlAdapter htmlAdapter = adapterFactory.getOcanStaffXmlAdapter(0, node, intake); - - builder.append(htmlAdapter.getPreBuilder()); - - for (IntakeNode child : node.getChildren()) { - toStaffXml(builder, intake, child); - } - - builder.append(htmlAdapter.getPostBuilder()); - } - - /* - * street health report, not finished yet public List getCohort(Date - * beginDate, Date endDate) { return genericIntakeDAO.getCohort(beginDate, - * endDate, demographicDao.getClients()); } - */ - - - public List getIntakeNodeJavascriptLocation(String questionId) { - if(questionId != null && questionId.length()>0) { - return this.genericIntakeNodeDAO.getIntakeNodeJavascriptLocation(questionId); - } - return null; - } -} + package org.oscarehr.PMmodule.service; + + import java.sql.SQLException; + import java.util.ArrayList; + import java.util.Calendar; + import java.util.Date; + import java.util.HashMap; + import java.util.Hashtable; + import java.util.LinkedHashMap; + import java.util.List; + import java.util.Map; + import java.util.Map.Entry; + import java.util.Set; + import java.util.SortedMap; + import java.util.SortedSet; + import java.util.TreeSet; + + import org.apache.logging.log4j.Logger; + import org.oscarehr.PMmodule.dao.GenericIntakeDAO; + import org.oscarehr.PMmodule.dao.GenericIntakeDAOImpl; + import org.oscarehr.PMmodule.dao.GenericIntakeNodeDAO; + import org.oscarehr.PMmodule.dao.ProgramDao; + import org.oscarehr.PMmodule.model.Agency; + import org.oscarehr.PMmodule.model.Intake; + import org.oscarehr.PMmodule.model.IntakeAnswer; + import org.oscarehr.PMmodule.model.IntakeAnswerElement; + import org.oscarehr.PMmodule.model.IntakeNode; + import org.oscarehr.PMmodule.model.IntakeNodeJavascript; + import org.oscarehr.PMmodule.model.IntakeNodeLabel; + import org.oscarehr.PMmodule.model.IntakeNodeTemplate; + import org.oscarehr.PMmodule.model.Program; + import org.oscarehr.PMmodule.web.adapter.IntakeNodeHtmlAdapter; + import org.oscarehr.PMmodule.web.adapter.ocan.OcanXmlAdapterFactory; + import org.oscarehr.common.dao.AdmissionDao; + import org.oscarehr.common.model.Admission; + import org.oscarehr.common.model.ReportStatistic; + import org.oscarehr.util.MiscUtils; + import org.springframework.transaction.annotation.Transactional; + + public interface GenericIntakeManager { + public void setGenericIntakeNodeDAO( + GenericIntakeNodeDAO genericIntakeNodeDAO); + + public void setGenericIntakeDAO(GenericIntakeDAO genericIntakeDAO); + + public void setProgramDao(ProgramDao programDao); + + public void setAdmissionDao(AdmissionDao admissionDao); + + // Copy + + public Intake copyQuickIntake(Integer clientId, String staffId, + Integer facilityId); + + public Intake copyRegIntake(Integer clientId, String staffId, + Integer facilityId); + + public Intake copyIndepthIntake(Integer clientId, String staffId, + Integer facilityId); + + public Intake copyProgramIntake(Integer clientId, Integer programId, + String staffId, Integer facilityId); + + // Create + + public Intake createQuickIntake(String providerNo); + + public Intake createIndepthIntake(String providerNo); + + public Intake createIntake(IntakeNode node, String providerNo); + + public Intake createProgramIntake(Integer programId, String providerNo); + + // Get + + public Intake getMostRecentQuickIntakeByFacility(Integer clientId, + Integer facilityId); + + public Intake getMostRecentQuickIntake(Integer clientId, Integer facilityId); + + public Intake getRegIntakeById(Integer intakeId, Integer facilityId); + public Intake getMostRecentIndepthIntake(Integer clientId, + Integer facilityId); + public Intake getMostRecentProgramIntake(Integer clientId, + Integer programId, Integer facilityId); + public List getQuickIntakes(Integer clientId, Integer facilityId); + + public List getRegIntakes(Integer clientId, Integer facilityId); + + public List getIntakeClientsByFacilityId(Integer facilityId); + public List getIntakeFacilityIds(); + + public List getIndepthIntakes(Integer clientId, Integer facilityId); + + public List getProgramIntakes(Integer clientId, Integer facilityId); + + public List getIntakesByType(Integer clientId, Integer facilityId, Integer formType); + + public List getProgramsWithIntake(Integer clientId); + + // Save + + public Integer saveIntake(Intake intake); + + // Save Or Update + + public void saveUpdateIntake(Intake intake); + + // Report + + public GenericIntakeDAOImpl.GenericIntakeReportStatistics getQuestionStatistics2( + String intakeType, Integer programId, Date startDate, Date endDate) + throws SQLException; + + public Map> getQuestionStatistics( + String nodeId, String intakeType, Integer programId, Date startDate, Date endDate, + boolean includePast) throws SQLException; + + public Intake copyIntakeWithId(IntakeNode node, Integer clientId, + Integer programId, String staffId, Integer facilityId); + + public List getIntakeNodes(); + + public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel); + + public void saveIntakeNode(IntakeNode intakeNode); + public void deleteIntakeForm(IntakeNode intakeNode); + public void updateIntakeNode(IntakeNode intakeNode); + public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate); + + public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement); + public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel); + + public void updateAgencyIntakeQuick(Integer intakeNodeId); + public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId); + + public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId); + public IntakeNode getIntakeNode(Integer nodeId); + + public List getIntakeNodesByType(Integer formType); + + public List> getIntakeListforOcan(Calendar after); + /* + * street health report, not finished yet public List getCohort(Date + * beginDate, Date endDate) { return genericIntakeDAO.getCohort(beginDate, + * endDate, demographicDao.getClients()); } + */ + + + public List getIntakeNodeJavascriptLocation(String questionId); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManagerImpl.java new file mode 100644 index 0000000000..dc40943789 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/GenericIntakeManagerImpl.java @@ -0,0 +1,872 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.service; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Hashtable; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.apache.logging.log4j.Logger; +import org.oscarehr.PMmodule.dao.GenericIntakeDAO; +import org.oscarehr.PMmodule.dao.GenericIntakeDAOImpl; +import org.oscarehr.PMmodule.dao.GenericIntakeNodeDAO; +import org.oscarehr.PMmodule.dao.ProgramDao; +import org.oscarehr.PMmodule.model.Agency; +import org.oscarehr.PMmodule.model.Intake; +import org.oscarehr.PMmodule.model.IntakeAnswer; +import org.oscarehr.PMmodule.model.IntakeAnswerElement; +import org.oscarehr.PMmodule.model.IntakeNode; +import org.oscarehr.PMmodule.model.IntakeNodeJavascript; +import org.oscarehr.PMmodule.model.IntakeNodeLabel; +import org.oscarehr.PMmodule.model.IntakeNodeTemplate; +import org.oscarehr.PMmodule.model.Program; +import org.oscarehr.PMmodule.web.adapter.IntakeNodeHtmlAdapter; +import org.oscarehr.PMmodule.web.adapter.ocan.OcanXmlAdapterFactory; +import org.oscarehr.common.dao.AdmissionDao; +import org.oscarehr.common.model.Admission; +import org.oscarehr.common.model.ReportStatistic; +import org.oscarehr.util.MiscUtils; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class GenericIntakeManagerImpl implements GenericIntakeManager { + + private GenericIntakeNodeDAO genericIntakeNodeDAO; + private GenericIntakeDAO genericIntakeDAO; + private GenericIntakeDAOImpl genericIntakeDAOImpl; + private ProgramDao programDao; + private AdmissionDao admissionDao; + private OcanXmlAdapterFactory adapterFactory = new OcanXmlAdapterFactory(); + + private static Logger logger = MiscUtils.getLogger(); + + public void setGenericIntakeNodeDAO( + GenericIntakeNodeDAO genericIntakeNodeDAO) { + this.genericIntakeNodeDAO = genericIntakeNodeDAO; + } + + public void setGenericIntakeDAO(GenericIntakeDAO genericIntakeDAO) { + this.genericIntakeDAO = genericIntakeDAO; + } + + public void setProgramDao(ProgramDao programDao) { + this.programDao = programDao; + } + + public void setAdmissionDao(AdmissionDao admissionDao) { + this.admissionDao = admissionDao; + } + + // Copy + + public Intake copyQuickIntake(Integer clientId, String staffId, + Integer facilityId) { + // return copyIntake(getQuickIntakeNode(), clientId, null, staffId); + return copyIntakeWithId(getQuickIntakeNode(), clientId, null, staffId, + facilityId); + } + + public Intake copyRegIntake(Integer clientId, String staffId, + Integer facilityId) { + // return copyIntake(getQuickIntakeNode(), clientId, null, staffId); + IntakeNode latestInode = getLatestRegIntakeNodes(clientId); + Intake intake = this.genericIntakeDAO.getLatestIntakeByFacility( + latestInode, clientId, null, facilityId); + if (intake != null) { + return copyIntakeWithId(latestInode, clientId, null, staffId, + facilityId); + } else { + IntakeNode qin = this.getQuickIntakeNode(); + if (qin.getLabel() == null) { + return null; + } + List previousIntakeNodes = genericIntakeNodeDAO + .getPublishedIntakeNodesByName(qin.getLabel().getLabel()); + for (IntakeNode in : previousIntakeNodes) { + intake = genericIntakeDAO.getLatestIntakeByFacility(in, + clientId, null, facilityId); + if (intake != null) + return copyOldIntake(latestInode, intake, clientId, null, + staffId, facilityId); + } + } + return null; + } + + public Intake copyIndepthIntake(Integer clientId, String staffId, + Integer facilityId) { + // return copyIntake(getIndepthIntakeNode(), clientId, null, staffId); + return copyIntakeWithId(getIndepthIntakeNode(), clientId, null, + staffId, facilityId); + } + + public Intake copyProgramIntake(Integer clientId, Integer programId, + String staffId, Integer facilityId) { + // return copyIntake(getProgramIntakeNode(programId), clientId, + // programId, staffId); + return copyIntakeWithId(getProgramIntakeNode(programId), clientId, + programId, staffId, facilityId); + } + + // Create + + public Intake createQuickIntake(String providerNo) { + return createIntake(getQuickIntakeNode(), null, null, providerNo); + } + + public Intake createIndepthIntake(String providerNo) { + return createIntake(getIndepthIntakeNode(), null, null, providerNo); + } + + public Intake createIntake(IntakeNode node, String providerNo) { + return createIntake(node, null, null, providerNo); + } + + public Intake createProgramIntake(Integer programId, String providerNo) { + return createIntake(getProgramIntakeNode(programId), null, programId, + providerNo); + } + + // Get + + public Intake getMostRecentQuickIntakeByFacility(Integer clientId, + Integer facilityId) { + IntakeNode regIntakeNode = getQuickIntakeNode(); + Intake intake = genericIntakeDAO.getLatestIntakeByFacility( + regIntakeNode, clientId, null, facilityId); + + if (intake == null && regIntakeNode.getLabel() != null) { + /* + * search old registration intakes in proper order to make sure we + * return the latest one + */ + List previousIntakeNodes = genericIntakeNodeDAO + .getPublishedIntakeNodesByName(regIntakeNode.getLabel() + .getLabel()); + for (IntakeNode in : previousIntakeNodes) { + logger.info("searching for intakes for node version: " + + in.getForm_version()); + intake = genericIntakeDAO.getLatestIntakeByFacility(in, + clientId, null, facilityId); + if (intake != null) + break; + } + } + + return intake; + } + + public Intake getMostRecentQuickIntake(Integer clientId, Integer facilityId) { + return genericIntakeDAO.getLatestIntake(getQuickIntakeNode(), clientId, + null, facilityId); + } + + public Intake getRegIntakeById(Integer intakeId, Integer facilityId) { + return genericIntakeDAO.getIntakeById( + getIntakeNodeByIntakeId(intakeId), intakeId, null, facilityId); + } + + public Intake getMostRecentIndepthIntake(Integer clientId, + Integer facilityId) { + return genericIntakeDAO.getLatestIntake(getIndepthIntakeNode(), + clientId, null, facilityId); + } + + public Intake getMostRecentProgramIntake(Integer clientId, + Integer programId, Integer facilityId) { + return genericIntakeDAO.getLatestIntake( + getProgramIntakeNode(programId), clientId, programId, + facilityId); + } + + public List getQuickIntakes(Integer clientId, Integer facilityId) { + return genericIntakeDAO.getIntakes(getQuickIntakeNode(), clientId, + null, facilityId); + } + + public List getRegIntakes(Integer clientId, Integer facilityId) { + return genericIntakeDAO.getRegIntakes(getRegIntakeNodes(clientId), + clientId, null, facilityId); + } + + public List getIntakeClientsByFacilityId(Integer facilityId) { + return genericIntakeDAO.getIntakeClientsByFacilityId(facilityId); + } + + public List getIntakeFacilityIds() { + return genericIntakeDAO.getIntakeFacilityIds(); + } + + public List getIndepthIntakes(Integer clientId, Integer facilityId) { + return genericIntakeDAO.getIntakes(getIndepthIntakeNode(), clientId, + null, facilityId); + } + + public List getProgramIntakes(Integer clientId, Integer facilityId) { + List programIntakes = new ArrayList(); + + for (Program program : getProgramsWithIntake(clientId)) { + programIntakes.addAll(genericIntakeDAO.getIntakes( + getProgramIntakeNode(program), clientId, program.getId(), + facilityId)); + } + + return programIntakes; + } + + public List getIntakesByType(Integer clientId, Integer facilityId, Integer formType) { + return genericIntakeDAO.getIntakesByType(formType, clientId, + null, facilityId); + } + + public List getProgramsWithIntake(Integer clientId) { + List programsWithIntake = new ArrayList(); + + List serviceProgramAdmissions = admissionDao + .getCurrentServiceProgramAdmission(programDao, clientId); + if (serviceProgramAdmissions != null) { + for (Object o : serviceProgramAdmissions) { + Admission admission = (Admission) o; + Program program = programDao.getProgram(admission + .getProgramId()); + + if (program != null && program.getIntakeProgram() != null) { + programsWithIntake.add(program); + } + } + } + + return programsWithIntake; + } + + // Save + + public Integer saveIntake(Intake intake) { + return genericIntakeDAO.saveIntake(intake); + } + + // Save Or Update + + public void saveUpdateIntake(Intake intake) { + genericIntakeDAO.saveUpdateIntake(intake); + } + + // Report + + public GenericIntakeDAOImpl.GenericIntakeReportStatistics getQuestionStatistics2( + String intakeType, Integer programId, Date startDate, Date endDate) + throws SQLException { + + // get node + IntakeNode node = null; + + if (Intake.QUICK.equalsIgnoreCase(intakeType)) { + node = getQuickIntakeNode(); + } else if (Intake.INDEPTH.equalsIgnoreCase(intakeType)) { + node = getIndepthIntakeNode(); + } else if (Intake.PROGRAM.equalsIgnoreCase(intakeType)) { + node = getProgramIntakeNode(programId); + } + + Calendar endCal = Calendar.getInstance(); + endCal.setTime(endDate); + endCal.add(Calendar.DAY_OF_YEAR, 1); + List intakeIds = genericIntakeDAO.getIntakeIds2(node.getId(), + startDate, endCal.getTime()); + Set choiceAnswerIds = node.getChoiceAnswerIds(); + + GenericIntakeDAOImpl.GenericIntakeReportStatistics reportStatistics = genericIntakeDAOImpl + .getReportStatistics2(intakeIds, choiceAnswerIds); + + return reportStatistics; + } + + public Map> getQuestionStatistics( + String nodeId, String intakeType, Integer programId, Date startDate, Date endDate, + boolean includePast) throws SQLException { + Map> questionStatistics = new LinkedHashMap>(); + + // get node + IntakeNode node = null; + + if (Intake.QUICK.equalsIgnoreCase(intakeType)) { + node = getQuickIntakeNode(); + } else if (Intake.INDEPTH.equalsIgnoreCase(intakeType)) { + node = getIndepthIntakeNode(); + } else if (Intake.PROGRAM.equalsIgnoreCase(intakeType)) { + node = getProgramIntakeNode(programId); + } else { + node = getIntakeNode(Integer.valueOf(nodeId)); + } + + if(node==null) { + logger.info("No node found with given parameters"); + return questionStatistics; + } + // get report statistics + List nodeList = getEqIntakeNodes(node, includePast); + Hashtable choiceAnswerIds = new Hashtable(); + SortedSet latestIntakeIds = new TreeSet(); + for (IntakeNode iN : nodeList) { + choiceAnswerIds.putAll(getEqAnswerIds(iN.getChoiceAnswerIds(), + includePast)); + latestIntakeIds.addAll(genericIntakeDAO.getLatestIntakeIds(iN + .getId(), startDate, endDate)); + } + if (includePast) + buildlastIndex(choiceAnswerIds); + + SortedMap> reportStatistics = genericIntakeDAO + .getReportStatistics(choiceAnswerIds, latestIntakeIds); + // populate map + if (!reportStatistics.isEmpty()) { + List questionList = new ArrayList(); + for (IntakeNode n : nodeList) { + questionList.addAll(n.getQuestionsWithChoiceAnswers()); + } + Hashtable questionIds = getEqQuestionIds( + questionList, includePast); + if (includePast) + buildlastIndex(questionIds); + + List nodeIds = new ArrayList(); + List counts = new ArrayList(); + List totals = new ArrayList(); + List labels = new ArrayList(); + List keys = new ArrayList(); + for (IntakeNode question : questionList) { + for (IntakeNode answer : question.getChoiceAnswers()) { + SortedMap valueStatistics = reportStatistics + .get(answer.getId()); + + if (valueStatistics != null) { + int total = 0; + for (Entry valueStatistic : valueStatistics + .entrySet()) { + ReportStatistic statistic = valueStatistic + .getValue(); + nodeIds.add(answer.getId()); + counts.add(statistic.getCount()); + total += statistic.getCount(); + labels.add(answer.getLabelStr()); + keys.add(valueStatistic.getKey()); + } + for (int i = totals.size(); i < counts.size(); i++) { + totals.add(total); + } + } + } + } + + if (includePast) { + List chngttl = new ArrayList(); + int maxttl = 0; + for (int id : choiceAnswerIds.keySet()) { + int cid = choiceAnswerIds.get(id); + if (id == cid) + continue; + + int x = nodeIds.indexOf(cid), idx_t = -1, idx_f = -1, cnt_t = 0, cnt_f = 0, ttl_t = 0, ttl_f = 0; + for (int i = 0; i < nodeIds.size(); i++) { + int nid = nodeIds.get(i); + if (nid != id && nid != cid) + continue; + if (counts.get(i).equals(-1)) + continue; + + if (nid == id) { + nodeIds.set(i, cid); + if (x != -1) + labels.set(i, labels.get(x)); + } + if (keys.get(i).equals("T")) { + cnt_t += counts.get(i); + ttl_t += totals.get(i); + idx_t = i; + } else { + cnt_f += counts.get(i); + ttl_f += totals.get(i); + idx_f = i; + } + counts.set(i, -1); + chngttl.add(i); + } + if (idx_t != -1) { + counts.set(idx_t, cnt_t); + totals.set(idx_t, ttl_t); + } + if (idx_f != -1) { + counts.set(idx_f, cnt_f); + totals.set(idx_f, ttl_f); + } + maxttl = ttl_t > maxttl ? ttl_t : maxttl; + maxttl = ttl_f > maxttl ? ttl_f : maxttl; + } + for (int i : chngttl) + totals.set(i, maxttl); + } + + List missResponses = new ArrayList(); + List missResponseIds = new ArrayList(); + for (IntakeNode question : questionList) { + SortedSet statistics = new TreeSet(); + Integer eqQuestionId = questionIds.get(question.getId()); + boolean showQuestion = false; + if (eqQuestionId.equals(question.getId())) + showQuestion = true; + + for (IntakeNode answer : question.getChoiceAnswers()) { + for (int i = 0; i < nodeIds.size(); i++) { + if (!nodeIds.get(i).equals(answer.getId())) + continue; + if (counts.get(i).equals(-1)) + continue; + + ReportStatistic statistic = new ReportStatistic(counts + .get(i), totals.get(i)); + if (showQuestion) { + statistic.setLabel(createStatisticLabel(labels + .get(i), keys.get(i))); + statistics.add(statistic); + } else { + statistic.setLabel(createStatisticLabel(labels + .get(i) + + " (missing responses)", keys.get(i))); + missResponseIds.add(eqQuestionId); + missResponses.add(statistic); + } + } + } + + if (showQuestion) { + for (int i = 0; i < missResponseIds.size(); i++) { + if (!missResponseIds.get(i).equals(question.getId())) + continue; + + statistics.add(missResponses.get(i)); + missResponseIds.set(i, -1); + } + questionStatistics.put(question.getLabelStr(), statistics); + } + } + } + return questionStatistics; + } + + private Intake createIntake(IntakeNode node, Integer clientId, + Integer programId, String staffId) { + Intake intake = Intake.create(node, clientId, programId, staffId); + createAnswers(intake, intake.getNode().getChildren()); + + return intake; + } + + public Intake copyIntakeWithId(IntakeNode node, Integer clientId, + Integer programId, String staffId, Integer facilityId) { + Intake source = genericIntakeDAO.getLatestIntake(node, clientId, + programId, facilityId); + + // Intake dest = createIntakeWithId(node, clientId, programId, + // staffId,source.getId(),source.getIntakeLocation()); + Intake dest = null; + + if (source != null) { + dest = createIntakeWithId(node, clientId, programId, staffId, + source.getId(), source.getIntakeLocation()); + + for (IntakeAnswer answer : source.getAnswers()) { + if(answer.getNode().getRepeating()) { + dest.getRepeatingAnswerMapped(answer.getNode().getIdStr(), answer.getIndex()).setValue(answer.getValue()); + } else { + dest.getAnswerMapped(answer.getNode().getIdStr()).setValue( answer.getValue()); + } + } + } + + return dest; + } + + private Intake copyOldIntake(IntakeNode sourceNode, Intake source, + Integer clientId, Integer programId, String staffId, + Integer facilityId) { + Intake dest = null; + IntakeNode destNode = getQuickIntakeNode(); + + if (source != null) { + dest = createIntake(destNode, clientId, programId, staffId); + + for (IntakeAnswer ia : dest.getAnswers()) { + if (ia.isAnswerScalar()) { + if (ia.getNode().getId().intValue() != ia.getNode() + .getEq_to_id().intValue()) { + try { + String value = source.getAnswerMapped( + String.valueOf(ia.getNode().getEq_to_id())) + .getValue(); + + ia.setValue(value); + } catch (IllegalStateException e) { + logger.warn("Warning", e); + } + } + } + } + } + + return dest; + } + + private Intake createIntakeWithId(IntakeNode node, Integer clientId, + Integer programId, String staffId, Integer intakeId, + Integer intakeLocation) { + Intake intake = Intake.create(node, clientId, programId, staffId, + intakeId, intakeLocation); + createAnswers(intake, intake.getNode().getChildren()); + + return intake; + } + + private void createAnswers(Intake intake, List children) { + for (IntakeNode child : children) { + if (child != null) { + if (child.isAnswerScalar()) { + intake.addToanswers(IntakeAnswer.create(child)); + } + + createAnswers(intake, child.getChildren()); + } + } + } + + private IntakeNode getQuickIntakeNode() { + Agency agency = Agency.getLocalAgency(); + Integer quickIntakeNodeId = (agency != null) ? agency.getIntakeQuick() + : null; + + return getIntakeNode(quickIntakeNodeId); + } + + private IntakeNode getIntakeNodeByIntakeId(Integer intakeId) { + Integer intakeNodeId = genericIntakeDAO + .getIntakeNodeIdByIntakeId(intakeId); + return getIntakeNode(intakeNodeId); + } + + private List getRegIntakeNodes(Integer clientId) { + List nodeIds = genericIntakeDAO + .getIntakeNodesIdByClientId(clientId,1); + List nodeList = new ArrayList(); + if (nodeIds.size() > 0) { + for (Integer i : nodeIds) { + nodeList.add(getIntakeNode(i)); + } + } else { + nodeList.add(getQuickIntakeNode()); + } + return nodeList; + } + + private IntakeNode getLatestRegIntakeNodes(Integer clientId) { + // List nodeIds = + // genericIntakeDAO.getIntakeNodesIdByClientId(clientId); + + // IntakeNode node = getIntakeNode(nodeIds.get(0)); + // return node; + + Agency agency = Agency.getLocalAgency(); + Integer quickIntakeNodeId = (agency != null) ? agency.getIntakeQuick() + : null; + return getIntakeNode(quickIntakeNodeId); + } + + private IntakeNode getIndepthIntakeNode() { + Agency agency = Agency.getLocalAgency(); + Integer indepthIntakeNodeId = (agency != null) ? agency + .getIntakeIndepth() : null; + + return getIntakeNode(indepthIntakeNodeId); + } + + private IntakeNode getProgramIntakeNode(Integer programId) { + return getProgramIntakeNode(programDao.getProgram(programId)); + } + + private IntakeNode getProgramIntakeNode(Program program) { + Integer programIntakeNodeId = (program != null) ? program + .getIntakeProgram() : null; + + return getIntakeNode(programIntakeNodeId); + } + + private List getEqIntakeNodes(IntakeNode iNode, boolean incpast) + throws SQLException { + if (incpast) { + return genericIntakeNodeDAO.getIntakeNodeByEqToId(iNode + .getEq_to_id()); + } + List iNodeList = new ArrayList(); + iNodeList.add(iNode); + return iNodeList; + } + + private Hashtable getEqAnswerIds(Set caIds, + boolean incpast) throws SQLException { + Hashtable eqNodeIdsHash = new Hashtable(); + + for (Integer Id : caIds) { + if (incpast) { + for (Integer nodeId : genericIntakeNodeDAO + .getEqToIdByIntakeNodeId(Id)) { + eqNodeIdsHash.put(Id, nodeId); + } + } else { + eqNodeIdsHash.put(Id, Id); + } + } + return eqNodeIdsHash; + } + + private Hashtable getEqQuestionIds( + List qNodes, boolean incpast) throws SQLException { + Hashtable eqNodeIdsHash = new Hashtable(); + + for (IntakeNode qNode : qNodes) { + if (incpast) { + for (Integer nodeId : genericIntakeNodeDAO + .getEqToIdByIntakeNodeId(qNode.getId())) { + eqNodeIdsHash.put(qNode.getId(), nodeId); + } + } else { + eqNodeIdsHash.put(qNode.getId(), qNode.getId()); + } + } + return eqNodeIdsHash; + } + + private void buildlastIndex(Hashtable eqNodeIds) { + Hashtable eqNodeIdsLastIdx = new Hashtable(); + + for (Integer i : eqNodeIds.keySet()) { + int nid = -1; + for (Integer j : eqNodeIds.keySet()) { + if (i == j) + continue; + if (eqNodeIds.get(i) == eqNodeIds.get(j)) { + nid = i > j ? i : j; + } + } + nid = nid == -1 ? i : nid; + eqNodeIdsLastIdx.put(i, nid); + } + eqNodeIds.clear(); + eqNodeIds.putAll(eqNodeIdsLastIdx); + } + + public List getIntakeNodes() { + return genericIntakeNodeDAO.getIntakeNodes(); + } + + public void saveNodeLabel(IntakeNodeLabel intakeNodeLabel) { + genericIntakeNodeDAO.saveNodeLabel(intakeNodeLabel); + } + + public void saveIntakeNode(IntakeNode intakeNode) { + genericIntakeNodeDAO.saveIntakeNode(intakeNode); + } + + public void deleteIntakeForm(IntakeNode intakeNode) { + genericIntakeNodeDAO.deleteIntakeNode(intakeNode); + } + + public void updateIntakeNode(IntakeNode intakeNode) { + genericIntakeNodeDAO.updateIntakeNode(intakeNode); + } + + public void saveIntakeNodeTemplate(IntakeNodeTemplate intakeNodeTemplate) { + genericIntakeNodeDAO.saveIntakeNodeTemplate(intakeNodeTemplate); + } + + public void saveIntakeAnswerElement(IntakeAnswerElement intakeAnswerElement) { + genericIntakeNodeDAO.saveIntakeAnswerElement(intakeAnswerElement); + } + + // / + public void updateNodeLabel(IntakeNodeLabel intakeNodeLabel) { + genericIntakeNodeDAO.updateNodeLabel(intakeNodeLabel); + } + + public void updateAgencyIntakeQuick(Integer intakeNodeId) { + Agency agency = Agency.getLocalAgency(); + agency.setIntakeQuick(intakeNodeId); + genericIntakeNodeDAO.updateAgencyIntakeQuick(agency); + } + + public IntakeNodeLabel getIntakeNodeLabel(Integer intakeNodeLabelId) { + return genericIntakeNodeDAO.getIntakeNodeLabel(intakeNodeLabelId); + } + + public IntakeNodeTemplate getIntakeNodeTemplate(Integer intakeNodeTemplateId) { + return genericIntakeNodeDAO.getIntakeNodeTemplate(intakeNodeTemplateId); + } + + public IntakeNode getIntakeNode(Integer nodeId) { + if (nodeId == null) { + throw new IllegalArgumentException( + "Parameter nodeId must be non-null"); + } + + IntakeNode node = genericIntakeNodeDAO.getIntakeNode(nodeId); + + if (!node.isIntake()) { + throw new IllegalStateException("node with id : " + nodeId + + " is not an intake"); + } + + return node; + } + + private String createStatisticLabel(String answerLabel, String answerElement) { + StringBuilder builder = new StringBuilder(); + + builder.append(answerLabel); + + if (builder.length() > 0) { + builder.append(":"); + } + + builder.append(answerElement); + + return builder.toString(); + } + + public List getIntakeNodesByType(Integer formType) { + return genericIntakeDAO.getIntakeNodesByType(formType); + } + + public List> getIntakeListforOcan(Calendar after) { + Map> pairs = new HashMap>(); + + List triads = genericIntakeDAO.getOcanIntakesAfterDate(after); + for (Object[] triad : triads) { + Intake i = (Intake) triad[0]; + IntakeNode n = (IntakeNode) triad[1]; + IntakeNodeLabel l = (IntakeNodeLabel) triad[2]; + String key = l.getLabel().indexOf("Client") > -1 ? "client" : "staff"; + i.setNode(n); + if (!pairs.containsKey(i.getClientId())) { + // new client + Map pair = new HashMap(); + pair.put(key, i); + pairs.put(i.getClientId(), pair); + } else if (!pairs.get(i.getClientId()).containsKey(key)) { + // new key + Map pair = pairs.get(i.getClientId()); + pair.put(key, i); + } + } + + List> list = new ArrayList>(); + + for (Integer clientId : pairs.keySet()) { + Map pair = pairs.get(clientId); + if (pair.size() == 2) { + // need both client and staff + Map entry = new HashMap(); + entry.put("clientId", clientId.toString()); + entry.put("client", toXml(pair, "client")); + entry.put("staff", toXml(pair, "staff")); + list.add(entry); + } + } + + return list; + } + + private String toXml(Map intakeMap, String type) { + StringBuilder xml = new StringBuilder(); + Intake intake = intakeMap.get(type); + if ("client".equals(type)) { + toClientXml(xml, intake, intake.getNode()); + } else { + toStaffXml(xml, intake, intake.getNode()); + } + return xml.toString(); + } + + private void toClientXml(StringBuilder builder, Intake intake, IntakeNode node) { + if (node == null) + return; + IntakeNodeHtmlAdapter htmlAdapter = adapterFactory.getOcanClientXmlAdapter(0, node, intake); + + builder.append(htmlAdapter.getPreBuilder()); + + for (IntakeNode child : node.getChildren()) { + toClientXml(builder, intake, child); + } + + builder.append(htmlAdapter.getPostBuilder()); + } + + private void toStaffXml(StringBuilder builder, Intake intake, IntakeNode node) { + if (node == null) + return; + IntakeNodeHtmlAdapter htmlAdapter = adapterFactory.getOcanStaffXmlAdapter(0, node, intake); + + builder.append(htmlAdapter.getPreBuilder()); + + for (IntakeNode child : node.getChildren()) { + toStaffXml(builder, intake, child); + } + + builder.append(htmlAdapter.getPostBuilder()); + } + + /* + * street health report, not finished yet public List getCohort(Date + * beginDate, Date endDate) { return genericIntakeDAO.getCohort(beginDate, + * endDate, demographicDao.getClients()); } + */ + + + public List getIntakeNodeJavascriptLocation(String questionId) { + if(questionId != null && questionId.length()>0) { + return this.genericIntakeNodeDAO.getIntakeNodeJavascriptLocation(questionId); + } + return null; + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManager.java b/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManager.java index 2d9f296ba5..1f106d463a 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2005, 2009 IBM Corporation and others. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -17,32 +18,21 @@ * * Contributors: * + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.service; - -import org.oscarehr.PMmodule.dao.HealthSafetyDao; -import org.oscarehr.PMmodule.model.HealthSafety; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class HealthSafetyManager { - - private HealthSafetyDao healthSafetyDao=null; - - public HealthSafetyDao getHealthSafetyDao() { - return healthSafetyDao; - } - - public void setHealthSafetyDao(HealthSafetyDao healthSafetyDao) { - this.healthSafetyDao = healthSafetyDao; - } - - public HealthSafety getHealthSafetyByDemographic(Long demographicNo) { - return healthSafetyDao.getHealthSafetyByDemographic(demographicNo); - } + package org.oscarehr.PMmodule.service; - public void saveHealthSafetyByDemographic(HealthSafety healthsafety) { - healthSafetyDao.saveHealthSafetyByDemographic(healthsafety); - } -} + import org.oscarehr.PMmodule.dao.HealthSafetyDao; + import org.oscarehr.PMmodule.model.HealthSafety; + import org.springframework.transaction.annotation.Transactional; + + public interface HealthSafetyManager{ + public HealthSafetyDao getHealthSafetyDao(); + + public void setHealthSafetyDao(HealthSafetyDao healthSafetyDao); + public HealthSafety getHealthSafetyByDemographic(Long demographicNo); + public void saveHealthSafetyByDemographic(HealthSafety healthsafety); + } + \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManagerImpl.java new file mode 100644 index 0000000000..2162ed2133 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/HealthSafetyManagerImpl.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * Copyright (c) 2005, 2009 IBM Corporation and others. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * Contributors: + * + * + * Modifications made by Magenta Health in 2024. + */ + +package org.oscarehr.PMmodule.service; + +import org.oscarehr.PMmodule.dao.HealthSafetyDao; +import org.oscarehr.PMmodule.model.HealthSafety; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class HealthSafetyManagerImpl implements HealthSafetyManager{ + + private HealthSafetyDao healthSafetyDao=null; + + public HealthSafetyDao getHealthSafetyDao() { + return healthSafetyDao; + } + + public void setHealthSafetyDao(HealthSafetyDao healthSafetyDao) { + this.healthSafetyDao = healthSafetyDao; + } + + public HealthSafety getHealthSafetyByDemographic(Long demographicNo) { + return healthSafetyDao.getHealthSafetyByDemographic(demographicNo); + } + + public void saveHealthSafetyByDemographic(HealthSafety healthsafety) { + healthSafetyDao.saveHealthSafetyByDemographic(healthsafety); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProgramManager.java b/src/main/java/org/oscarehr/PMmodule/service/ProgramManager.java index 2446f8eb23..c0d3aed034 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/ProgramManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/ProgramManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,11 +20,11 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; - import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -52,454 +53,183 @@ import org.oscarehr.PMmodule.model.ProgramTeam; import org.oscarehr.PMmodule.model.VacancyTemplate; import org.oscarehr.util.LoggedInInfo; - import oscar.OscarProperties; -public class ProgramManager { - - private ProgramDao programDao; - private ProgramProviderDAO programProviderDAO; - private ProgramFunctionalUserDAO programFunctionalUserDAO; - private ProgramTeamDAO programTeamDAO; - private ProgramAccessDAO programAccessDAO; - private AdmissionDao admissionDao; - private DefaultRoleAccessDAO defaultRoleAccessDAO; - private ProgramClientStatusDAO clientStatusDAO; - private ProgramSignatureDao programSignatureDao; - private VacancyTemplateDao vacancyTemplateDao; - - private boolean enabled; - public boolean getEnabled() { - return enabled; - } +public interface ProgramManager { - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } + boolean getEnabled(); - public ProgramSignatureDao getProgramSignatureDao() { - return programSignatureDao; - } + void setEnabled(boolean enabled); - public void setProgramSignatureDao(ProgramSignatureDao programSignatureDao) { - this.programSignatureDao = programSignatureDao; - } + ProgramSignatureDao getProgramSignatureDao(); - public void setProgramDao(ProgramDao dao) { - this.programDao = dao; - } + void setProgramSignatureDao(ProgramSignatureDao programSignatureDao); - public void setProgramProviderDAO(ProgramProviderDAO dao) { - this.programProviderDAO = dao; - } + void setProgramDao(ProgramDao dao); - public void setProgramFunctionalUserDAO(ProgramFunctionalUserDAO dao) { - this.programFunctionalUserDAO = dao; - } + void setProgramProviderDAO(ProgramProviderDAO dao); - public void setProgramTeamDAO(ProgramTeamDAO dao) { - this.programTeamDAO = dao; - } + void setProgramFunctionalUserDAO(ProgramFunctionalUserDAO dao); - public void setProgramAccessDAO(ProgramAccessDAO dao) { - this.programAccessDAO = dao; - } + void setProgramTeamDAO(ProgramTeamDAO dao); - public void setAdmissionDao(AdmissionDao dao) { - this.admissionDao = dao; - } + void setProgramAccessDAO(ProgramAccessDAO dao); - public void setDefaultRoleAccessDAO(DefaultRoleAccessDAO dao) { - this.defaultRoleAccessDAO = dao; - } + void setAdmissionDao(AdmissionDao dao); - public void setProgramClientStatusDAO(ProgramClientStatusDAO dao) { - this.clientStatusDAO = dao; - } + void setDefaultRoleAccessDAO(DefaultRoleAccessDAO dao); - public Program getProgram(String programId) { - return programDao.getProgram(Integer.valueOf(programId)); - } + void setProgramClientStatusDAO(ProgramClientStatusDAO dao); - public Program getProgram(Integer programId) { - return programDao.getProgram(programId); - } + Program getProgram(String programId); - public Program getProgram(Long programId) { - return programDao.getProgram(new Integer(programId.intValue())); - } + Program getProgram(Integer programId); + + Program getProgram(Long programId); - public List getActiveProgramByFacility(String providerNo, Integer facilityId) { - List programs = new ArrayList(); - for (ProgramProvider programProvider : programProviderDAO.getProgramDomainByFacility(providerNo, facilityId)) { - Program program = this.getProgram(programProvider.getProgramId()); - if (program.isActive()) { - programs.add(program); - } - } - return programs; - } - - public String getProgramName(String programId) { - return programDao.getProgramName(Integer.valueOf(programId)); - } - - public Integer getProgramIdByProgramName(String programName) { - return programDao.getProgramIdByProgramName(programName); - } - - public List getAllPrograms() { - return programDao.getAllPrograms(); - } - - public List getAllPrograms(String programStatus, String type, int facilityId) { - return programDao.getAllPrograms(programStatus, type, facilityId); - } - - /** - * facilityId can be null, it will return all community programs optionally filtering by facility id if filtering is enabled. - */ - public List getCommunityPrograms(Integer facilityId) { - if (OscarProperties.getInstance().getBooleanProperty("FILTER_ON_FACILITY", "true")) { - return programDao.getCommunityProgramsByFacilityId(facilityId); - } - else { - return programDao.getPrograms(); - } - } - - - public List getPrograms(Integer facilityId) { - if (OscarProperties.getInstance().getBooleanProperty("FILTER_ON_FACILITY", "true")) { - return programDao.getProgramsByFacilityId(facilityId); - } - else { - return programDao.getAllPrograms(); - } - } - - public List getPrograms() { - return programDao.getPrograms(); - } - - public Program[] getBedPrograms() { - return programDao.getProgramsByType(null, Program.BED_TYPE, null).toArray(new Program[0]); - } - - public Program[] getBedPrograms(Integer facilityId) { - return programDao.getProgramsByType(facilityId, Program.BED_TYPE, null).toArray(new Program[0]); - } - - public List getServicePrograms() { - return programDao.getProgramsByType(null, Program.SERVICE_TYPE, null); - } - - public Program[] getExternalPrograms() { - return programDao.getProgramsByType(null, Program.EXTERNAL_TYPE, true).toArray(new Program[0]); - } - - public boolean isBedProgram(String programId) { - return programDao.isBedProgram(Integer.valueOf(programId)); - } - - public boolean isServiceProgram(String programId) { - return programDao.isServiceProgram(Integer.valueOf(programId)); - } - - public boolean isCommunityProgram(String programId) { - return programDao.isCommunityProgram(Integer.valueOf(programId)); - } - - public void saveProgram(Program program) { - if (program.getHoldingTank()) { - programDao.resetHoldingTank(); - } - programDao.saveProgram(program); - } - - public void removeProgram(String programId) { - programDao.removeProgram(Integer.valueOf(programId)); - } - - public List getProgramProviders(String programId) { - return programProviderDAO.getProgramProviders(Long.valueOf(programId)); - } - - public List getProgramProvidersByProvider(String providerNo) { - return programProviderDAO.getProgramProvidersByProvider(providerNo); - } - - public ProgramProvider getProgramProvider(String id) { - return programProviderDAO.getProgramProvider(Long.valueOf(id)); - } - - public ProgramProvider getProgramProvider(String providerNo, String programId) { - return programProviderDAO.getProgramProvider(providerNo, Long.valueOf(programId)); - } - - public void saveProgramProvider(ProgramProvider pp) { - programProviderDAO.saveProgramProvider(pp); - } - - public void deleteProgramProvider(String id) { - programProviderDAO.deleteProgramProvider(Long.valueOf(id)); - } - - public void deleteProgramProviderByProgramId(Long programId) { - programProviderDAO.deleteProgramProviderByProgramId(programId); - } - - public List getFunctionalUserTypes() { - return programFunctionalUserDAO.getFunctionalUserTypes(); - } - - public FunctionalUserType getFunctionalUserType(String id) { - return programFunctionalUserDAO.getFunctionalUserType(Long.valueOf(id)); - } - - public void saveFunctionalUserType(FunctionalUserType fut) { - programFunctionalUserDAO.saveFunctionalUserType(fut); - } - - public void deleteFunctionalUserType(String id) { - programFunctionalUserDAO.deleteFunctionalUserType(Long.valueOf(id)); - } - - public List getFunctionalUsers(String programId) { - return programFunctionalUserDAO.getFunctionalUsers(Long.valueOf(programId)); - } - - public ProgramFunctionalUser getFunctionalUser(String id) { - return programFunctionalUserDAO.getFunctionalUser(Long.valueOf(id)); - } - - public void saveFunctionalUser(ProgramFunctionalUser pfu) { - programFunctionalUserDAO.saveFunctionalUser(pfu); - } + List getActiveProgramByFacility(String providerNo, Integer facilityId); + + String getProgramName(String programId); + + Integer getProgramIdByProgramName(String programName); + + List getAllPrograms(); + + List getAllPrograms(String programStatus, String type, int facilityId); + + List getCommunityPrograms(Integer facilityId); + + List getPrograms(Integer facilityId); + + List getPrograms(); + + Program[] getBedPrograms(); + + Program[] getBedPrograms(Integer facilityId); + + List getServicePrograms(); + + Program[] getExternalPrograms(); + + boolean isBedProgram(String programId); + + boolean isServiceProgram(String programId); + + boolean isCommunityProgram(String programId); + + void saveProgram(Program program); + + void removeProgram(String programId); + + List getProgramProviders(String programId); + + List getProgramProvidersByProvider(String providerNo); + + ProgramProvider getProgramProvider(String id); + + ProgramProvider getProgramProvider(String providerNo, String programId); + + void saveProgramProvider(ProgramProvider pp); + + void deleteProgramProvider(String id); + + void deleteProgramProviderByProgramId(Long programId); + + List getFunctionalUserTypes(); + + FunctionalUserType getFunctionalUserType(String id); + + void saveFunctionalUserType(FunctionalUserType fut); + + void deleteFunctionalUserType(String id); + + List getFunctionalUsers(String programId); + + ProgramFunctionalUser getFunctionalUser(String id); + + void saveFunctionalUser(ProgramFunctionalUser pfu); + + void deleteFunctionalUser(String id); - public void deleteFunctionalUser(String id) { - programFunctionalUserDAO.deleteFunctionalUser(Long.valueOf(id)); - } + Long getFunctionalUserByUserType(Long programId, Long userTypeId); - public Long getFunctionalUserByUserType(Long programId, Long userTypeId) { - return programFunctionalUserDAO.getFunctionalUserByUserType(programId, userTypeId); - } + List getProgramTeams(String programId); - public List getProgramTeams(String programId) { - return programTeamDAO.getProgramTeams(Integer.valueOf(programId)); - } + ProgramTeam getProgramTeam(String id); - public ProgramTeam getProgramTeam(String id) { - return programTeamDAO.getProgramTeam(Integer.valueOf(id)); - } - - public void saveProgramTeam(ProgramTeam team) { - programTeamDAO.saveProgramTeam(team); - } - - public void deleteProgramTeam(String id) { - programTeamDAO.deleteProgramTeam(Integer.valueOf(id)); - } - - public boolean teamNameExists(Integer programId, String teamName) { - return programTeamDAO.teamNameExists(programId, teamName); - } - - public List getProgramAccesses(String programId) { - return programAccessDAO.getAccessListByProgramId(Long.valueOf(programId)); - } - - public ProgramAccess getProgramAccess(String id) { - return programAccessDAO.getProgramAccess(Long.valueOf(id)); - } - - public void saveProgramAccess(ProgramAccess pa) { - programAccessDAO.saveProgramAccess(pa); - } - - public void deleteProgramAccess(String id) { - programAccessDAO.deleteProgramAccess(Long.valueOf(id)); - } - - public List getAccessTypes() { - return programAccessDAO.getAccessTypes(); - } - - public AccessType getAccessType(Long id) { - return programAccessDAO.getAccessType(id); - } - - public List getAllProvidersInTeam(Integer programId, Integer teamId) { - return this.programProviderDAO.getProgramProvidersInTeam(programId, teamId); - } - - public List getAllClientsInTeam(Integer programId, Integer teamId) { - return admissionDao.getAdmissionsInTeam(programId, teamId); - } - - public List search(Program criteria) { - return this.programDao.search(criteria); - } - - public List searchByFacility(Program criteria, Integer facilityId){ - return this.programDao.searchByFacility(criteria, facilityId); - } - - public Program getHoldingTankProgram() { - return this.programDao.getHoldingTankProgram(); - } - - public ProgramAccess getProgramAccess(String programId, String accessTypeId) { - return this.programAccessDAO.getProgramAccess(Long.valueOf(programId), Long.valueOf(accessTypeId)); - } - - public List getProgramDomain(String providerNo) { - List programDomain = new ArrayList(); - - for (Iterator i = programProviderDAO.getProgramDomain(providerNo).iterator(); i.hasNext();) { - ProgramProvider programProvider = (ProgramProvider) i.next(); - Program p = getProgram(programProvider.getProgramId()); - if(p != null) - programDomain.add(p); - } - - return programDomain; - } - - - public List getActiveProgramDomain(String providerNo) { - List programDomain = new ArrayList(); - - for (Iterator i = programProviderDAO.getActiveProgramDomain(providerNo).iterator(); i.hasNext();) { - ProgramProvider programProvider = (ProgramProvider) i.next(); - Program p = getProgram(programProvider.getProgramId()); - if(p!=null) - programDomain.add(p); - } - - return programDomain; - } - - public List getProgramDomainInCurrentFacilityForCurrentProvider(LoggedInInfo loggedInInfo, boolean activeOnly) { - List programs = null; - - if (activeOnly) programs=getActiveProgramDomain(loggedInInfo.getLoggedInProviderNo()); - else programs=getProgramDomain(loggedInInfo.getLoggedInProviderNo()); - - List results = new ArrayList(); - for(Program program : programs) { - if(program.getFacilityId()==loggedInInfo.getCurrentFacility().getId().intValue()) { - results.add(program); - } - } - return results; - } - - public Program[] getCommunityPrograms() { - return programDao.getProgramsByType(null, Program.COMMUNITY_TYPE, null).toArray(new Program[0]); - } - - public List getProgramBeans(String providerNo) { - if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); - ArrayList pList = new ArrayList(); - List programs = programDao.getProgramsByType(null, Program.COMMUNITY_TYPE, null); - for (Program program : programs) { - pList.add(new LabelValueBean(program.getName(), program.getId().toString())); - } - return pList; - /* - * Iterator iter = programProviderDAOT.getProgramProvidersByProvider(new Long(providerNo)).iterator(); ArrayList pList = new ArrayList(); while (iter.hasNext()) { ProgramProvider p = (ProgramProvider) iter.next(); if (p!=null && p.getProgramId() != - * null && p.getProgramId().longValue()>0){ //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); Program program = programDao.getProgram(new Integer(p.getProgramId().intValue())); - * pList.add(new LabelValueBean(program.getName(),program.getId().toString())); } } return pList; - */ - } - - public List getDefaultRoleAccesses() { - return defaultRoleAccessDAO.getDefaultRoleAccesses(); - } - - public DefaultRoleAccess getDefaultRoleAccess(String id) { - return defaultRoleAccessDAO.getDefaultRoleAccess(Long.valueOf(id)); - } - - public void saveDefaultRoleAccess(DefaultRoleAccess dra) { - defaultRoleAccessDAO.saveDefaultRoleAccess(dra); - } - - public void deleteDefaultRoleAccess(String id) { - defaultRoleAccessDAO.deleteDefaultRoleAccess(Long.valueOf(id)); - } - - public DefaultRoleAccess findDefaultRoleAccess(long roleId, long accessTypeId) { - return defaultRoleAccessDAO.find(new Long(roleId), new Long(accessTypeId)); - } - - public List getProgramClientStatuses(Integer programId) { - return clientStatusDAO.getProgramClientStatuses(programId); - } - - public void saveProgramClientStatus(ProgramClientStatus status) { - clientStatusDAO.saveProgramClientStatus(status); - } - - public void deleteProgramClientStatus(String id) { - clientStatusDAO.deleteProgramClientStatus(id); - } - - public boolean clientStatusNameExists(Integer programId, String statusName) { - return clientStatusDAO.clientStatusNameExists(programId, statusName); - } - - public List getAllClientsInStatus(Integer programId, Integer statusId) { - return clientStatusDAO.getAllClientsInStatus(programId, statusId); - } - - public ProgramClientStatus getProgramClientStatus(String statusId) { - return clientStatusDAO.getProgramClientStatus(statusId); - } - - public ProgramSignature getProgramFirstSignature(Integer programId) { - return programSignatureDao.getProgramFirstSignature(programId); - } - - public List getProgramSignatures(Integer programId) { - return programSignatureDao.getProgramSignatures(programId); - } - - public void saveProgramSignature(ProgramSignature programSignature) { - programSignatureDao.saveProgramSignature(programSignature); - } + void saveProgramTeam(ProgramTeam team); + + void deleteProgramTeam(String id); + + boolean teamNameExists(Integer programId, String teamName); + + List getProgramAccesses(String programId); + + ProgramAccess getProgramAccess(String id); + + void saveProgramAccess(ProgramAccess pa); + + void deleteProgramAccess(String id); + + List getAccessTypes(); + + AccessType getAccessType(Long id); + + List getAllProvidersInTeam(Integer programId, Integer teamId); + + List getAllClientsInTeam(Integer programId, Integer teamId); + + List search(Program criteria); + + List searchByFacility(Program criteria, Integer facilityId); + + Program getHoldingTankProgram(); + + ProgramAccess getProgramAccess(String programId, String accessTypeId); + + List getProgramDomain(String providerNo); + + List getActiveProgramDomain(String providerNo); + + List getProgramDomainInCurrentFacilityForCurrentProvider(LoggedInInfo loggedInInfo, boolean activeOnly); + + Program[] getCommunityPrograms(); + + List getProgramBeans(String providerNo); + + List getDefaultRoleAccesses(); + + DefaultRoleAccess getDefaultRoleAccess(String id); + + void saveDefaultRoleAccess(DefaultRoleAccess dra); + + void deleteDefaultRoleAccess(String id); + + DefaultRoleAccess findDefaultRoleAccess(long roleId, long accessTypeId); + + List getProgramClientStatuses(Integer programId); + + void saveProgramClientStatus(ProgramClientStatus status); + + void deleteProgramClientStatus(String id); + + boolean clientStatusNameExists(Integer programId, String statusName); + + List getAllClientsInStatus(Integer programId, Integer statusId); + + ProgramClientStatus getProgramClientStatus(String statusId); + + ProgramSignature getProgramFirstSignature(Integer programId); + + List getProgramSignatures(Integer programId); + + void saveProgramSignature(ProgramSignature programSignature); - public VacancyTemplate getVacancyTemplate(Integer templateId) { - return vacancyTemplateDao.getVacancyTemplate(templateId); - } - - public void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao) { - this.vacancyTemplateDao = vacancyTemplateDao; - } - - public boolean hasAccessBasedOnCurrentFacility(LoggedInInfo loggedInInfo, Integer programId) { - // if no program restrictions are defined. - if (programId == null) return(true); - - // check the providers facilities against the programs facilities - Program program = getProgram(programId); - if(program!=null) { - return(program.getFacilityId() == loggedInInfo.getCurrentFacility().getId().intValue()); - } else { - return false; - } - } - - public List getAllProgramsByRole(String providerNo,int roleId) { - List results = new ArrayList(); - List ppList = programProviderDAO.getProgramProvidersByProvider(providerNo); - for(ProgramProvider pp:ppList) { - if(pp.getRoleId().intValue() == roleId) { - Program p = programDao.getProgram(pp.getProgramId().intValue()); - results.add(p); - } - } - return results; - } + VacancyTemplate getVacancyTemplate(Integer templateId); + + void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao); + + boolean hasAccessBasedOnCurrentFacility(LoggedInInfo loggedInInfo, Integer programId); + + List getAllProgramsByRole(String providerNo,int roleId); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProgramManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/ProgramManagerImpl.java new file mode 100644 index 0000000000..325f4ae39b --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/ProgramManagerImpl.java @@ -0,0 +1,508 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ + + package org.oscarehr.PMmodule.service; + + + import java.util.ArrayList; + import java.util.Iterator; + import java.util.List; + + import org.apache.struts.util.LabelValueBean; + import org.oscarehr.common.dao.AdmissionDao; + import org.oscarehr.PMmodule.dao.DefaultRoleAccessDAO; + import org.oscarehr.PMmodule.dao.ProgramAccessDAO; + import org.oscarehr.PMmodule.dao.ProgramClientStatusDAO; + import org.oscarehr.PMmodule.dao.ProgramDao; + import org.oscarehr.PMmodule.dao.ProgramFunctionalUserDAO; + import org.oscarehr.PMmodule.dao.ProgramProviderDAO; + import org.oscarehr.PMmodule.dao.ProgramSignatureDao; + import org.oscarehr.PMmodule.dao.ProgramTeamDAO; + import org.oscarehr.PMmodule.dao.VacancyTemplateDao; + import org.oscarehr.PMmodule.model.AccessType; + import org.oscarehr.common.model.Admission; + import org.oscarehr.PMmodule.model.DefaultRoleAccess; + import org.oscarehr.PMmodule.model.FunctionalUserType; + import org.oscarehr.PMmodule.model.Program; + import org.oscarehr.PMmodule.model.ProgramAccess; + import org.oscarehr.PMmodule.model.ProgramClientStatus; + import org.oscarehr.PMmodule.model.ProgramFunctionalUser; + import org.oscarehr.PMmodule.model.ProgramProvider; + import org.oscarehr.PMmodule.model.ProgramSignature; + import org.oscarehr.PMmodule.model.ProgramTeam; + import org.oscarehr.PMmodule.model.VacancyTemplate; + import org.oscarehr.util.LoggedInInfo; + + import oscar.OscarProperties; + public class ProgramManagerImpl implements ProgramManager{ + + private ProgramDao programDao; + private ProgramProviderDAO programProviderDAO; + private ProgramFunctionalUserDAO programFunctionalUserDAO; + private ProgramTeamDAO programTeamDAO; + private ProgramAccessDAO programAccessDAO; + private AdmissionDao admissionDao; + private DefaultRoleAccessDAO defaultRoleAccessDAO; + private ProgramClientStatusDAO clientStatusDAO; + private ProgramSignatureDao programSignatureDao; + private VacancyTemplateDao vacancyTemplateDao; + + private boolean enabled; + + public boolean getEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public ProgramSignatureDao getProgramSignatureDao() { + return programSignatureDao; + } + + public void setProgramSignatureDao(ProgramSignatureDao programSignatureDao) { + this.programSignatureDao = programSignatureDao; + } + + public void setProgramDao(ProgramDao dao) { + this.programDao = dao; + } + + public void setProgramProviderDAO(ProgramProviderDAO dao) { + this.programProviderDAO = dao; + } + + public void setProgramFunctionalUserDAO(ProgramFunctionalUserDAO dao) { + this.programFunctionalUserDAO = dao; + } + + public void setProgramTeamDAO(ProgramTeamDAO dao) { + this.programTeamDAO = dao; + } + + public void setProgramAccessDAO(ProgramAccessDAO dao) { + this.programAccessDAO = dao; + } + + public void setAdmissionDao(AdmissionDao dao) { + this.admissionDao = dao; + } + + public void setDefaultRoleAccessDAO(DefaultRoleAccessDAO dao) { + this.defaultRoleAccessDAO = dao; + } + + public void setProgramClientStatusDAO(ProgramClientStatusDAO dao) { + this.clientStatusDAO = dao; + } + + public Program getProgram(String programId) { + return programDao.getProgram(Integer.valueOf(programId)); + } + + public Program getProgram(Integer programId) { + return programDao.getProgram(programId); + } + + public Program getProgram(Long programId) { + return programDao.getProgram(new Integer(programId.intValue())); + } + + public List getActiveProgramByFacility(String providerNo, Integer facilityId) { + List programs = new ArrayList(); + for (ProgramProvider programProvider : programProviderDAO.getProgramDomainByFacility(providerNo, facilityId)) { + Program program = this.getProgram(programProvider.getProgramId()); + if (program.isActive()) { + programs.add(program); + } + } + return programs; + } + + public String getProgramName(String programId) { + return programDao.getProgramName(Integer.valueOf(programId)); + } + + public Integer getProgramIdByProgramName(String programName) { + return programDao.getProgramIdByProgramName(programName); + } + + public List getAllPrograms() { + return programDao.getAllPrograms(); + } + + public List getAllPrograms(String programStatus, String type, int facilityId) { + return programDao.getAllPrograms(programStatus, type, facilityId); + } + + /** + * facilityId can be null, it will return all community programs optionally filtering by facility id if filtering is enabled. + */ + public List getCommunityPrograms(Integer facilityId) { + if (OscarProperties.getInstance().getBooleanProperty("FILTER_ON_FACILITY", "true")) { + return programDao.getCommunityProgramsByFacilityId(facilityId); + } + else { + return programDao.getPrograms(); + } + } + + + public List getPrograms(Integer facilityId) { + if (OscarProperties.getInstance().getBooleanProperty("FILTER_ON_FACILITY", "true")) { + return programDao.getProgramsByFacilityId(facilityId); + } + else { + return programDao.getAllPrograms(); + } + } + + public List getPrograms() { + return programDao.getPrograms(); + } + + public Program[] getBedPrograms() { + return programDao.getProgramsByType(null, Program.BED_TYPE, null).toArray(new Program[0]); + } + + public Program[] getBedPrograms(Integer facilityId) { + return programDao.getProgramsByType(facilityId, Program.BED_TYPE, null).toArray(new Program[0]); + } + + public List getServicePrograms() { + return programDao.getProgramsByType(null, Program.SERVICE_TYPE, null); + } + + public Program[] getExternalPrograms() { + return programDao.getProgramsByType(null, Program.EXTERNAL_TYPE, true).toArray(new Program[0]); + } + + public boolean isBedProgram(String programId) { + return programDao.isBedProgram(Integer.valueOf(programId)); + } + + public boolean isServiceProgram(String programId) { + return programDao.isServiceProgram(Integer.valueOf(programId)); + } + + public boolean isCommunityProgram(String programId) { + return programDao.isCommunityProgram(Integer.valueOf(programId)); + } + + public void saveProgram(Program program) { + if (program.getHoldingTank()) { + programDao.resetHoldingTank(); + } + programDao.saveProgram(program); + } + + public void removeProgram(String programId) { + programDao.removeProgram(Integer.valueOf(programId)); + } + + public List getProgramProviders(String programId) { + return programProviderDAO.getProgramProviders(Long.valueOf(programId)); + } + + public List getProgramProvidersByProvider(String providerNo) { + return programProviderDAO.getProgramProvidersByProvider(providerNo); + } + + public ProgramProvider getProgramProvider(String id) { + return programProviderDAO.getProgramProvider(Long.valueOf(id)); + } + + public ProgramProvider getProgramProvider(String providerNo, String programId) { + return programProviderDAO.getProgramProvider(providerNo, Long.valueOf(programId)); + } + + public void saveProgramProvider(ProgramProvider pp) { + programProviderDAO.saveProgramProvider(pp); + } + + public void deleteProgramProvider(String id) { + programProviderDAO.deleteProgramProvider(Long.valueOf(id)); + } + + public void deleteProgramProviderByProgramId(Long programId) { + programProviderDAO.deleteProgramProviderByProgramId(programId); + } + + public List getFunctionalUserTypes() { + return programFunctionalUserDAO.getFunctionalUserTypes(); + } + + public FunctionalUserType getFunctionalUserType(String id) { + return programFunctionalUserDAO.getFunctionalUserType(Long.valueOf(id)); + } + + public void saveFunctionalUserType(FunctionalUserType fut) { + programFunctionalUserDAO.saveFunctionalUserType(fut); + } + + public void deleteFunctionalUserType(String id) { + programFunctionalUserDAO.deleteFunctionalUserType(Long.valueOf(id)); + } + + public List getFunctionalUsers(String programId) { + return programFunctionalUserDAO.getFunctionalUsers(Long.valueOf(programId)); + } + + public ProgramFunctionalUser getFunctionalUser(String id) { + return programFunctionalUserDAO.getFunctionalUser(Long.valueOf(id)); + } + + public void saveFunctionalUser(ProgramFunctionalUser pfu) { + programFunctionalUserDAO.saveFunctionalUser(pfu); + } + + public void deleteFunctionalUser(String id) { + programFunctionalUserDAO.deleteFunctionalUser(Long.valueOf(id)); + } + + public Long getFunctionalUserByUserType(Long programId, Long userTypeId) { + return programFunctionalUserDAO.getFunctionalUserByUserType(programId, userTypeId); + } + + public List getProgramTeams(String programId) { + return programTeamDAO.getProgramTeams(Integer.valueOf(programId)); + } + + public ProgramTeam getProgramTeam(String id) { + return programTeamDAO.getProgramTeam(Integer.valueOf(id)); + } + + public void saveProgramTeam(ProgramTeam team) { + programTeamDAO.saveProgramTeam(team); + } + + public void deleteProgramTeam(String id) { + programTeamDAO.deleteProgramTeam(Integer.valueOf(id)); + } + + public boolean teamNameExists(Integer programId, String teamName) { + return programTeamDAO.teamNameExists(programId, teamName); + } + + public List getProgramAccesses(String programId) { + return programAccessDAO.getAccessListByProgramId(Long.valueOf(programId)); + } + + public ProgramAccess getProgramAccess(String id) { + return programAccessDAO.getProgramAccess(Long.valueOf(id)); + } + + public void saveProgramAccess(ProgramAccess pa) { + programAccessDAO.saveProgramAccess(pa); + } + + public void deleteProgramAccess(String id) { + programAccessDAO.deleteProgramAccess(Long.valueOf(id)); + } + + public List getAccessTypes() { + return programAccessDAO.getAccessTypes(); + } + + public AccessType getAccessType(Long id) { + return programAccessDAO.getAccessType(id); + } + + public List getAllProvidersInTeam(Integer programId, Integer teamId) { + return this.programProviderDAO.getProgramProvidersInTeam(programId, teamId); + } + + public List getAllClientsInTeam(Integer programId, Integer teamId) { + return admissionDao.getAdmissionsInTeam(programId, teamId); + } + + public List search(Program criteria) { + return this.programDao.search(criteria); + } + + public List searchByFacility(Program criteria, Integer facilityId){ + return this.programDao.searchByFacility(criteria, facilityId); + } + + public Program getHoldingTankProgram() { + return this.programDao.getHoldingTankProgram(); + } + + public ProgramAccess getProgramAccess(String programId, String accessTypeId) { + return this.programAccessDAO.getProgramAccess(Long.valueOf(programId), Long.valueOf(accessTypeId)); + } + + public List getProgramDomain(String providerNo) { + List programDomain = new ArrayList(); + + for (Iterator i = programProviderDAO.getProgramDomain(providerNo).iterator(); i.hasNext();) { + ProgramProvider programProvider = (ProgramProvider) i.next(); + Program p = getProgram(programProvider.getProgramId()); + if(p != null) + programDomain.add(p); + } + + return programDomain; + } + + + public List getActiveProgramDomain(String providerNo) { + List programDomain = new ArrayList(); + + for (Iterator i = programProviderDAO.getActiveProgramDomain(providerNo).iterator(); i.hasNext();) { + ProgramProvider programProvider = (ProgramProvider) i.next(); + Program p = getProgram(programProvider.getProgramId()); + if(p!=null) + programDomain.add(p); + } + + return programDomain; + } + + public List getProgramDomainInCurrentFacilityForCurrentProvider(LoggedInInfo loggedInInfo, boolean activeOnly) { + List programs = null; + + if (activeOnly) programs=getActiveProgramDomain(loggedInInfo.getLoggedInProviderNo()); + else programs=getProgramDomain(loggedInInfo.getLoggedInProviderNo()); + + List results = new ArrayList(); + for(Program program : programs) { + if(program.getFacilityId()==loggedInInfo.getCurrentFacility().getId().intValue()) { + results.add(program); + } + } + return results; + } + + public Program[] getCommunityPrograms() { + return programDao.getProgramsByType(null, Program.COMMUNITY_TYPE, null).toArray(new Program[0]); + } + + public List getProgramBeans(String providerNo) { + if (providerNo == null || "".equalsIgnoreCase(providerNo.trim())) return new ArrayList(); + ArrayList pList = new ArrayList(); + List programs = programDao.getProgramsByType(null, Program.COMMUNITY_TYPE, null); + for (Program program : programs) { + pList.add(new LabelValueBean(program.getName(), program.getId().toString())); + } + return pList; + /* + * Iterator iter = programProviderDAOT.getProgramProvidersByProvider(new Long(providerNo)).iterator(); ArrayList pList = new ArrayList(); while (iter.hasNext()) { ProgramProvider p = (ProgramProvider) iter.next(); if (p!=null && p.getProgramId() != + * null && p.getProgramId().longValue()>0){ //logger.debug("programName="+p.getProgram().getName()+"::"+"programId="+p.getProgram().getId().toString()); Program program = programDao.getProgram(new Integer(p.getProgramId().intValue())); + * pList.add(new LabelValueBean(program.getName(),program.getId().toString())); } } return pList; + */ + } + + public List getDefaultRoleAccesses() { + return defaultRoleAccessDAO.getDefaultRoleAccesses(); + } + + public DefaultRoleAccess getDefaultRoleAccess(String id) { + return defaultRoleAccessDAO.getDefaultRoleAccess(Long.valueOf(id)); + } + + public void saveDefaultRoleAccess(DefaultRoleAccess dra) { + defaultRoleAccessDAO.saveDefaultRoleAccess(dra); + } + + public void deleteDefaultRoleAccess(String id) { + defaultRoleAccessDAO.deleteDefaultRoleAccess(Long.valueOf(id)); + } + + public DefaultRoleAccess findDefaultRoleAccess(long roleId, long accessTypeId) { + return defaultRoleAccessDAO.find(new Long(roleId), new Long(accessTypeId)); + } + + public List getProgramClientStatuses(Integer programId) { + return clientStatusDAO.getProgramClientStatuses(programId); + } + + public void saveProgramClientStatus(ProgramClientStatus status) { + clientStatusDAO.saveProgramClientStatus(status); + } + + public void deleteProgramClientStatus(String id) { + clientStatusDAO.deleteProgramClientStatus(id); + } + + public boolean clientStatusNameExists(Integer programId, String statusName) { + return clientStatusDAO.clientStatusNameExists(programId, statusName); + } + + public List getAllClientsInStatus(Integer programId, Integer statusId) { + return clientStatusDAO.getAllClientsInStatus(programId, statusId); + } + + public ProgramClientStatus getProgramClientStatus(String statusId) { + return clientStatusDAO.getProgramClientStatus(statusId); + } + + public ProgramSignature getProgramFirstSignature(Integer programId) { + return programSignatureDao.getProgramFirstSignature(programId); + } + + public List getProgramSignatures(Integer programId) { + return programSignatureDao.getProgramSignatures(programId); + } + + public void saveProgramSignature(ProgramSignature programSignature) { + programSignatureDao.saveProgramSignature(programSignature); + } + + public VacancyTemplate getVacancyTemplate(Integer templateId) { + return vacancyTemplateDao.getVacancyTemplate(templateId); + } + + public void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao) { + this.vacancyTemplateDao = vacancyTemplateDao; + } + + public boolean hasAccessBasedOnCurrentFacility(LoggedInInfo loggedInInfo, Integer programId) { + // if no program restrictions are defined. + if (programId == null) return(true); + + // check the providers facilities against the programs facilities + Program program = getProgram(programId); + if(program!=null) { + return(program.getFacilityId() == loggedInInfo.getCurrentFacility().getId().intValue()); + } else { + return false; + } + } + + public List getAllProgramsByRole(String providerNo,int roleId) { + List results = new ArrayList(); + List ppList = programProviderDAO.getProgramProvidersByProvider(providerNo); + for(ProgramProvider pp:ppList) { + if(pp.getRoleId().intValue() == roleId) { + Program p = programDao.getProgram(pp.getProgramId().intValue()); + results.add(p); + } + } + return results; + } + } \ No newline at end of file diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManager.java b/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManager.java index d6d391eaf1..8ea5ce512a 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; import java.util.ArrayList; @@ -37,84 +39,15 @@ import org.oscarehr.PMmodule.model.VacancyTemplate; import org.springframework.transaction.annotation.Transactional; -@Transactional -public class ProgramQueueManager -{ - private ProgramQueueDao dao; - private ClientReferralDAO referralDAO; - private VacancyTemplateDao vacancyTemplateDao; - private VacancyDao vacancyDao; - - public void setVacancyDao(VacancyDao vacancyDao) { - this.vacancyDao = vacancyDao; - } - - public void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao) { - this.vacancyTemplateDao = vacancyTemplateDao; - } - public void setProgramQueueDao(ProgramQueueDao dao) { - this.dao = dao; - } - - public void setClientReferralDAO(ClientReferralDAO dao) { - this.referralDAO = dao; - } - - public ProgramQueue getProgramQueue(String queueId) - { - ProgramQueue pq = dao.getProgramQueue(Long.valueOf(queueId)); - return pq; - } - - public List getProgramQueuesByProgramId(Long programId) { - return dao.getProgramQueuesByProgramId(programId); - } - - public void saveProgramQueue(ProgramQueue programQueue) { - dao.saveProgramQueue(programQueue); - } - - public List getActiveProgramQueuesByProgramId(Long programId) { - List queue = dao.getActiveProgramQueuesByProgramId(programId); - List q = new ArrayList(); - //Get vacancy name and vacancy template name. - for(ProgramQueue pq : queue) { - if(pq.getReferralId()!=null) { - ClientReferral ref = referralDAO.getClientReferral(pq.getReferralId()); - if(ref.getSelectVacancy()!=null) { - pq.setVacancyName(ref.getSelectVacancy()==null?"":ref.getSelectVacancy()); - Vacancy vacancy = vacancyDao.getVacancyById(ref.getVacancyId()==null?0:ref.getVacancyId()); - if(vacancy!=null) { - VacancyTemplate vt = vacancyTemplateDao.getVacancyTemplate(vacancy.getTemplateId()==null?0:vacancy.getTemplateId()); - pq.setVacancyTemplateName(vt!=null?vt.getName():""); - } - - } - } - q.add(pq); - } - return q; - } - - public ProgramQueue getActiveProgramQueue(String programId, String demographicNo) { - return dao.getActiveProgramQueue(Long.valueOf(programId), Long.valueOf(demographicNo)); - } - - public void rejectQueue(String programId, String clientId,String notes, String rejectionReason) { - ProgramQueue queue = getActiveProgramQueue(programId,clientId); - if(queue==null) { - return; - } - ClientReferral referral = this.referralDAO.getClientReferral(queue.getReferralId()); - if(referral != null) { - referral.setStatus(ClientReferral.STATUS_REJECTED); - referral.setCompletionDate(new Date()); - referral.setCompletionNotes(notes); - referral.setRadioRejectionReason(rejectionReason); - this.referralDAO.saveClientReferral(referral); - } - queue.setStatus(ProgramQueue.STATUS_REJECTED); - - this.saveProgramQueue(queue); - } +public interface ProgramQueueManager { + void setVacancyDao(VacancyDao vacancyDao); + void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao); + void setProgramQueueDao(ProgramQueueDao dao); + void setClientReferralDAO(ClientReferralDAO dao); + ProgramQueue getProgramQueue(String queueId); + List getProgramQueuesByProgramId(Long programId); + void saveProgramQueue(ProgramQueue programQueue); + List getActiveProgramQueuesByProgramId(Long programId); + ProgramQueue getActiveProgramQueue(String programId, String demographicNo); + void rejectQueue(String programId, String clientId,String notes, String rejectionReason); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManagerImpl.java new file mode 100644 index 0000000000..b279fa51d8 --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/ProgramQueueManagerImpl.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.service; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.oscarehr.PMmodule.dao.ClientReferralDAO; +import org.oscarehr.PMmodule.dao.ProgramQueueDao; +import org.oscarehr.PMmodule.dao.VacancyDao; +import org.oscarehr.PMmodule.dao.VacancyTemplateDao; +import org.oscarehr.PMmodule.model.ClientReferral; +import org.oscarehr.PMmodule.model.ProgramQueue; +import org.oscarehr.PMmodule.model.Vacancy; +import org.oscarehr.PMmodule.model.VacancyTemplate; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class ProgramQueueManagerImpl implements ProgramQueueManager +{ + private ProgramQueueDao dao; + private ClientReferralDAO referralDAO; + private VacancyTemplateDao vacancyTemplateDao; + private VacancyDao vacancyDao; + + public void setVacancyDao(VacancyDao vacancyDao) { + this.vacancyDao = vacancyDao; + } + + public void setVacancyTemplateDao(VacancyTemplateDao vacancyTemplateDao) { + this.vacancyTemplateDao = vacancyTemplateDao; + } + + public void setProgramQueueDao(ProgramQueueDao dao) { + this.dao = dao; + } + + public void setClientReferralDAO(ClientReferralDAO dao) { + this.referralDAO = dao; + } + + public ProgramQueue getProgramQueue(String queueId) { + ProgramQueue pq = dao.getProgramQueue(Long.valueOf(queueId)); + return pq; + } + + public List getProgramQueuesByProgramId(Long programId) { + return dao.getProgramQueuesByProgramId(programId); + } + + public void saveProgramQueue(ProgramQueue programQueue) { + dao.saveProgramQueue(programQueue); + } + + public List getActiveProgramQueuesByProgramId(Long programId) { + List queue = dao.getActiveProgramQueuesByProgramId(programId); + List q = new ArrayList(); + //Get vacancy name and vacancy template name. + for(ProgramQueue pq : queue) { + if(pq.getReferralId()!=null) { + ClientReferral ref = referralDAO.getClientReferral(pq.getReferralId()); + if(ref.getSelectVacancy()!=null) { + pq.setVacancyName(ref.getSelectVacancy()==null?"":ref.getSelectVacancy()); + Vacancy vacancy = vacancyDao.getVacancyById(ref.getVacancyId()==null?0:ref.getVacancyId()); + if(vacancy!=null) { + VacancyTemplate vt = vacancyTemplateDao.getVacancyTemplate(vacancy.getTemplateId()==null?0:vacancy.getTemplateId()); + pq.setVacancyTemplateName(vt!=null?vt.getName():""); + } + + } + } + q.add(pq); + } + return q; + } + + public ProgramQueue getActiveProgramQueue(String programId, String demographicNo) { + return dao.getActiveProgramQueue(Long.valueOf(programId), Long.valueOf(demographicNo)); + } + + public void rejectQueue(String programId, String clientId,String notes, String rejectionReason) { + ProgramQueue queue = getActiveProgramQueue(programId,clientId); + if(queue==null) { + return; + } + ClientReferral referral = this.referralDAO.getClientReferral(queue.getReferralId()); + if(referral != null) { + referral.setStatus(ClientReferral.STATUS_REJECTED); + referral.setCompletionDate(new Date()); + referral.setCompletionNotes(notes); + referral.setRadioRejectionReason(rejectionReason); + this.referralDAO.saveClientReferral(referral); + } + queue.setStatus(ProgramQueue.STATUS_REJECTED); + + this.saveProgramQueue(queue); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProviderManager.java b/src/main/java/org/oscarehr/PMmodule/service/ProviderManager.java index 3387e87bf5..6850cb8f15 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/ProviderManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/ProviderManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. * This software is published under the GPL GNU General Public License. @@ -19,8 +20,9 @@ * This software was written for * Centre for Research on Inner City Health, St. Michael's Hospital, * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ - package org.oscarehr.PMmodule.service; import java.util.ArrayList; @@ -37,97 +39,24 @@ import org.oscarehr.common.model.Provider; import org.springframework.transaction.annotation.Transactional; -@Transactional -public class ProviderManager -{ - private ProviderDao providerDao; - private AgencyDao agencyDao; - private ProgramProviderDAO programProviderDAO; - private SecUserRoleDao secUserRoleDao; - - - public void setProviderDao(ProviderDao providerDao) { - this.providerDao = providerDao; - } - - public void setAgencyDao(AgencyDao agencyDao) { - this.agencyDao = agencyDao; - } - - public void setProgramProviderDAO(ProgramProviderDAO dao) { - this.programProviderDAO = dao; - } - - public void setSecUserRoleDao(SecUserRoleDao secUserRoleDao) { - this.secUserRoleDao = secUserRoleDao; - } - - public Provider getProvider(String providerNo) - { - return providerDao.getProvider(providerNo); - } - - public String getProviderName(String providerNo) - { - return providerDao.getProviderName(providerNo); - } - - public List getProviders() - { - return providerDao.getProviders(); - } - - public List getActiveProviders() - { - return providerDao.getActiveProviders(); - } - - public List getActiveProviders(String facilityId, String programId) { - return providerDao.getActiveProviders(facilityId, programId); - } - /* get my collegues */ - public List getActiveProviders(String providerNo, Integer shelterId) { - return providerDao.getActiveProviders(providerNo, shelterId); - } - - public List search(String name) { - return providerDao.search(name); - } - - public List getProgramDomain(String providerNo) { - return programProviderDAO.getProgramDomain(providerNo); - } - - public List getProgramDomainByFacility(String providerNo, Integer facilityId) { - return programProviderDAO.getProgramDomainByFacility(providerNo, facilityId); - } - - public List getFacilitiesInProgramDomain(String providerNo) { - return programProviderDAO.getFacilitiesInProgramDomain(providerNo); - } - - public List getShelterIds(String provider_no) - { - return providerDao.getShelterIds(provider_no); - } - - public List getAgencyDomain(String providerNo) { - Agency localAgency = agencyDao.getLocalAgency(); - List agencies = new ArrayList(); - agencies.add(localAgency); - return agencies; - } - - public List getProvidersByType(String type) { - return providerDao.getProvidersByType(type); - } - - public List getSecUserRoles(String providerNo) { - return secUserRoleDao.getUserRoles(providerNo); - } - - public void saveUserRole(SecUserRole sur) { - secUserRoleDao.save(sur); - } - +public interface ProviderManager { + void setProviderDao(ProviderDao providerDao); + void setAgencyDao(AgencyDao agencyDao); + void setProgramProviderDAO(ProgramProviderDAO dao); + void setSecUserRoleDao(SecUserRoleDao secUserRoleDao); + Provider getProvider(String providerNo); + String getProviderName(String providerNo); + List getProviders(); + List getActiveProviders(); + List getActiveProviders(String facilityId, String programId); + List getActiveProviders(String providerNo, Integer shelterId); + List search(String name); + List getProgramDomain(String providerNo); + List getProgramDomainByFacility(String providerNo, Integer facilityId); + List getFacilitiesInProgramDomain(String providerNo); + List getShelterIds(String provider_no); + List getAgencyDomain(String providerNo); + List getProvidersByType(String type); + List getSecUserRoles(String providerNo); + void saveUserRole(SecUserRole sur); } diff --git a/src/main/java/org/oscarehr/PMmodule/service/ProviderManagerImpl.java b/src/main/java/org/oscarehr/PMmodule/service/ProviderManagerImpl.java new file mode 100644 index 0000000000..ae3498898e --- /dev/null +++ b/src/main/java/org/oscarehr/PMmodule/service/ProviderManagerImpl.java @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. + * + * Copyright (c) 2005-2012. Centre for Research on Inner City Health, St. Michael's Hospital, Toronto. All Rights Reserved. + * This software is published under the GPL GNU General Public License. + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * This software was written for + * Centre for Research on Inner City Health, St. Michael's Hospital, + * Toronto, Ontario, Canada + * + * Modifications made by Magenta Health in 2024. + */ +package org.oscarehr.PMmodule.service; + +import org.oscarehr.PMmodule.dao.AgencyDao; +import org.oscarehr.PMmodule.dao.ProgramProviderDAO; +import org.oscarehr.PMmodule.dao.ProviderDao; +import org.oscarehr.PMmodule.dao.SecUserRoleDao; +import org.oscarehr.PMmodule.model.Agency; +import org.oscarehr.PMmodule.model.ProgramProvider; +import org.oscarehr.PMmodule.model.SecUserRole; +import org.oscarehr.common.model.Facility; +import org.oscarehr.common.model.Provider; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.List; + +@Transactional +public class ProviderManagerImpl implements ProviderManager { + private ProviderDao providerDao; + private AgencyDao agencyDao; + private ProgramProviderDAO programProviderDAO; + private SecUserRoleDao secUserRoleDao; + + public void setProviderDao(ProviderDao providerDao) { + this.providerDao = providerDao; + } + + public void setAgencyDao(AgencyDao agencyDao) { + this.agencyDao = agencyDao; + } + + public void setProgramProviderDAO(ProgramProviderDAO dao) { + this.programProviderDAO = dao; + } + + public void setSecUserRoleDao(SecUserRoleDao secUserRoleDao) { + this.secUserRoleDao = secUserRoleDao; + } + + public Provider getProvider(String providerNo) { + return providerDao.getProvider(providerNo); + } + + public String getProviderName(String providerNo) { + return providerDao.getProviderName(providerNo); + } + + public List getProviders() { + return providerDao.getProviders(); + } + + public List getActiveProviders() { + return providerDao.getActiveProviders(); + } + + public List getActiveProviders(String facilityId, String programId) { + return providerDao.getActiveProviders(facilityId, programId); + } + + public List getActiveProviders(String providerNo, Integer shelterId) { + return providerDao.getActiveProviders(providerNo, shelterId); + } + + public List search(String name) { + return providerDao.search(name); + } + + public List getProgramDomain(String providerNo) { + return programProviderDAO.getProgramDomain(providerNo); + } + + public List getProgramDomainByFacility(String providerNo, Integer facilityId) { + return programProviderDAO.getProgramDomainByFacility(providerNo, facilityId); + } + + public List getFacilitiesInProgramDomain(String providerNo) { + return programProviderDAO.getFacilitiesInProgramDomain(providerNo); + } + + public List getShelterIds(String provider_no) { + return providerDao.getShelterIds(provider_no); + } + + public List getAgencyDomain(String providerNo) { + Agency localAgency = agencyDao.getLocalAgency(); + List agencies = new ArrayList(); + agencies.add(localAgency); + return agencies; + } + + public List getProvidersByType(String type) { + return providerDao.getProvidersByType(type); + } + + public List getSecUserRoles(String providerNo) { + return secUserRoleDao.getUserRoles(providerNo); + } + + public void saveUserRole(SecUserRole sur) { + secUserRoleDao.save(sur); + } +} diff --git a/src/main/java/org/oscarehr/PMmodule/service/SurveyManager.java b/src/main/java/org/oscarehr/PMmodule/service/SurveyManager.java index bed9353fa5..c552fca2c3 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/SurveyManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/SurveyManager.java @@ -30,6 +30,7 @@ import org.apache.logging.log4j.Logger; import org.apache.struts.util.LabelValueBean; import org.oscarehr.PMmodule.dao.SurveySecurityDao; +import org.oscarehr.PMmodule.dao.SurveySecurityDaoImpl; import org.oscarehr.PMmodule.web.reports.custom.CustomReportDataSource; import org.oscarehr.PMmodule.web.reports.custom.Item; import org.oscarehr.common.dao.CaisiFormDao; @@ -51,119 +52,125 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -@Component(value="surveyManager2") +@Component(value = "surveyManager2") public class SurveyManager implements CustomReportDataSource { - - Logger log=MiscUtils.getLogger(); - + + Logger log = MiscUtils.getLogger(); + @Autowired - private CaisiFormDao caisiFormDao ; + private CaisiFormDao caisiFormDao; @Autowired - private CaisiFormDataDao caisiFormDataDao ; + private CaisiFormDataDao caisiFormDataDao; @Autowired - private CaisiFormInstanceDao caisiFormInstanceDao ; + private CaisiFormInstanceDao caisiFormInstanceDao; @Autowired - private CaisiFormDataTmpSaveDao caisiFormDataTmpSaveDao ; + private CaisiFormDataTmpSaveDao caisiFormDataTmpSaveDao; @Autowired - private CaisiFormInstanceTmpSaveDao caisiFormInstanceTmpSaveDao ; - + private CaisiFormInstanceTmpSaveDao caisiFormInstanceTmpSaveDao; + public List getAllFormsForCurrentProviderAndCurrentFacility(LoggedInInfo loggedInInfo) { List allForms = caisiFormDao.findActiveByFacilityIdOrNull(loggedInInfo.getCurrentFacility().getId()); List results = new ArrayList(); - SurveySecurityDao securityDao = new SurveySecurityDao(); - //filter out the ones due to security - for(CaisiForm form:allForms) { - //String name = form.getDescription().toLowerCase().replaceAll(" ","_"); + SurveySecurityDao securityDao = new SurveySecurityDaoImpl(); + // filter out the ones due to security + for (CaisiForm form : allForms) { + // String name = form.getDescription().toLowerCase().replaceAll(" ","_"); String name = form.getDescription(); - - if(securityDao.checkPrivilege(name,loggedInInfo.getLoggedInProviderNo())) { + + if (securityDao.checkPrivilege(name, loggedInInfo.getLoggedInProviderNo())) { results.add(form); } - + } return results; } + public CaisiForm getForm(String formId) { return caisiFormDao.find(Integer.valueOf(formId)); } - + public void saveFormInstance(CaisiFormInstance instance) { caisiFormInstanceDao.persist(instance); - + /* - for(Iterator iter=dataList.iterator();iter.hasNext();) { - CaisiFormData data = iter.next(); - data.setInstanceId(instance.getId()); - this.caisiFormDataDao.persist(data); - } - */ - + * for(Iterator iter=dataList.iterator();iter.hasNext();) { + * CaisiFormData data = iter.next(); + * data.setInstanceId(instance.getId()); + * this.caisiFormDataDao.persist(data); + * } + */ + } public void deleteTmpsave(String instanceId, String formId, String clientId, String providerId) { - List tmpInstances = getTmpForms(instanceId,formId,clientId,providerId); - if(tmpInstances.size()> 0 && tmpInstances!=null) { - CaisiFormInstanceTmpSave tmpInstance = (CaisiFormInstanceTmpSave)tmpInstances.get(0); + List tmpInstances = getTmpForms(instanceId, formId, clientId, providerId); + if (tmpInstances.size() > 0 && tmpInstances != null) { + CaisiFormInstanceTmpSave tmpInstance = (CaisiFormInstanceTmpSave) tmpInstances.get(0); /* - for(Iterator iter=tmpInstance.getData().iterator();iter.hasNext();) { - CaisiFormDataTmpSave data = (CaisiFormDataTmpSave)iter.next(); - this.caisiFormDataTmpSaveDao.remove(data); - } - */ + * for(Iterator iter=tmpInstance.getData().iterator();iter.hasNext();) { + * CaisiFormDataTmpSave data = (CaisiFormDataTmpSave)iter.next(); + * this.caisiFormDataTmpSaveDao.remove(data); + * } + */ caisiFormInstanceTmpSaveDao.remove(tmpInstance.getId()); } } - + public void saveFormInstanceTmpsave(CaisiFormInstanceTmpSave instance) { /* - for(Iterator iter=instance.getData().iterator();iter.hasNext();) { - CaisiFormDataTmpSave data = (CaisiFormDataTmpSave)iter.next(); - this.caisiFormDataTmpSaveDao.persist(data); - } - */ + * for(Iterator iter=instance.getData().iterator();iter.hasNext();) { + * CaisiFormDataTmpSave data = (CaisiFormDataTmpSave)iter.next(); + * this.caisiFormDataTmpSaveDao.persist(data); + * } + */ caisiFormInstanceTmpSaveDao.persist(instance); } - + public CaisiFormInstance getLatestForm(String formId, String clientId) { - return caisiFormInstanceDao.getLatestForm(Integer.valueOf(formId),Integer.valueOf(clientId)); + return caisiFormInstanceDao.getLatestForm(Integer.valueOf(formId), Integer.valueOf(clientId)); } - public List getFormsForCurrentProviderAndCurrentFacility(LoggedInInfo loggedInInfo, String clientId){ - List forms = caisiFormInstanceDao.getForms(Integer.valueOf(clientId), loggedInInfo.getCurrentFacility().getId()); + public List getFormsForCurrentProviderAndCurrentFacility(LoggedInInfo loggedInInfo, String clientId) { + List forms = caisiFormInstanceDao.getForms(Integer.valueOf(clientId), + loggedInInfo.getCurrentFacility().getId()); List results = new ArrayList(); - SurveySecurityDao securityDao = new SurveySecurityDao(); - - for(CaisiFormInstance form:forms) { + SurveySecurityDao securityDao = new SurveySecurityDaoImpl(); + + for (CaisiFormInstance form : forms) { String name = form.getDescription(); - - if(securityDao.checkPrivilege(name,loggedInInfo.getLoggedInProviderNo())) { + + if (securityDao.checkPrivilege(name, loggedInInfo.getLoggedInProviderNo())) { results.add(form); } } return results; } - + public List getForms(String clientId) { return caisiFormInstanceDao.getForms(Long.valueOf(clientId)); } public List getForms(String formId, String clientId) { - return caisiFormInstanceDao.getForms(Integer.valueOf(formId),Integer.valueOf(clientId)); + return caisiFormInstanceDao.getForms(Integer.valueOf(formId), Integer.valueOf(clientId)); } - public List getFormsByFacility(String clientId, Integer facilityId){ + public List getFormsByFacility(String clientId, Integer facilityId) { return caisiFormInstanceDao.getForms(Integer.valueOf(clientId), facilityId); } - + public CaisiFormInstance getCurrentFormById(String formInstanceId) { return caisiFormInstanceDao.find(Integer.valueOf(formInstanceId)); } + public List getTmpForms(String instanceId, String formId, String clientId, String providerId) { - return caisiFormInstanceTmpSaveDao.getTmpForms(Integer.valueOf(instanceId),Integer.valueOf(formId),Integer.valueOf(clientId), Integer.valueOf(providerId)); + return caisiFormInstanceTmpSaveDao.getTmpForms(Integer.valueOf(instanceId), Integer.valueOf(formId), + Integer.valueOf(clientId), Integer.valueOf(providerId)); } + public List getTmpFormData(String tmpInstanceId) { return caisiFormDataTmpSaveDao.getTmpFormData(Long.valueOf(tmpInstanceId)); } + public void saveFormData(CaisiFormData data) { caisiFormDataDao.persist(data); } @@ -171,90 +178,89 @@ public void saveFormData(CaisiFormData data) { public void saveFormDataTmpsave(CaisiFormDataTmpSave data) { caisiFormDataTmpSaveDao.persist(data); } - + public SurveyDocument.Survey getFormModel(String formId) { CaisiForm survey = getForm(formId); - if(survey != null) { + if (survey != null) { try { - String xml = survey.getSurveyData(); - SurveyDocument model = SurveyDocument.Factory.parse(new StringReader(xml)); - return model.getSurvey(); - }catch(Exception e) { - MiscUtils.getLogger().error("Error", e); - } + String xml = survey.getSurveyData(); + SurveyDocument model = SurveyDocument.Factory.parse(new StringReader(xml)); + return model.getSurvey(); + } catch (Exception e) { + MiscUtils.getLogger().error("Error", e); + } } return null; } - + public List getCurrentForms(String formId, List clients) { - return caisiFormInstanceDao.getCurrentForms(formId,clients); + return caisiFormInstanceDao.getCurrentForms(formId, clients); } - + public LabelValueBean[] getFormNames() { List forms = caisiFormDao.getCaisiForms(); LabelValueBean[] results = new LabelValueBean[forms.size()]; - int x=0; - for(CaisiForm form: forms) { - results[x] = new LabelValueBean(form.getDescription(),String.valueOf(form.getId())); + int x = 0; + for (CaisiForm form : forms) { + results[x] = new LabelValueBean(form.getDescription(), String.valueOf(form.getId())); x++; } return results; } - - + public LabelValueBean[] getItems(String formId) { List results = new ArrayList(); SurveyDocument.Survey survey = getFormModel(formId); - if(survey == null) { + if (survey == null) { return results.toArray(new LabelValueBean[results.size()]); } - - int pageId=1; - int sectionId=0; - for(Page page:survey.getBody().getPageArray()) { - for(Page.QContainer qcontainer:page.getQContainerArray()) { - sectionId=0; - if(qcontainer.isSetQuestion()) { + + int pageId = 1; + int sectionId = 0; + for (Page page : survey.getBody().getPageArray()) { + for (Page.QContainer qcontainer : page.getQContainerArray()) { + sectionId = 0; + if (qcontainer.isSetQuestion()) { Question question = qcontainer.getQuestion(); String id = pageId + "_" + sectionId + "_" + question.getId(); - results.add(new LabelValueBean(question.getDescription(),id)); + results.add(new LabelValueBean(question.getDescription(), id)); } else { Section section = qcontainer.getSection(); sectionId = section.getId(); - for(Question question: section.getQuestionArray()) { + for (Question question : section.getQuestionArray()) { String id = pageId + "_" + sectionId + "_" + question.getId(); - results.add(new LabelValueBean(question.getDescription(),id)); + results.add(new LabelValueBean(question.getDescription(), id)); } } } } - return results.toArray(new LabelValueBean[results.size()]); + return results.toArray(new LabelValueBean[results.size()]); } - + public Item getItem(String formId, String id) { SurveyDocument.Survey survey = getFormModel(formId); - if(survey == null) { + if (survey == null) { return null; } - - int pageId=1; - int sectionId=0; - for(Page page:survey.getBody().getPageArray()) { - for(Page.QContainer qcontainer:page.getQContainerArray()) { - sectionId=0; - if(qcontainer.isSetQuestion()) { + + int pageId = 1; + int sectionId = 0; + for (Page page : survey.getBody().getPageArray()) { + for (Page.QContainer qcontainer : page.getQContainerArray()) { + sectionId = 0; + if (qcontainer.isSetQuestion()) { Question question = qcontainer.getQuestion(); String tmpId = pageId + "_" + sectionId + "_" + question.getId(); - if(id.equals(tmpId)) { - return createItem(question,id); + if (id.equals(tmpId)) { + return createItem(question, id); } } else { Section section = qcontainer.getSection(); sectionId = section.getId(); - for(Question question: section.getQuestionArray()) { + for (Question question : section.getQuestionArray()) { String tmpId = pageId + "_" + sectionId + "_" + question.getId(); - if(id.equals(tmpId)) { - return createItem(question,id); + if (id.equals(tmpId)) { + return createItem(question, id); } } } @@ -262,12 +268,12 @@ public Item getItem(String formId, String id) { } return null; } - - private Item createItem(Question question,String id) { + + private Item createItem(Question question, String id) { Item item = new Item(); item.setId(id); item.setName(question.getDescription()); - + return item; } } diff --git a/src/main/java/org/oscarehr/PMmodule/service/VacancyTemplateManager.java b/src/main/java/org/oscarehr/PMmodule/service/VacancyTemplateManager.java index be904fb8eb..17b085e177 100644 --- a/src/main/java/org/oscarehr/PMmodule/service/VacancyTemplateManager.java +++ b/src/main/java/org/oscarehr/PMmodule/service/VacancyTemplateManager.java @@ -1,4 +1,5 @@ /** + * Copyright (c) 2024. Magenta Health. All Rights Reserved. * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or @@ -20,478 +21,36 @@ * McMaster University * Hamilton * Ontario, Canada + * + * Modifications made by Magenta Health in 2024. */ -package org.oscarehr.PMmodule.service; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; -import org.oscarehr.PMmodule.dao.CriteriaDao; -import org.oscarehr.PMmodule.dao.CriteriaSelectionOptionDao; -import org.oscarehr.PMmodule.dao.CriteriaTypeDao; -import org.oscarehr.PMmodule.dao.CriteriaTypeOptionDao; -import org.oscarehr.PMmodule.dao.ProgramDao; -import org.oscarehr.PMmodule.dao.VacancyDao; -import org.oscarehr.PMmodule.dao.VacancyTemplateDao; -import org.oscarehr.PMmodule.model.Criteria; -import org.oscarehr.PMmodule.model.CriteriaSelectionOption; -import org.oscarehr.PMmodule.model.CriteriaType; -import org.oscarehr.PMmodule.model.CriteriaTypeOption; -import org.oscarehr.PMmodule.model.Program; -import org.oscarehr.PMmodule.model.Vacancy; -import org.oscarehr.PMmodule.model.VacancyTemplate; -import org.oscarehr.util.LoggedInInfo; -import org.oscarehr.util.SpringUtils; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class VacancyTemplateManager { - - private static VacancyTemplateDao vacancyTemplateDAO = SpringUtils.getBean(VacancyTemplateDao.class); - private static CriteriaDao criteriaDAO = SpringUtils.getBean(CriteriaDao.class); - private static CriteriaTypeDao criteriaTypeDAO = SpringUtils.getBean(CriteriaTypeDao.class); - private static CriteriaTypeOptionDao criteriaTypeOptionDAO = SpringUtils.getBean(CriteriaTypeOptionDao.class); - private static CriteriaSelectionOptionDao criteriaSelectionOptionDAO = SpringUtils.getBean(CriteriaSelectionOptionDao.class); - private static ProgramDao programDao = (ProgramDao) SpringUtils.getBean("programDao"); - private static VacancyDao vacancyDAO= SpringUtils.getBean(VacancyDao.class); - - public static List getPrograms(Integer facilityId) { - return programDao.getProgramsByFacilityId(facilityId); - } - - public static List getVacancyTemplateByWlProgramId(Integer wlProgramId) { - List results = vacancyTemplateDAO.getVacancyTemplateByWlProgramId(wlProgramId); - return (results); - } - - public static List getVacanciesByWlProgramId(Integer wlProgramId) { - List results = vacancyDAO.getVacanciesByWlProgramId(wlProgramId); - return (results); - } - - public static List getVacanciesByWlProgramIdAndStatus(Integer wlProgramId,String status) { - List results = vacancyDAO.getVacanciesByWlProgramIdAndStatus(wlProgramId,status); - return (results); - } - - public static List getCriteriaTypeOptions(Integer typeId) { - List results = criteriaTypeOptionDAO.getCriteriaTypeOptionByTypeId(typeId); - return (results); - } - - public static List getAllCriteriaTypeOptions() { - List results = criteriaTypeOptionDAO.findAll(); - return (results); - } - - public static VacancyTemplate getVacancyTemplateByTemplateId(Integer templateId) { - VacancyTemplate vacancyTemplate = vacancyTemplateDAO.find(templateId); - return (vacancyTemplate); - } - - public static Criteria getCriteriaByCriteriaId(Integer id) { - Criteria c = criteriaDAO.find(id); - return (c); - } - - - public static Criteria getSelectedCriteria(Integer templateId, Integer vacancyId, Integer typeId) { - if(templateId == null && typeId == null) - return null; - if(vacancyId == null && typeId == null) - return null; - if(vacancyId != null && typeId != null) - return criteriaDAO.getCriteriaByTemplateIdVacancyIdTypeId(null, vacancyId, typeId); - else if (templateId != null && typeId != null) - return criteriaDAO.getCriteriaByTemplateIdVacancyIdTypeId(templateId, null, typeId); - else - return criteriaDAO.getCriteriaByTemplateIdVacancyIdTypeId(templateId, vacancyId, typeId); - } - - public static List getAllCriteriaTypes() { - return criteriaTypeDAO.getAllCriteriaTypes(); - } - - public static List getAllCriteriaTypesByWlProgramId(Integer programId) { - return criteriaTypeDAO.getAllCriteriaTypesByWlProgramId(programId); - } - - public static List getRefinedCriteriasByVacancyId(Integer vacancyId) { - return criteriaDAO.getRefinedCriteriasByVacancyId(vacancyId); - } - - public static List getCriteriasByVacancyId(Integer vacancyId) { - return criteriaDAO.getCriteriasByVacancyId(vacancyId); - } - - public static List getRefinedCriteriasByTemplateId(Integer templateId) { - return criteriaDAO.getRefinedCriteriasByTemplateId(templateId); - } - - public static List getActiveVacancyTemplatesByWlProgramId(Integer programId) { - if(programId == null) - return null; - return vacancyTemplateDAO.getActiveVacancyTemplatesByWlProgramId(programId); - } - - public static CriteriaType getCriteriaTypeById(Integer id) { - return criteriaTypeDAO.find(id); - } - - public static Vacancy getVacancyById(Integer id) { - return vacancyDAO.find(id); - } - - public static Vacancy getVacancyByName(String vacancyName) { - List v = vacancyDAO.getVacanciesByName(vacancyName); - if(v.isEmpty()) - return null; - else - return vacancyDAO.getVacanciesByName(vacancyName).get(0); - } - - /** - * This method is meant to return a bunch of html