001package org.kuali.ole.deliver.inquiry;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.kuali.ole.OLEConstants;
005import org.kuali.ole.OLEPropertyConstants;
006import org.kuali.ole.deliver.bo.*;
007import org.kuali.ole.deliver.processor.LoanProcessor;
008import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
009import org.kuali.rice.core.api.config.property.ConfigContext;
010import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
011import org.kuali.rice.kim.impl.identity.affiliation.EntityAffiliationBo;
012import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentBo;
013import org.kuali.rice.kim.impl.identity.entity.EntityBo;
014import org.kuali.rice.krad.bo.BusinessObject;
015import org.kuali.rice.krad.bo.ExternalizableBusinessObject;
016import org.kuali.rice.krad.datadictionary.exception.UnknownBusinessClassAttributeException;
017import org.kuali.rice.krad.inquiry.InquirableImpl;
018import org.kuali.rice.krad.service.KRADServiceLocator;
019import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
020import org.kuali.rice.krad.service.ModuleService;
021
022import java.security.GeneralSecurityException;
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027
028/**
029 * OlePatronInquirableImpl supports to get the data object and patron document.
030 */
031public class OlePatronInquirableImpl extends InquirableImpl {
032    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePatronInquirableImpl.class);
033
034    /**
035     * This method will retrieve the patron document based on the olePatronId
036     *
037     * @param parameters
038     * @return patronDocument(Object)
039     */
040    String baseUrl = ConfigContext.getCurrentContextConfig().getProperty(OLEPropertyConstants.OLE_URL_BASE);
041
042    public Object retrieveDataObject(Map<String, String> parameters) {
043        if (dataObjectClass == null) {
044            LOG.error("Data object class must be set in inquirable before retrieving the object");
045            throw new RuntimeException("Data object class must be set in inquirable before retrieving the object");
046        }
047
048        // build list of key values from the map parameters
049        List<String> pkPropertyNames = getDataObjectMetaDataService().listPrimaryKeyFieldNames(dataObjectClass);
050
051        // some classes might have alternate keys defined for retrieving
052        List<List<String>> alternateKeyNames = this.getAlternateKeysForClass(dataObjectClass);
053
054        // add pk set as beginning so it will be checked first for match
055        alternateKeyNames.add(0, pkPropertyNames);
056
057        List<String> dataObjectKeySet = retrieveKeySetFromMap(alternateKeyNames, parameters);
058        if ((dataObjectKeySet == null) || dataObjectKeySet.isEmpty()) {
059            LOG.warn("Matching key set not found in request for class: " + getDataObjectClass());
060
061            return null;
062        }
063        String patronHome = parameters.get("flow");
064
065        // found key set, now build map of key values pairs we can use to retrieve the object
066        Map<String, Object> keyPropertyValues = new HashMap<String, Object>();
067        for (String keyPropertyName : dataObjectKeySet) {
068            String keyPropertyValue = parameters.get(keyPropertyName);
069
070            // uppercase value if needed
071            Boolean forceUppercase = Boolean.FALSE;
072            try {
073                forceUppercase = getDataDictionaryService().getAttributeForceUppercase(dataObjectClass,
074                        keyPropertyName);
075            } catch (UnknownBusinessClassAttributeException ex) {
076                // swallowing exception because this check for ForceUppercase would
077                // require a DD entry for the attribute, and we will just set force uppercase to false
078                LOG.warn("Data object class "
079                        + dataObjectClass
080                        + " property "
081                        + keyPropertyName
082                        + " should probably have a DD definition.", ex);
083            }
084
085            if (forceUppercase.booleanValue() && (keyPropertyValue != null)) {
086                keyPropertyValue = keyPropertyValue.toUpperCase();
087            }
088
089            // check security on key field
090            if (getDataObjectAuthorizationService().attributeValueNeedsToBeEncryptedOnFormsAndLinks(dataObjectClass,
091                    keyPropertyName)) {
092                try {
093                    keyPropertyValue = getEncryptionService().decrypt(keyPropertyValue);
094                } catch (GeneralSecurityException e) {
095                    LOG.error("Data object class "
096                            + dataObjectClass
097                            + " property "
098                            + keyPropertyName
099                            + " should have been encrypted, but there was a problem decrypting it.", e);
100                    throw new RuntimeException("Data object class "
101                            + dataObjectClass
102                            + " property "
103                            + keyPropertyName
104                            + " should have been encrypted, but there was a problem decrypting it.", e);
105                }
106            }
107
108            keyPropertyValues.put(keyPropertyName, keyPropertyValue);
109        }
110
111        // now retrieve the object based on the key set
112        Object dataObject = null;
113
114        ModuleService moduleService = KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService(
115                getDataObjectClass());
116        if (moduleService != null && moduleService.isExternalizable(getDataObjectClass())) {
117            dataObject = moduleService.getExternalizableBusinessObject(getDataObjectClass().asSubclass(
118                    ExternalizableBusinessObject.class), keyPropertyValues);
119        } else if (BusinessObject.class.isAssignableFrom(getDataObjectClass())) {
120            dataObject = getBusinessObjectService().findByPrimaryKey(getDataObjectClass().asSubclass(
121                    BusinessObject.class), keyPropertyValues);
122        }
123        //OleEntityAddressBo entityAddressBo = new OleEntityAddressBo();
124        EntityAddressBo entityAddress = new EntityAddressBo();
125        List<OleEntityAddressBo> oleEntityAddressList = new ArrayList<OleEntityAddressBo>();
126        OlePatronDocument patronDocument = (OlePatronDocument) dataObject;
127        if (patronDocument != null) {
128            EntityBo kimEnity = patronDocument.getEntity();
129            if (kimEnity.getNames().size() > 0) {
130                patronDocument.setName(kimEnity.getNames().get(0));
131            }
132            if(kimEnity.getEntityTypeContactInfos().size()>0){
133                List<EntityAddressBo> entityAddressList = kimEnity.getEntityTypeContactInfos().get(0).getAddresses();
134                for (EntityAddressBo entityAdd : entityAddressList) {
135                    OleEntityAddressBo entityAddressBo = new OleEntityAddressBo();
136                    entityAddressBo.setEntityAddressBo(entityAdd);
137                    Map addMap = new HashMap();
138                    //addMap.put(OLEConstants.OlePatron.OLE_ADDRESS_ID, entityAdd.getId());
139                    addMap.put("id", entityAdd.getId());
140                    OleAddressBo oleAddressBo = getBusinessObjectService().findByPrimaryKey(OleAddressBo.class, addMap);
141                    entityAddressBo.setOleAddressBo(oleAddressBo);
142                    oleEntityAddressList.add(entityAddressBo);
143                }
144                patronDocument.setOleEntityAddressBo(oleEntityAddressList);
145                patronDocument.setPhones(kimEnity.getEntityTypeContactInfos().get(0).getPhoneNumbers());
146                patronDocument.setEmails(kimEnity.getEntityTypeContactInfos().get(0).getEmailAddresses());
147                patronDocument.setPatronAffiliations(getPatronAffiliationFromEntity(kimEnity.getAffiliations(), kimEnity.getEmploymentInformation()));
148                if (patronHome != null) {
149                    if (patronHome.equalsIgnoreCase("start"))
150                        patronDocument.setPatronHomePage(false);
151                    else
152                        patronDocument.setPatronHomePage(true);
153                }
154            }
155            if (null != patronDocument.getName()) {
156                String createBillUrl = OLEConstants.OlePatron.PATRON_CREATE_BILL_URL + patronDocument.getOlePatronId() + "&firstName=" + patronDocument.getName().getFirstName() + "&lastName=" + patronDocument.getName().getLastName();
157                patronDocument.setCreateBillUrl(createBillUrl);
158            }
159            if (CollectionUtils.isNotEmpty(patronDocument.getPatronBillPayments())) {
160                patronDocument.setPatronBillFileName(OLEConstants.OlePatron.PATRON_VIEW_BILLS);
161                patronDocument.setViewBillUrl(OLEConstants.OlePatron.PATRON_VIEW_BILL_URL + patronDocument.getOlePatronId());
162            }
163            patronDocument.setShowBillUrlsFlag(true);
164        }
165
166        if(patronDocument.getOleLoanDocuments()!=null){
167            patronDocument.setLoanCount(patronDocument.getOleLoanDocuments().size());
168        }
169        if(patronDocument.getOleTemporaryCirculationHistoryRecords()!=null){
170            patronDocument.setTempCirculationHistoryCount(patronDocument.getOleTemporaryCirculationHistoryRecords().size());
171        }
172        if(patronDocument.getOleDeliverRequestBos()!=null){
173            patronDocument.setRequestedItemRecordsCount(patronDocument.getOleDeliverRequestBos().size());
174        }
175        return patronDocument;
176    }
177
178    private List<OlePatronAffiliation> getPatronAffiliationFromEntity(List<EntityAffiliationBo> affiliations,
179                                                                      List<EntityEmploymentBo> employeeDetails) {
180        List<OlePatronAffiliation> patronAffiliations = new ArrayList<OlePatronAffiliation>();
181        for (EntityAffiliationBo entityAffiliationBo : affiliations) {
182            OlePatronAffiliation patronAffiliation = new OlePatronAffiliation(entityAffiliationBo);
183            List<EntityEmploymentBo> employmentBos = new ArrayList<EntityEmploymentBo>();
184            for (EntityEmploymentBo entityEmploymentBo : employeeDetails) {
185                if (patronAffiliation.getEntityAffiliationId().equalsIgnoreCase(entityEmploymentBo.getEntityAffiliationId())) {
186                    employmentBos.add(entityEmploymentBo);
187                }
188                patronAffiliation.setEmployments(employmentBos);
189            }
190            patronAffiliations.add(patronAffiliation);
191        }
192        return patronAffiliations;
193    }
194
195    public String getTempCircRecords(String olePatronId) {
196        String url = baseUrl + "/portal.do?channelTitle=Patron&channelUrl=" + baseUrl + "/ole-kr-krad/temporaryCirculationRecord?viewId=OleTemporaryCirculationHistoryRecordView&amp;methodToCall=viewTempCircRecords&amp;patronId=" + olePatronId;
197        return url;
198    }
199
200    public String getLoanedRecords(String olePatronId) {
201
202        String url = baseUrl + "/portal.do?channelTitle=Patron&channelUrl=" + baseUrl + "/ole-kr-krad/patronLoanedRecord?viewId=OlePatronLoanedRecordView&amp;methodToCall=viewLoanedRecords&amp;patronId=" + olePatronId;
203        return url;
204    }
205
206    public String getRequestedRecords(String olePatronId) {
207        String url = baseUrl + "/portal.do?channelTitle=Patron&channelUrl=" + baseUrl + "/ole-kr-krad/patronRequestedRecord?viewId=OlePatronRequestedRecordView&amp;methodToCall=viewRequestedRecords&amp;patronId=" + olePatronId;
208        return url;
209    }
210
211    public String getCountOfPendingRequests(String itemId){
212        Map itemMap = new HashMap();
213        itemMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemId);
214        List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, itemMap);
215        if (oleDeliverRequestBoList!=null && oleDeliverRequestBoList.size()>0) {
216
217            return "View all requests";
218        }
219        else
220            return " ";
221    }
222
223    public String getHrefLink(String item,String instance,String bib){
224       String inquiryUrl= ConfigContext.getCurrentContextConfig().getProperty(OLEPropertyConstants.OLE_URL_BASE)+
225               "/ole-kr-krad/editorcontroller?viewId=EditorView&amp;methodToCall=load&amp;docCategory=work&amp;docType=item&amp;editable=false&amp;docFormat=oleml&amp;docId="+item+"&amp;instanceId="+instance+"&amp;bibId="+bib+"";
226        return inquiryUrl;
227    }
228
229}