001package org.kuali.ole.deliver.processor;
002
003import org.apache.commons.collections.CollectionUtils;
004import org.apache.commons.lang.StringUtils;
005import org.apache.log4j.Logger;
006import org.kuali.ole.DataCarrierService;
007import org.kuali.ole.DocumentUniqueIDPrefix;
008import org.kuali.ole.OLEConstants;
009import org.kuali.ole.OLEParameterConstants;
010import org.kuali.ole.deliver.OleLoanDocumentsFromSolrBuilder;
011import org.kuali.ole.deliver.SearchParmsBuilder;
012import org.kuali.ole.deliver.batch.OleDeliverBatchServiceImpl;
013import org.kuali.ole.deliver.batch.OleMailer;
014import org.kuali.ole.deliver.batch.OleNoticeBo;
015import org.kuali.ole.deliver.bo.*;
016import org.kuali.ole.deliver.calendar.bo.OleCalendar;
017import org.kuali.ole.deliver.calendar.service.OleCalendarService;
018import org.kuali.ole.deliver.calendar.service.impl.OleCalendarServiceImpl;
019import org.kuali.ole.deliver.form.OleLoanForm;
020import org.kuali.ole.deliver.service.CircDeskLocationResolver;
021import org.kuali.ole.deliver.service.OLEDeliverNoticeHelperService;
022import org.kuali.ole.deliver.service.OleDeliverRequestDocumentHelperServiceImpl;
023import org.kuali.ole.deliver.service.OleLoanDocumentDaoOjb;
024import org.kuali.ole.describe.bo.OleInstanceItemType;
025import org.kuali.ole.describe.bo.OleItemAvailableStatus;
026import org.kuali.ole.describe.bo.OleLocation;
027import org.kuali.ole.describe.bo.OleLocationLevel;
028import org.kuali.ole.describe.keyvalue.LocationValuesBuilder;
029import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
030import org.kuali.ole.docstore.common.document.*;
031import org.kuali.ole.docstore.common.document.Item;
032import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecord;
033import org.kuali.ole.docstore.common.document.content.enums.DocType;
034import org.kuali.ole.docstore.common.document.content.instance.*;
035import org.kuali.ole.docstore.common.document.content.instance.ItemClaimsReturnedRecord;
036import org.kuali.ole.docstore.common.document.content.instance.ItemDamagedRecord;
037import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
038import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
039import org.kuali.ole.docstore.common.document.content.instance.MissingPieceItemRecord;
040import org.kuali.ole.docstore.common.search.*;
041import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.DataField;
042import org.kuali.ole.docstore.model.xmlpojo.work.bib.marc.SubField;
043import org.kuali.ole.ingest.pojo.MatchBo;
044import org.kuali.ole.pojo.bib.BibliographicRecord;
045import org.kuali.ole.service.OleCirculationPolicyService;
046import org.kuali.ole.service.OleCirculationPolicyServiceImpl;
047import org.kuali.ole.service.OlePatronHelperService;
048import org.kuali.ole.service.OlePatronHelperServiceImpl;
049import org.kuali.ole.sys.context.SpringContext;
050import org.kuali.ole.util.DocstoreUtil;
051import org.kuali.rice.core.api.config.property.ConfigContext;
052import org.kuali.rice.core.api.datetime.DateTimeService;
053import org.kuali.rice.core.api.mail.EmailBody;
054import org.kuali.rice.core.api.mail.EmailFrom;
055import org.kuali.rice.core.api.mail.EmailSubject;
056import org.kuali.rice.core.api.mail.EmailTo;
057import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
058import org.kuali.rice.core.api.util.type.KualiDecimal;
059import org.kuali.rice.coreservice.api.CoreServiceApiServiceLocator;
060import org.kuali.rice.coreservice.api.parameter.Parameter;
061import org.kuali.rice.coreservice.api.parameter.ParameterKey;
062import org.kuali.rice.kim.api.identity.principal.Principal;
063import org.kuali.rice.kim.api.permission.PermissionService;
064import org.kuali.rice.kim.api.role.Role;
065import org.kuali.rice.kim.api.services.KimApiServiceLocator;
066import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
067import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
068import org.kuali.rice.kim.impl.identity.entity.EntityBo;
069import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
070import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
071import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
072import org.kuali.rice.kim.impl.role.RoleServiceImpl;
073import org.kuali.rice.krad.service.BusinessObjectService;
074import org.kuali.rice.krad.service.KRADServiceLocator;
075import org.kuali.rice.krad.service.PersistenceService;
076import org.kuali.rice.krad.util.GlobalVariables;
077import org.kuali.rice.krad.util.KRADConstants;
078import org.kuali.rice.krms.api.KrmsApiServiceLocator;
079import org.kuali.rice.krms.api.engine.*;
080import org.kuali.rice.krms.api.repository.agenda.AgendaDefinition;
081import org.kuali.rice.krms.api.repository.context.ContextDefinition;
082import org.kuali.rice.krms.impl.repository.KrmsRepositoryServiceLocator;
083
084import javax.xml.datatype.DatatypeConfigurationException;
085import javax.xml.datatype.DatatypeFactory;
086import javax.xml.datatype.XMLGregorianCalendar;
087import java.math.BigDecimal;
088import java.sql.Timestamp;
089import java.text.DateFormat;
090import java.text.ParseException;
091import java.text.SimpleDateFormat;
092import java.util.*;
093import java.util.regex.Matcher;
094import java.util.regex.Pattern;
095
096/**
097 * The Loan Processor  class acts between the controller and the service layers in delegating the appropriate service
098 * to the functions called from the controller.
099 */
100public class LoanProcessor {
101    private static final Logger LOG = Logger.getLogger(LoanProcessor.class);
102
103    private BusinessObjectService businessObjectService;
104    private DocstoreUtil docstoreUtil;
105    private OleCirculationPolicyService oleCirculationPolicyService;
106    private OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService;
107    private String circDeskId;
108    private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
109    private static final String NAME_SELECTOR = "name";
110    private String lostDescription;
111    private String lostStatus;
112    private String lostPatronId;
113    private OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb;
114    private OLEDeliverNoticeHelperService oleDeliverNoticeHelperService;
115    private static Map<String, String> locationName = new HashMap<>();
116
117    private CircDeskLocationResolver circDeskLocationResolver;
118    private OlePatronHelperServiceImpl olePatronHelperService;
119    private DocstoreClientLocator docstoreClientLocator;
120
121    private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
122
123    private  DataCarrierService dataCarrierService;
124
125    private String itemStatus;
126    private OleLoanDocumentsFromSolrBuilder oleLoanDocumentsFromSolrBuilder;
127
128    public DataCarrierService getDataCarrierService() {
129        if(dataCarrierService == null){
130            dataCarrierService = SpringContext.getBean(DataCarrierService.class);
131        }
132        return dataCarrierService;
133    }
134
135    public DocstoreUtil getDocstoreUtil() {
136        if(docstoreUtil == null){
137            docstoreUtil = new DocstoreUtil();
138        }
139        return docstoreUtil;
140    }
141
142    public void setDataCarrierService(DataCarrierService dataCarrierService) {
143        this.dataCarrierService = dataCarrierService;
144    }
145
146    public DocstoreClientLocator getDocstoreClientLocator() {
147
148        if (docstoreClientLocator == null) {
149            docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
150
151        }
152        return docstoreClientLocator;
153    }
154
155
156    public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
157        if(itemOlemlRecordProcessor == null){
158            itemOlemlRecordProcessor = SpringContext.getBean(ItemOlemlRecordProcessor.class);
159        }
160        return itemOlemlRecordProcessor;
161    }
162
163    public OleDeliverRequestDocumentHelperServiceImpl getOleDeliverRequestDocumentHelperService() {
164        if (oleDeliverRequestDocumentHelperService == null) {
165            oleDeliverRequestDocumentHelperService = (OleDeliverRequestDocumentHelperServiceImpl) SpringContext.getService("oleDeliverRequestDocumentHelperService");
166        }
167        return oleDeliverRequestDocumentHelperService;
168    }
169
170    public OlePatronHelperService getOlePatronHelperService(){
171        if(olePatronHelperService==null)
172            olePatronHelperService=new OlePatronHelperServiceImpl();
173        return olePatronHelperService;
174    }
175
176    public void setOlePatronHelperService(OlePatronHelperServiceImpl olePatronHelperService) {
177        this.olePatronHelperService = olePatronHelperService;
178    }
179
180    public void setBusinessObjectService(BusinessObjectService businessObjectService) {
181        this.businessObjectService = businessObjectService;
182    }
183
184    public void setOleCirculationPolicyService(OleCirculationPolicyService oleCirculationPolicyService) {
185        this.oleCirculationPolicyService = oleCirculationPolicyService;
186    }
187
188    public void setOleDeliverRequestDocumentHelperService(OleDeliverRequestDocumentHelperServiceImpl oleDeliverRequestDocumentHelperService) {
189        this.oleDeliverRequestDocumentHelperService = oleDeliverRequestDocumentHelperService;
190    }
191
192    public void setDocstoreClientLocator(DocstoreClientLocator docstoreClientLocator) {
193        this.docstoreClientLocator = docstoreClientLocator;
194    }
195
196    public void setItemOlemlRecordProcessor(ItemOlemlRecordProcessor itemOlemlRecordProcessor) {
197        this.itemOlemlRecordProcessor = itemOlemlRecordProcessor;
198    }
199
200    public String getLostDescription() {
201        return lostDescription;
202    }
203
204    public void setLostDescription(String lostDescription) {
205        this.lostDescription = lostDescription;
206    }
207
208    public String getLostStatus() {
209        return lostStatus;
210    }
211
212    public void setLostStatus(String lostStatus) {
213        this.lostStatus = lostStatus;
214    }
215
216    public String getLostPatronId() {
217        return lostPatronId;
218    }
219
220    public void setLostPatronId(String lostPatronId) {
221        this.lostPatronId = lostPatronId;
222    }
223
224    /**
225     * Gets the businessObjectService attribute.
226     *
227     * @return Returns the businessObjectService
228     */
229    public BusinessObjectService getBusinessObjectService() {
230        if (null == businessObjectService) {
231            businessObjectService = KRADServiceLocator.getBusinessObjectService();
232        }
233        return businessObjectService;
234    }
235
236    /**
237     * Gets the oleCirculationPolicyService attribute.
238     *
239     * @return Returns the oleCirculationPolicyService
240     */
241    public OleCirculationPolicyService getOleCirculationPolicyService() {
242        if (null == oleCirculationPolicyService) {
243            oleCirculationPolicyService = SpringContext.getBean(OleCirculationPolicyServiceImpl.class);
244        }
245        return oleCirculationPolicyService;
246    }
247
248    private CircDeskLocationResolver getCircDeskLocationResolver() {
249        if (circDeskLocationResolver == null) {
250            circDeskLocationResolver = new CircDeskLocationResolver();
251        }
252        return circDeskLocationResolver;
253    }
254
255    public void setCircDeskLocationResolver(CircDeskLocationResolver circDeskLocationResolver) {
256        this.circDeskLocationResolver = circDeskLocationResolver;
257    }
258
259
260    /**
261     * Validates the patron barcode for general blocks and address verified.
262     *
263     * @param oleLoanDocument
264     * @return
265     * @throws Exception
266     */
267    private boolean checkAddressVerifiedAndBlocks(OleLoanDocument oleLoanDocument) throws Exception {
268        boolean isAddressVerified = false;
269        try {
270            isAddressVerified = (boolean) getOleCirculationPolicyService().isAddressVerified(oleLoanDocument.getOlePatron(),oleLoanDocument.getPatronId());
271            if (!isAddressVerified || oleLoanDocument.getOlePatron().isGeneralBlock()) {
272                oleLoanDocument.setAddressVerified(true);
273            }
274        } catch (Exception e) {
275            LOG.error("Exception while checking address verified & blocks", e);
276            throw e;
277        }
278        return isAddressVerified;
279    }
280
281    /**
282     * Retrieve information about patron name,borrorwer type and patron loaned items
283     *
284     * @param barcode
285     * @return OleLoanDocument
286     */
287    public OleLoanDocument getLoanDocument(String barcode, String realPtrnBarcode, boolean selfCheckOut,boolean isProxyToRealPatron) throws Exception {
288        LOG.debug("Inside the getLoanDocument method");
289        Long b1 = System.currentTimeMillis();
290        OleLoanDocument oleLoanDocument = new OleLoanDocument();
291        String patronInactiveMessage=OLEConstants.PATRON_INVALID_BARCODE_MESSAGE;
292        if (barcode != null && checkLostPatronBarcode(barcode)) {
293            //oleLoanDocument.setErrorMessage(OLEConstants.H4 + OLEConstants.BARCODE_LOST_OR_STOLEN + OLEConstants.H4_CLOSE);
294            String url="<a target=\"_blank\" href="+OLEConstants.ASSIGN_EDIT_PATRON_ID + getLostPatronId() + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT+">"+getLostPatronId()+"</a>";
295            String patronUrl=OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + "Patron Details : " + OLEConstants.TEXT_BOLD_TAG_CLOSE +url+OLEConstants.H5_CLOSE + OLEConstants.H5;
296            oleLoanDocument.setErrorMessage(patronInactiveMessage+patronUrl+OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_STATUS_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostStatus()!=null?getLostStatus():"") + OLEConstants.H5_CLOSE + OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_DESCRIPTION_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostDescription()!=null?getLostDescription():"") + OLEConstants.H5_CLOSE);
297            oleLoanDocument.setBlockLoan(true);
298            oleLoanDocument.setLostPatron(true);
299            return oleLoanDocument;
300        } else if (realPtrnBarcode != null && checkLostPatronBarcode(realPtrnBarcode)) {
301            //oleLoanDocument.setErrorMessage(OLEConstants.H4 + OLEConstants.BARCODE_LOST_OR_STOLEN + OLEConstants.H4_CLOSE);
302            String url="<a target=\"_blank\" href="+OLEConstants.ASSIGN_EDIT_PATRON_ID + getLostPatronId() + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT+">"+getLostPatronId()+"</a>";
303            String patronUrl=OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + "Patron Details : " + OLEConstants.TEXT_BOLD_TAG_CLOSE +url+OLEConstants.H5_CLOSE + OLEConstants.H5;
304            oleLoanDocument.setErrorMessage(patronInactiveMessage+patronUrl+OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_STATUS_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostStatus()!=null?getLostStatus():"") + OLEConstants.H5_CLOSE + OLEConstants.H5 + OLEConstants.TEXT_BOLD_TAG_START + OLEConstants.PATRON_DESCRIPTION_LABEL + OLEConstants.TEXT_BOLD_TAG_CLOSE + (getLostDescription()!=null?getLostDescription():"") + OLEConstants.H5_CLOSE);
305            oleLoanDocument.setBlockLoan(true);
306            oleLoanDocument.setLostPatron(true);
307            return oleLoanDocument;
308        }
309        oleLoanDocument = getPatronBarcodeRecord(barcode);
310        oleLoanDocument.setRealPatronBarcode(realPtrnBarcode);
311        Date expirationDate = oleLoanDocument.getOlePatron().getExpirationDate();
312        List<OlePatronDocument> proxyPatron = null;
313        if (!selfCheckOut && !isProxyToRealPatron) {
314            proxyPatron = (List<OlePatronDocument>) getOleCirculationPolicyService().isProxyPatron(oleLoanDocument.getOlePatron());
315        }
316        String agendaName = OLEConstants.CHECK_OUT_GEN_AGENDA_NM;
317        OleLoanDocument oleLoanDocumentForRealPatron = new OleLoanDocument();
318        String digitRoutine = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE);
319        String pattern = getParameter(OLEConstants.PATRON_DIGIT_ROUTINE_PATTERN);
320        HashMap<String, Object> termValues = new HashMap<String, Object>();
321        // Check for Proxy Patron.
322        if (!isProxyToRealPatron) {
323            if (proxyPatron != null && proxyPatron.size() > 0 && !isProxyToRealPatron) {
324                // Display real patron in pop up, if it is more than one. Or continue if the proxy patron as single real patron.
325                if (realPtrnBarcode == null && proxyPatron.size() > 0) {
326                    oleLoanDocument.setRealPatron(proxyPatron);
327                    return oleLoanDocument;
328                }
329                oleLoanDocumentForRealPatron = getPatronBarcodeRecord(realPtrnBarcode);      // retrieves Loan Document for real patron.
330                oleLoanDocument.setProxyPatronId(oleLoanDocumentForRealPatron.getPatronId());
331                oleLoanDocument.setRealPatronName(getPatronName(oleLoanDocumentForRealPatron.getPatronId()));
332                oleLoanDocument.setRealPatronType(oleLoanDocumentForRealPatron.getBorrowerTypeCode());
333                boolean isAddressVerifiedReal = checkAddressVerifiedAndBlocks(oleLoanDocumentForRealPatron); // Checks isAddressVerified for real patron.
334                termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocumentForRealPatron.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
335                termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerifiedReal ? OLEConstants.TRUE : OLEConstants.FALSE);
336                termValues.put(OLEConstants.EXPIR_DATE, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate());  // Checks Expiration Date for real patron.
337                termValues.put(OLEConstants.PROXY_EXPIR_DATE, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate());                                 // Checks Expiration Date for proxy patron.
338                termValues.put(OLEConstants.PATRON_BAR, realPtrnBarcode);  // Checks Barcode for real patron.
339                termValues.put(OLEConstants.IS_PROXY_PATRON, OLEConstants.TRUE);
340                termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocument.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
341                termValues.put(OLEConstants.IS_ACTIVE_PROXY_PATRON, oleLoanDocumentForRealPatron.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
342                termValues.put(OLEConstants.PROXY_PATRON_ACTIVATION_DATE, oleLoanDocumentForRealPatron.getOlePatron().getActivationDate());
343                termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocument.getOlePatron().getActivationDate());
344                termValues.put(OLEConstants.PROXY_PATRON_ACTIVATION_DATE_STRING, oleLoanDocumentForRealPatron.getOlePatron().getActivationDate() != null ? oleLoanDocumentForRealPatron.getOlePatron().getActivationDate().toString() : "null");
345                termValues.put(OLEConstants.PROXY_PATRON_EXPIRATION_DATE_STRING, oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate() != null ? oleLoanDocumentForRealPatron.getOlePatron().getExpirationDate().toString() : "null");
346            } else {
347                boolean isAddressVerified = checkAddressVerifiedAndBlocks(oleLoanDocument);
348                termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocument.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
349                termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
350                termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
351                termValues.put(OLEConstants.PATRON_BAR, barcode);
352                termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocument.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
353                termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocument.getOlePatron().getActivationDate());
354            }
355        } else {
356            OleLoanDocument oleLoanDocumentProxyToReal = new OleLoanDocument();
357            oleLoanDocumentProxyToReal=getPatronBarcodeRecord(barcode);
358            boolean isAddressVerified = checkAddressVerifiedAndBlocks(oleLoanDocumentProxyToReal);
359            termValues.put(OLEConstants.GENERAL_BLOCK, oleLoanDocumentProxyToReal.getOlePatron().isGeneralBlock() ? OLEConstants.TRUE : OLEConstants.FALSE);
360            termValues.put(OLEConstants.EXPIR_DATE, expirationDate);
361            termValues.put(OLEConstants.ADDR_VERIFIED, isAddressVerified ? OLEConstants.TRUE : OLEConstants.FALSE);
362            termValues.put(OLEConstants.PATRON_BAR, barcode);
363            termValues.put(OLEConstants.IS_ACTIVE_PATRON, oleLoanDocumentProxyToReal.getOlePatron().isActiveIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE);
364            termValues.put(OLEConstants.PATRON_ACTIVATION_DATE, oleLoanDocumentProxyToReal.getOlePatron().getActivationDate());
365        }
366        termValues.put(OLEConstants.ACTIVATION_DATE_STRING, oleLoanDocument.getOlePatron().getActivationDate() != null ? oleLoanDocument.getOlePatron().getActivationDate().toString() : "null");
367        termValues.put(OLEConstants.EXPIRATION_DATE_STRING, oleLoanDocument.getOlePatron().getExpirationDate() != null ? oleLoanDocument.getOlePatron().getExpirationDate().toString() : "null");
368        termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
369        termValues.put(OLEConstants.PATTERN, pattern);
370        Long t1 = System.currentTimeMillis();
371        EngineResults engineResults = getEngineResults(agendaName, termValues);
372        Long t2 = System.currentTimeMillis();
373        Long t3 = t2 - t1;
374        LOG.info("Time taken for Patron KRMS"+t3);
375        HashMap<String, String> errorsAndPermission = new HashMap<>();
376        errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
377        StringBuffer failures = new StringBuffer();
378        oleLoanDocument.getErrorsAndPermission().clear();
379        int i = 1;
380        if (errorsAndPermission != null) {
381            Set<String> errorMessage = errorsAndPermission.keySet();
382            if (errorMessage != null && errorMessage.size() > 0) {
383                //TODO KRMS Code Cleanup
384                for (String errMsg : errorMessage) {
385                    if (StringUtils.isNotEmpty(errMsg)) {
386                        oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
387                        if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
388                            failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
389                            oleLoanDocument.setBlockLoan(true);
390                        } else {
391                            if (oleLoanDocument.getOlePatron().isGeneralBlock()) {
392                                if (errMsg.equalsIgnoreCase(OLEConstants.GENERAL_BLOCK_MESSAGE)) {
393                                    failures.append(i++ + ". " + errMsg + " " + OLEConstants.SEMI_COLON + " " + oleLoanDocument.getOlePatron().getGeneralBlockNotes() + OLEConstants.BREAK);
394                                } else {
395                                    failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
396                                }
397                            } else {
398                                failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
399                            }
400
401                        }
402                    }
403                }
404            }
405            errorsAndPermission.clear();
406        }
407        List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
408        if (errorMessage != null && errorMessage.size() > 0) {
409            for (String errMsg : errorMessage) {
410                if (StringUtils.isNotEmpty(errMsg)) {
411                    if (errMsg.contains(OLEConstants.LOST_STOLEN)) {
412                        failures.append(OLEConstants.H4 + i++ + ". " + errMsg + OLEConstants.H4_CLOSE);
413                        oleLoanDocument.setBlockLoan(true);
414                    } else {
415                        failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
416                    }
417                }
418            }
419        }
420        if (!failures.toString().isEmpty()) {
421            oleLoanDocument.setErrorMessage(failures.toString());
422        }
423        getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
424        getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
425        Long b2 = System.currentTimeMillis();
426        Long b3 = b2-b1;
427        LOG.info("The time taken inside getLoanDocument method"+b3);
428        return oleLoanDocument;
429    }
430
431
432    /**
433     * Checks whether the patron barcode is Lost/Stolen.
434     *
435     * @param barcode
436     * @return
437     * @throws Exception
438     */
439    private boolean checkLostPatronBarcode(String barcode) throws Exception {
440        LOG.debug("Inside the checkLostPatronBarcode method");
441        Map barMap = new HashMap();
442        barMap.put("invalidOrLostBarcodeNumber", barcode);
443        List<OlePatronLostBarcode> olePatronLostBarcodes = (List<OlePatronLostBarcode>) getBusinessObjectService().findMatching(OlePatronLostBarcode.class, barMap);
444        boolean lostInvalidBarcode = false;
445        if (olePatronLostBarcodes != null) {
446            for (int lostBarcode = 0; lostBarcode < olePatronLostBarcodes.size(); lostBarcode++) {
447                OlePatronLostBarcode olePatronLostBarcode = (OlePatronLostBarcode) olePatronLostBarcodes.get(lostBarcode);
448                if (olePatronLostBarcode.getInvalidOrLostBarcodeNumber().equals(barcode) && (!olePatronLostBarcode.isActive())) {
449                    setLostDescription(olePatronLostBarcode.getDescription());
450                    setLostStatus(olePatronLostBarcode.getStatus());
451                    lostInvalidBarcode = true;
452                    setLostPatronId(olePatronLostBarcode.getOlePatronId());
453                    return lostInvalidBarcode;
454                }
455            }
456        }
457        return lostInvalidBarcode;
458    }
459
460    /**
461     * Retrieves Patron preferred address.
462     *
463     * @param entityTypeContactInfoBo
464     * @param loanDocument
465     * @return
466     * @throws Exception
467     */
468    private OleLoanDocument getPatronPreferredAddress(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
469        LOG.debug("Inside the getPatronPreferredAddress method");
470        if (entityTypeContactInfoBo.getAddresses() != null) {
471            for (EntityAddressBo entityAddressBo : entityTypeContactInfoBo.getAddresses()) {
472                if (entityAddressBo.isDefaultValue()) {
473                    String address = "";
474                    if (entityAddressBo.getLine1() != null) {
475                        if (!entityAddressBo.getLine1().isEmpty()) {
476                            address += entityAddressBo.getLine1() + OLEConstants.COMMA;
477                        }
478                    }
479
480                    if (entityAddressBo.getLine2() != null) {
481                        if (!entityAddressBo.getLine2().isEmpty()) {
482                            address += entityAddressBo.getLine2() + OLEConstants.COMMA;
483                        }
484                    }
485
486                    if (entityAddressBo.getLine3() != null) {
487                        if (!entityAddressBo.getLine3().isEmpty()) {
488                            address += entityAddressBo.getLine3() + OLEConstants.COMMA;
489                        }
490                    }
491
492                    if (entityAddressBo.getCity() != null) {
493                        if (!entityAddressBo.getCity().isEmpty()) {
494                            address += entityAddressBo.getCity() + OLEConstants.COMMA;
495                        }
496                    }
497
498                    if (entityAddressBo.getStateProvinceCode() != null) {
499                        if (!entityAddressBo.getStateProvinceCode().isEmpty()) {
500                            address += entityAddressBo.getStateProvinceCode() + OLEConstants.COMMA;
501                        }
502                    }
503
504                    if (entityAddressBo.getCountryCode() != null) {
505                        if (!entityAddressBo.getCountryCode().isEmpty()) {
506                            address += entityAddressBo.getCountryCode() + OLEConstants.COMMA;
507                        }
508                    }
509
510                    if (entityAddressBo.getPostalCode() != null) {
511                        if (!entityAddressBo.getPostalCode().isEmpty()) {
512                            address += entityAddressBo.getPostalCode();
513                        }
514                    }
515
516                    loanDocument.setPreferredAddress(address);
517                    break;
518                }
519            }
520        }
521
522        return loanDocument;
523    }
524
525    /**
526     * Retrieves Patron home phone number.
527     *
528     * @param entityTypeContactInfoBo
529     * @param loanDocument
530     * @return
531     * @throws Exception
532     */
533    private OleLoanDocument getPatronHomePhoneNumber(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
534        LOG.debug("Inside the getPatronHomePhoneNumber method");
535        if (entityTypeContactInfoBo.getPhoneNumbers() != null) {
536            for (EntityPhoneBo entityPhoneBo : entityTypeContactInfoBo.getPhoneNumbers()) {
537                if (entityPhoneBo.isDefaultValue()) {
538                    loanDocument.setPhoneNumber(entityPhoneBo.getPhoneNumber());
539                    break;
540                }
541            }
542        }
543        return loanDocument;
544    }
545
546    /**
547     * Retrieves Patron home email id.
548     *
549     * @param entityTypeContactInfoBo
550     * @param loanDocument
551     * @return
552     * @throws Exception
553     */
554    private OleLoanDocument getPatronHomeEmailId(EntityTypeContactInfoBo entityTypeContactInfoBo, OleLoanDocument loanDocument) throws Exception {
555        LOG.debug("Inside the getPatronHomeEmailId method");
556        if (entityTypeContactInfoBo.getEmailAddresses() != null) {
557            for (EntityEmailBo entityEmailBo : entityTypeContactInfoBo.getEmailAddresses()) {
558                if (entityEmailBo.isDefaultValue()) {
559                    loanDocument.setEmail(entityEmailBo.getEmailAddress());
560                    break;
561                }
562            }
563        }
564        return loanDocument;
565    }
566
567    /**
568     * Retrieves Patron user note.
569     *
570     * @param olePatronNotes
571     * @param loanDocument
572     * @return
573     * @throws Exception
574     */
575    private OleLoanDocument getPatronNote(List<OlePatronNotes> olePatronNotes, OleLoanDocument loanDocument) throws Exception {
576        LOG.debug("Inside the getPatronNote method");
577        for (OlePatronNotes patronNotes : olePatronNotes) {
578            if (patronNotes.getOlePatronNoteType() != null) {
579                if (patronNotes.getOlePatronNoteType().getPatronNoteTypeCode().equalsIgnoreCase(OLEConstants.USER)) {
580                    loanDocument.setPatronUserNotes(patronNotes.getPatronNoteText());
581                    loanDocument.setPatronNoteTypeId((String) patronNotes.getPatronNoteTypeId());
582                    break;
583                }
584            }
585        }
586        return loanDocument;
587    }
588
589    /**
590     * This method returns Patron information using patron barcode.
591     *
592     * @param barcode
593     * @return loanDocument
594     * @throws Exception
595     */
596    private OleLoanDocument getPatronBarcodeRecord(String barcode) throws Exception {
597        LOG.debug("Inside the getPatronBarcodeRecord method");
598        OleLoanDocument loanDocument = new OleLoanDocument();
599        StringBuffer values_StringBuffer = new StringBuffer();
600        try {
601            Map barMap = new HashMap();
602            barMap.put(OLEConstants.OlePatron.BARCODE, barcode);
603            List<OlePatronDocument> matching = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
604            List<OleLoanDocument> loanDocuments = matching.get(0).getOleLoanDocumentsFromDb();
605            List<OleLoanDocument> LoanDocumentList = new ArrayList<>();
606            List<OleLoanDocument> indefiniteLoanDocumentList = new ArrayList<>();
607            for (OleLoanDocument loanDoc : loanDocuments) {
608                if (loanDoc.getLoanDueDate() != null && !(loanDoc.getLoanDueDate().toString().isEmpty())) {
609                    LoanDocumentList.add(loanDoc);
610                } else {
611                    indefiniteLoanDocumentList.add(loanDoc);
612                }
613            }
614            Collections.sort(LoanDocumentList, new Comparator<OleLoanDocument>() {
615                public int compare(OleLoanDocument o1, OleLoanDocument o2) {
616                    return o1.getLoanDueDate().compareTo(o2.getLoanDueDate());
617                }
618            });
619            LoanDocumentList.addAll(indefiniteLoanDocumentList);
620            if (matching != null && matching.size() > 0) {
621                OlePatronDocument olePatronDocument = matching.get(0);
622                olePatronDocument.setOleLoanDocuments(LoanDocumentList);
623                loanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
624                OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
625                loanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
626                loanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
627                EntityBo entityBo = olePatronDocument.getEntity();
628                loanDocument.setPatronName(getPatronName(entityBo));
629                loanDocument.setPatronId(olePatronDocument.getOlePatronId());
630                List<OlePatronNotes> olePatronNotes = olePatronDocument.getNotes();
631                if (olePatronNotes != null) {
632                    loanDocument = getPatronNote(olePatronNotes, loanDocument);
633                }
634                EntityTypeContactInfoBo entityTypeContactInfoBo = entityBo!=null ? entityBo.getEntityTypeContactInfos().get(0) : null;
635                if (entityTypeContactInfoBo != null) {
636                    loanDocument = getPatronPreferredAddress(entityTypeContactInfoBo, loanDocument);
637                    loanDocument = getPatronHomePhoneNumber(entityTypeContactInfoBo, loanDocument);
638                    loanDocument = getPatronHomeEmailId(entityTypeContactInfoBo, loanDocument);
639                }
640                loanDocument.setOlePatron(olePatronDocument);
641                return loanDocument;
642            } else {
643                LOG.error(OLEConstants.PTRN_BARCD_NOT_EXT);
644                throw new Exception(OLEConstants.PTRN_BARCD_NOT_EXT);
645            }
646        } catch (Exception e) {
647            LOG.error(OLEConstants.PTRN_BARCD_NOT_EXT + e, e);
648            values_StringBuffer.append(OLEConstants.PTRN_BARCD_NOT_EXT + "  " + OLEConstants.PTRN_START_LINK + ConfigContext.getCurrentContextConfig().getProperty("ole.fs.url.base") + OLEConstants.PTRN_END_LINK);
649            throw new Exception(values_StringBuffer.toString());
650        }
651
652    }
653
654    /**
655     * This method returns BorrowerTypeName using borrowerId
656     *
657     * @param borrowerId
658     * @return String
659     */
660    public OleBorrowerType getborrowerTypeName(String borrowerId) {
661        LOG.debug("Inside the getborrowerTypeName method");
662        OleBorrowerType oleBorrowerType = getBusinessObjectService().findBySinglePrimaryKey(OleBorrowerType.class, borrowerId);
663        return oleBorrowerType;
664    }
665
666    /**
667     * This method returns PatronName using entityId
668     *
669     * @param entityId
670     * @return String
671     */
672    private String getPatronName(String entityId) {
673        LOG.debug("Inside the getPatronName method");
674        Map barMap = new HashMap();
675        barMap.put(OLEConstants.ENTITY_ID, entityId);
676        List<EntityNameBo> entityNameBo = (List<EntityNameBo>) getBusinessObjectService().findMatching(EntityNameBo.class, barMap);
677        return entityNameBo.get(0).getFirstName() + " " + entityNameBo.get(0).getLastName();
678    }
679
680    /**
681     * This method returns PatronName using entityBo
682     *
683     * @param entityBo
684     * @return String
685     */
686    public String getPatronName(EntityBo entityBo) {
687        LOG.debug("Inside the getPatronName method");
688        List<EntityNameBo> entityNameBo = entityBo.getNames();
689        return entityNameBo!=null && entityNameBo.size() > 0 ? entityNameBo.get(0).getFirstName() + " " + entityNameBo.get(0).getLastName() : "";
690    }
691
692    public org.kuali.ole.docstore.common.document.content.instance.Item checkItemStatusForItemBarcode(String itemBarcode)throws Exception{
693        SearchResponse searchResponse = new SearchResponse();
694        SearchParams searchParams = new SearchParams();
695        List<SearchCondition> searchConditions = new ArrayList<>();
696        searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", "AVAILABLE"), "AND"));
697        searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", "RECENTLY-RETURNED"), "OR"));
698        searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", "UNAVAILABLE"), "OR"));
699        searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", "INPROCESS"), "OR"));
700        searchConditions.add(searchParams.buildSearchCondition("", searchParams.buildSearchField("item", "ItemStatus_search", "ONORDER"), "OR"));
701        searchConditions.add(searchParams.buildSearchCondition("phrase", searchParams.buildSearchField("item", "ItemBarcode_search", itemBarcode), "AND"));
702        SearchParmsBuilder.buildSearchParams(searchParams);
703        searchParams.getSearchConditions().addAll(searchConditions);
704        searchResponse = getDocstoreClientLocator().getDocstoreClient().search(searchParams);
705        String itemUUID = null;
706        if(searchResponse!=null) {
707            for (SearchResult searchResult : searchResponse.getSearchResults()) {
708                for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
709                    if (searchResultField.getFieldValue() != null) {
710                        if (searchResultField.getFieldName().equalsIgnoreCase("id")) {
711                            itemUUID = searchResultField.getFieldValue();
712                            break;
713                        }
714                    }
715                }
716            }
717        }
718
719        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = null;
720        String itemXml = null;
721        org.kuali.ole.docstore.common.document.Item item = null;
722        item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
723        itemXml = item.getContent()!=null ? item.getContent() : getItemXML(itemUUID);
724        oleItem = getItemPojo(itemXml);
725        return oleItem;
726    }
727
728    public void rollbackItemStatus(org.kuali.ole.docstore.common.document.content.instance.Item oleItem,String itemStatus,String itemBarcode) throws Exception{
729        Map barMap = new HashMap();
730        barMap.put("itemId", itemBarcode);
731        List<OleLoanDocument> matchingLoan = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
732        if(matchingLoan != null && matchingLoan.size()>0){
733            //oleItem.setCheckOutDateTime(convertToString());
734            oleItem.setDueDateTime(convertToString(matchingLoan.get(0).getLoanDueDate()));
735            if(StringUtils.isNotBlank(matchingLoan.get(0).getPatronId())) {
736                oleItem.setCurrentBorrower(matchingLoan.get(0).getPatronId());
737            }
738            if(StringUtils.isNotBlank(matchingLoan.get(0).getProxyPatronId())) {
739                oleItem.setProxyBorrower(matchingLoan.get(0).getProxyPatronId());
740            }
741        }
742        updateItemStatus(oleItem,itemStatus);
743    }
744
745    private String getPatronBarcodeByPatronId(String patronId) throws Exception{
746        Map barMap = new HashMap();
747        barMap.put("olePatronId", patronId);
748        List<OlePatronDocument> patronDocument = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
749        if(patronDocument != null && patronDocument.size()>0){
750            return patronDocument.get(0).getBarcode();
751        }
752        return null;
753    }
754
755
756    /**
757     * This method returns PatronRequestRecords  using patronId
758     *
759     * @param patronId
760     * @return List
761     * @throws Exception
762     */
763    public List<OleDeliverRequestBo> getPatronRequestRecords(String patronId) throws Exception {
764        LOG.debug("Inside the getPatronRequestRecords method");
765        Map barMap = new HashMap();
766        barMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, patronId);
767        List<OleDeliverRequestBo> matchingLoan = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, barMap);
768
769        for (int itemid = 0; itemid < matchingLoan.size(); itemid++) {
770            String itemUuid = matchingLoan.get(itemid).getItemUuid();
771
772
773            org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
774            org.kuali.ole.docstore.common.document.content.instance.Item itemContent = getItemOlemlRecordProcessor().fromXML(item.getContent());
775            HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
776            OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(item.getHolding().getContent());
777            OleDeliverRequestBo oleDeliverRequestBo = matchingLoan.get(itemid);
778            if (oleDeliverRequestBo.getItemUuid().equals(item.getId())) {
779                oleDeliverRequestBo.setTitle(item.getHolding().getBib().getTitle());
780                oleDeliverRequestBo.setAuthor(item.getHolding().getBib().getAuthor());
781                oleDeliverRequestBo.setCallNumber(getItemCallNumber(itemContent.getCallNumber(),oleHoldings.getCallNumber()));
782                oleDeliverRequestBo.setCopyNumber(itemContent.getCopyNumber());
783                oleDeliverRequestBo.setVolumeNumber(itemContent.getVolumeNumber());
784                oleDeliverRequestBo.setItemStatus(itemContent.getItemStatus().getCodeValue());
785                oleDeliverRequestBo.setItemType(itemContent.getItemType().getCodeValue());
786                if (oleDeliverRequestBo.getCirculationLocationCode() != null && !oleDeliverRequestBo.getCirculationLocationCode().equals("")) {
787                    LocationValuesBuilder locationValuesBuilder = new LocationValuesBuilder();
788                    locationValuesBuilder.getLocation(itemContent, oleDeliverRequestBo, item.getHolding().getId());
789                   /* oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(itemContent.getLocation().getLocationLevel().getName()));
790                    if (oleDeliverRequestBo.getShelvingLocation() == null || (oleDeliverRequestBo.getShelvingLocation() != null && oleDeliverRequestBo.getShelvingLocation().isEmpty())) {
791
792
793                        oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleHoldings.getLocation().getLocationLevel().getName()));
794                    }*/
795                }
796                break;
797            }
798        }
799        return matchingLoan;
800    }
801
802   /* public String getShelvingLocation(LocationLevel oleLocationLevel) {
803        String location = null;
804        if (oleLocationLevel != null) {
805            if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
806                location = oleLocationLevel.getName();
807        } else {
808            location = getShelvingLocation(oleLocationLevel.getLocationLevel());
809        }
810        if ("".equals(location) || location == null) {
811            return null;
812        }
813        return location;
814    }*/
815
816    public String getItemCallNumber(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String instanceUUID) throws Exception {
817       /* CallNumber callNumber = null;
818        if (oleItem.getCallNumber() != null && oleItem.getCallNumber().getNumber() != null && !oleItem.getCallNumber().getNumber().isEmpty()) {
819            callNumber = oleItem.getCallNumber();
820        } else {
821            OleHoldings oleHoldings = getOleHoldings(instanceUUID);
822            callNumber = oleHoldings.getCallNumber();
823        }*/
824        OleHoldings oleHoldings = getOleHoldings(instanceUUID);
825        return getItemCallNumber(oleItem.getCallNumber(),oleHoldings.getCallNumber());
826    }
827
828    /**
829     * Retrieves Item call number.
830     *
831     * @param itemCallNumber,holdingCallNumber
832     * @return
833     * @throws Exception
834     */
835    public String getItemCallNumber(CallNumber itemCallNumber,CallNumber holdingCallNumber) throws Exception {
836        LOG.debug("Inside the getItemCallNumber method");
837        String callNumber = "";
838
839            if (itemCallNumber != null && StringUtils.isNotBlank(itemCallNumber.getType())) {
840                callNumber += itemCallNumber.getType() + OLEConstants.DELIMITER_DASH;
841            }else if(holdingCallNumber != null && StringUtils.isNotBlank(holdingCallNumber.getType())){
842                callNumber += holdingCallNumber.getType() + OLEConstants.DELIMITER_DASH;
843            }
844            if (itemCallNumber != null && StringUtils.isNotBlank(itemCallNumber.getPrefix())) {
845                callNumber += itemCallNumber.getPrefix() + OLEConstants.DELIMITER_DASH;
846            }else if(holdingCallNumber != null && StringUtils.isNotBlank(holdingCallNumber.getPrefix())){
847                callNumber += holdingCallNumber.getPrefix() + OLEConstants.DELIMITER_DASH;
848            }
849            if (itemCallNumber != null && StringUtils.isNotBlank(itemCallNumber.getNumber())) {
850                callNumber += itemCallNumber.getNumber();
851            }else if(holdingCallNumber != null && StringUtils.isNotBlank(holdingCallNumber.getNumber())){
852                callNumber += holdingCallNumber.getNumber();
853            }
854
855        return callNumber;
856    }
857
858    /**
859     * Retrieves item xml using itemuuid.
860     *
861     * @param itemUUID
862     * @return
863     * @throws Exception
864     */
865    public String getItemXML(String itemUUID) throws Exception {
866        LOG.debug("Inside the getItemXML method");
867        String itemXml = "";
868        try {
869            org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
870            item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
871            itemXml = item.getContent();
872            if (LOG.isDebugEnabled()){
873                LOG.debug("item XML ----- > " + itemXml);
874            }
875        } catch (Exception e) {
876            LOG.error(OLEConstants.ITM_BARCD_NT_AVAL_DOC, e);
877            throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
878        }
879        return itemXml;
880    }
881
882    /**
883     * Converts item xml to item pojo.
884     *
885     * @param itemXml
886     * @return
887     * @throws Exception
888     */
889    public org.kuali.ole.docstore.common.document.content.instance.Item getItemPojo(String itemXml) throws Exception {
890        LOG.debug("Inside the getItemPojo method");
891        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = null;
892        try {
893            oleItem = getItemOlemlRecordProcessor().fromXML(itemXml);
894        } catch (Exception e) {
895            LOG.error(OLEConstants.PAR_EXP, e);
896            throw new Exception(OLEConstants.PAR_EXP);
897        }
898        return oleItem;
899    }
900
901    public void getDefaultHoldingLocation(OleLoanDocument oleLoanDocument) throws Exception {
902        try {
903            OleHoldings oleHoldings = getOleHoldings(oleLoanDocument.getInstanceUuid());
904            if (oleHoldings != null) {
905                Location physicalLocation = oleHoldings.getLocation();
906                LocationLevel locationLevel = null;
907                locationLevel = physicalLocation.getLocationLevel();
908                populateLocation(oleLoanDocument, locationLevel);
909            }
910        } catch (Exception holdingException) {
911            LOG.error("--------------Invalid Holding location data.---------------", holdingException);
912
913            throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
914        }
915    }
916
917    private void getCopyNumber( org.kuali.ole.docstore.common.document.content.instance.Item  item,OleHoldings oleHoldings,OleLoanDocument oleLoanDocument) throws Exception{
918        if(item.getCopyNumber()!=null && !item.getCopyNumber().equals("")){
919            oleLoanDocument.setItemCopyNumber(item.getCopyNumber());
920        }else if(oleHoldings.getCopyNumber() != null && !oleHoldings.getCopyNumber().equals("")){
921            oleLoanDocument.setItemCopyNumber(oleHoldings.getCopyNumber());
922        }
923    }
924
925    /**
926     * Retrieved item object from docstore using itemid .Fetch location code,item available status from item object and
927     * retrieve title from bib object.
928     *
929     * @param patronBarcode
930     * @param itemBarcode
931     * @param oleLoanDocument
932     * @return OleLoanDocument
933     */
934    public OleLoanDocument addLoan(String patronBarcode, String itemBarcode, OleLoanDocument oleLoanDocument,String operatorId) throws Exception {
935
936        LOG.debug("Inside the addLoan method");
937        String itemUUID= oleLoanDocument.getItemUuid();
938        String bibTitle = null;
939        String bibauthor = null;
940        String holdingsId = null;
941        Long begin = System.currentTimeMillis();
942        if(itemUUID==null){
943            try {
944                org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
945                org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
946                SearchResponse searchResponse = null;
947                search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, itemBarcode), ""));
948                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "id"));
949                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "Title_display"));
950//                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.HOLDINGS.getCode(), "id"));
951                searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
952                for (SearchResult searchResult : searchResponse.getSearchResults()) {
953                    for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
954                        if (searchResultField.getFieldName().equalsIgnoreCase("id")) {
955                            String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
956                            itemUUID = fieldValue;
957                        } else if (searchResultField.getFieldName().equalsIgnoreCase("Title_display")) {
958                            bibTitle = searchResultField.getFieldValue();
959                        } else if (searchResultField.getFieldName().equalsIgnoreCase("Author_display")) {
960                            bibauthor = searchResultField.getFieldValue();
961                        }
962                        oleLoanDocument.setItemUuid(itemUUID);
963//                        if (fieldName.equalsIgnoreCase("id") && !fieldValue.isEmpty() && searchResultField.getDocType().equalsIgnoreCase("holdings")) {
964//                            holdingsId = fieldValue;
965//                        } else {
966//                        }
967                    }
968                }
969                if(searchResponse.getSearchResults()!= null && searchResponse.getSearchResults().size() == 0){
970                    oleLoanDocument.setErrorMessage(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.ITEM_BARCODE_DOESNOT_EXISTS));
971                    return oleLoanDocument;
972                }
973            } catch (Exception ex) {
974                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, "Item Exists");
975                LOG.error(OLEConstants.ITEM_EXIST + ex);
976            }
977        }
978        Map<String,Object> detailMap = getOleDeliverRequestDocumentHelperService().retrieveBIbItemHoldingData(itemUUID);
979        Bib bib = (Bib)detailMap.get(OLEConstants.BIB);
980        if(bib != null) {
981            oleLoanDocument.setTitle(bib.getTitle());
982            oleLoanDocument.setAuthor(bib.getAuthor());
983        }
984        if(StringUtils.isNotEmpty(bibauthor)){
985           oleLoanDocument.setAuthor(bibauthor);
986        }
987        if (StringUtils.isNotEmpty(bibTitle)) {
988            oleLoanDocument.setTitle(bibTitle);
989        }
990        if(itemUUID!=null) {
991            Bib bibDetail=getDocstoreClientLocator().getDocstoreClient().retrieveBib(bib.getId()) ;
992            oleLoanDocument.setTitle(bibDetail.getTitle());
993            oleLoanDocument.setAuthor(bibDetail.getAuthor());
994        }
995        org.kuali.ole.docstore.common.document.content.instance.Item item = (org.kuali.ole.docstore.common.document.content.instance.Item)detailMap.get(OLEConstants.ITEM);
996        OleHoldings oleHoldings = (OleHoldings)detailMap.get(OLEConstants.HOLDING);
997        org.kuali.ole.docstore.common.document.Item item1 = (org.kuali.ole.docstore.common.document.Item)detailMap.get("documentItem");
998        oleLoanDocument.setInstanceUuid(oleHoldings.getHoldingsIdentifier());
999        Long end = System.currentTimeMillis();
1000        Long timeTaken = end-begin;
1001        LOG.info("The Time Taken for Docstore call in Add Item"+timeTaken);
1002        Date pastDueDate = oleLoanDocument.getLoanDueDate();
1003        boolean itemValidation = itemValidation(item);
1004        if (!itemValidation) {
1005            if (oleLoanDocument.isRenewalItemFlag()) {
1006                oleLoanDocument.setErrorMessage(OLEConstants.INVAL_ITEM);
1007                return oleLoanDocument;
1008            } else {
1009                throw new Exception(OLEConstants.INVAL_ITEM);
1010            }
1011        }
1012        oleLoanDocument.setOleItem(item);
1013        try {
1014            getCopyNumber(item,oleHoldings,oleLoanDocument);
1015            oleLoanDocument.setItemCallNumber(getItemCallNumber(item.getCallNumber(),oleHoldings.getCallNumber()));
1016            /*if(item.getCallNumber()!=null && !StringUtils.isEmpty(item.getCallNumber().getNumber())){
1017                oleLoanDocument.setItemCallNumber(getItemCallNumber(item.getCallNumber()));
1018            }else {
1019                oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
1020            }*/
1021            oleLoanDocument.setEnumeration(item.getEnumeration());
1022            oleLoanDocument.setChronology(item.getChronology());
1023            String status = item.getItemStatus().getCodeValue();
1024            oleLoanDocument.setItemLoanStatus(status);
1025        } catch (Exception e) {
1026            LOG.error(OLEConstants.ITM_STS_NT_AVAL, e);
1027            if (oleLoanDocument.isRenewalItemFlag()) {
1028                oleLoanDocument.setErrorMessage(OLEConstants.ITM_STS_NT_AVAL);
1029                return oleLoanDocument;
1030            } else {
1031                throw new Exception(OLEConstants.ITM_STS_NT_AVAL);
1032            }
1033        }
1034        oleLoanDocument.setItemId(itemBarcode);
1035        oleLoanDocument.setMissingPieceFlag(item.isMissingPieceFlag());
1036        oleLoanDocument.setMissingPiecesCount(item.getMissingPiecesCount());
1037        try {
1038            if (item.getTemporaryItemType() != null && item.getTemporaryItemType().getCodeValue() != "") {
1039                OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(item.getTemporaryItemType().getCodeValue());
1040                oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
1041                oleLoanDocument.setItemType(oleInstanceItemType.getInstanceItemTypeCode());
1042                oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
1043            }
1044            else if (item.getItemType() != null && item.getItemType().getCodeValue() != "") {
1045                OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(item.getItemType().getCodeValue());
1046                oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
1047                oleLoanDocument.setItemType(oleInstanceItemType.getInstanceItemTypeCode());
1048                oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
1049            }
1050        } catch (Exception e) {
1051            LOG.error(OLEConstants.INVAL_ITEM, e);
1052            throw new Exception(OLEConstants.INVAL_ITEM);
1053        }
1054        Long beginLocation = System.currentTimeMillis();
1055        getLocation(item, oleLoanDocument,item1);
1056        if (oleLoanDocument.getLocation() == null || oleLoanDocument.getLocation().isEmpty()) {
1057            getDefaultHoldingLocation(oleLoanDocument);
1058        }
1059        Long endLocation = System.currentTimeMillis();
1060        Long timeTakenLocation = endLocation-beginLocation;
1061        LOG.info("The Time Taken for Location call in Add Item"+timeTakenLocation);
1062        setLoan(oleLoanDocument);
1063        oleLoanDocument.setPatronBarcode(patronBarcode);
1064    /*    HashMap overdueItems = new HashMap();*/
1065      /*  Integer loanedItems = 0;*/
1066        Date expirationDate = null;
1067        Integer numberOfClaimsReturned = 0;
1068        String patronType = "";
1069        HashMap keyLoanMap = new HashMap();
1070
1071        if (oleLoanDocument.getProxyPatronId() != null) {
1072            // Checking for real patron.
1073            keyLoanMap=getOleCirculationPolicyService().getLoanedKeyMap(oleLoanDocument.getProxyPatronId(),oleLoanDocument.isRenewalItemFlag());
1074            expirationDate = getOleCirculationPolicyService().getPatronMembershipExpireDate(oleLoanDocument.getRealPatronBarcode());
1075            /**
1076             * For performance issue I commenting the below code. The number of claims will be recorded in the patron document.
1077             */
1078           // OlePatronDocument olePatronDocument = (OlePatronDocument) keyLoanMap.get("patronDetails");
1079            numberOfClaimsReturned = (Integer)keyLoanMap.get("claimsCount"); //oleCirculationPolicyService.getNumberOfClaimsReturned(oleLoanDocument.getProxyPatronId());
1080            patronType = oleLoanDocument.getRealPatronType();
1081
1082        } else {
1083            keyLoanMap=getOleCirculationPolicyService().getLoanedKeyMap(oleLoanDocument.getPatronId(),oleLoanDocument.isRenewalItemFlag());
1084            if (oleLoanDocument.getOlePatron() != null && oleLoanDocument.getOlePatron().getBarcode().equalsIgnoreCase(oleLoanDocument.getPatronBarcode())) {
1085                expirationDate=oleLoanDocument.getOlePatron().getExpirationDate();
1086            } else {
1087                expirationDate = getOleCirculationPolicyService().getPatronMembershipExpireDate(oleLoanDocument.getPatronBarcode());
1088            }
1089            /**
1090             * For performance issue I commenting the below code. The number of claims will be recorded in the patron document.
1091             */
1092           // OlePatronDocument olePatronDocument = (OlePatronDocument) keyLoanMap.get("patronDetails");
1093            numberOfClaimsReturned = (Integer)keyLoanMap.get("claimsCount");
1094            patronType = oleLoanDocument.getBorrowerTypeCode();
1095
1096        }
1097
1098
1099        oleLoanDocument.setExpirationDate(expirationDate);
1100        StringBuffer failures = new StringBuffer();
1101        List<FeeType> feeTypeList = oleCirculationPolicyService.getPatronBillPayment(oleLoanDocument.getPatronId());
1102
1103        List<Integer> listOfOverDueDays = (List<Integer>)keyLoanMap.get(OLEConstants.LIST_OF_OVERDUE_DAYS);
1104        getDataCarrierService().addData(OLEConstants.LIST_OVERDUE_DAYS, listOfOverDueDays);
1105        getDataCarrierService().addData(OLEConstants.HOURS_DIFF, oleCirculationPolicyService.getHoursDiff(oleLoanDocument.getLoanDueDate(), new Date()));
1106        getDataCarrierService().addData(OLEConstants.DUEDATE, oleLoanDocument.getLoanDueDate());
1107        getDataCarrierService().addData(OLEConstants.CHECKINDATE, oleLoanDocument.getCheckInDate());
1108        getDataCarrierService().addData(OLEConstants.LIST_RECALLED_OVERDUE_DAYS, (List<Integer>) keyLoanMap.get(OLEConstants.LIST_RECALLED_OVERDUE_DAYS));
1109        String patronId = oleLoanDocument.getPatronId()!=null ?  oleLoanDocument.getPatronId() : "";
1110        String itemId = oleLoanDocument.getItemId()!=null ?  oleLoanDocument.getItemId() : "";
1111        getDataCarrierService().removeData(patronId + itemId);
1112        if (oleLoanDocument.isRenewalItemFlag()) {
1113            getDataCarrierService().addData(OLEConstants.EXCLUDE_TIME, true);
1114        }
1115        HashMap<String,Integer> itemTypeMap  = (HashMap<String, Integer>) keyLoanMap.get("itemTypeMap");
1116        getDataCarrierService().addData("itemTypeMap", getItemTypeFromCurrentLoan(itemTypeMap, oleLoanDocument));
1117        Integer overdueFineAmt = 0;
1118        Integer replacementFeeAmt = 0;
1119        Integer serviceFeeAmt = 0;
1120        for (FeeType feeType : feeTypeList) {
1121            Integer fineAmount = feeType.getFeeAmount().subtract(feeType.getPaidAmount()).intValue();
1122            overdueFineAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.OVERDUE_FINE) ? fineAmount : 0;
1123            replacementFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.REPLACEMENT_FEE) ? fineAmount : 0;
1124            serviceFeeAmt += feeType.getOleFeeType().getFeeTypeName().equalsIgnoreCase(OLEConstants.SERVICE_FEE) ? fineAmount : 0;
1125        }
1126
1127        OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
1128        oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
1129      /* if (oleCirculationDesk != null && oleCirculationDesk.getCalendarGroupId() != null) {
1130            OleCalendarService oleCalendarService = new OleCalendarServiceImpl();
1131            OleCalendar oleCalendar = oleCalendarService.getActiveCalendar(new Timestamp(System.currentTimeMillis()), oleCirculationDesk.getCalendarGroupId());
1132            if (oleCalendar == null) {
1133                throw new Exception("Calendar does not exist");
1134            }
1135        }
1136        getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");*/
1137        getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");
1138        String operatorsCirculationLocation = getCircDeskLocationResolver().circulationDeskLocations(oleCirculationDesk);
1139        if (LOG.isDebugEnabled()){
1140            LOG.debug("operatorsCirculationLocation---->" + operatorsCirculationLocation);
1141        }
1142        String requestType = null;
1143        OlePatronDocument oleRequestPatron = null;
1144        String requestPatronId=null;
1145        OleDeliverRequestBo oleDeliverRequestForQueue = null;
1146        if(!oleLoanDocument.isVuFindFlag()){
1147            OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
1148            if (oleDeliverRequestBo != null) {
1149                oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo);
1150                requestType = oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode();
1151                oleRequestPatron = getOlePatronDocument(oleDeliverRequestBo.getBorrowerId());
1152                oleLoanDocument.setOleRequestPatron(oleRequestPatron);
1153                requestPatronId = oleRequestPatron != null ? oleRequestPatron.getOlePatronId() : null;
1154                if (oleLoanDocument.getPatronId().equals(requestPatronId) || (oleLoanDocument.getProxyPatronId() != null && oleLoanDocument.getProxyPatronId().equals(requestPatronId))) {
1155                    oleLoanDocument.setRequestPatron(true);
1156                    oleLoanDocument.setOleRequestId(oleDeliverRequestBo.getRequestId());
1157                } else {
1158                    oleDeliverRequestForQueue = getCurrentQueue(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid());
1159                    oleLoanDocument.setOleRequestId(oleDeliverRequestForQueue != null ? oleDeliverRequestForQueue.getRequestId() : null);
1160                }
1161               if(getOleDeliverRequestDocumentHelperService().getRequestByItem(oleLoanDocument.getItemId()).size() > 1){
1162                oleLoanDocument.setRequestFlag(OLEConstants.VIEW_ALL_REQUESTS);
1163               }
1164            }
1165        }
1166
1167        String digitRoutine = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE);
1168        String pattern = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE_PATTERN);
1169        String itemCircLoction = getCircDeskLocationResolver().getFullPathLocation(getCircDeskLocationResolver().getLocationByLocationCode(oleLoanDocument.getItemLocation()), getCircDeskLocationResolver().getLocationLevelIds());
1170        DateFormat formatter = new SimpleDateFormat(OLEConstants.DDMMYYYYHHMMSS);
1171        Date loanDueDate = oleLoanDocument.getLoanDueDate() != null ? new Date(oleLoanDocument.getLoanDueDate().getTime()) : null;
1172        String dateToString = oleLoanDocument.getLoanDueDate() != null ? formatter.format(oleLoanDocument.getLoanDueDate()) : "null";
1173        checkReplacementFineExist(oleLoanDocument);
1174        checkOverdueExist(oleLoanDocument);
1175        if(!oleLoanDocument.isRenewalItemFlag()){
1176          isItemLoanedByDifferentPatron(oleLoanDocument); // No need for renewal.
1177        }
1178        checkItemDamagedStatus(oleLoanDocument);
1179        isMissingPieceFlagActive(oleLoanDocument);
1180        String agendaName = oleLoanDocument.isRenewalItemFlag() ? OLEConstants.RENEWAL_AGENDA_NM : OLEConstants.CHECK_OUT_AGENDA_NM;
1181        Integer noOfRenewals = Integer.parseInt(oleLoanDocument.getNumberOfRenewals())+1;
1182        HashMap<String, Object> termValues = new HashMap<String, Object>();
1183        termValues.put(OLEConstants.BORROWER_TYPE, patronType);
1184        termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemTypeName());
1185        termValues.put(OLEConstants.NUM_ITEMS_CHECKED_OUT, keyLoanMap.get(OLEConstants.LOANED_ITEM_COUNT));
1186        termValues.put(OLEConstants.NUM_OVERDUE_ITEMS_CHECKED_OUT, (Integer) keyLoanMap.get(OLEConstants.OVERDUE_COUNT));
1187        termValues.put(OLEConstants.NUM_OVERDUE_RECALLED_ITEMS_CHECKED_OUT, (Integer) keyLoanMap.get(OLEConstants.RECALL_COUNT));
1188        termValues.put(OLEConstants.NUM_CLAIMS_RETURNED, numberOfClaimsReturned);
1189        termValues.put(OLEConstants.OVERDUE_FINE_AMT, overdueFineAmt);
1190        termValues.put(OLEConstants.REPLACEMENT_FEE_AMT, replacementFeeAmt);
1191        termValues.put(OLEConstants.ALL_CHARGES, overdueFineAmt + replacementFeeAmt + serviceFeeAmt);
1192        termValues.put(OLEConstants.IS_RENEWAL, oleLoanDocument.isRenewalItemFlag() ? OLEConstants.TRUE : OLEConstants.FALSE);
1193        termValues.put(OLEConstants.NUM_RENEWALS, noOfRenewals);
1194        termValues.put(OLEConstants.ITEMS_DUE_DATE, loanDueDate);
1195        termValues.put(OLEConstants.ITEMS_DUE_DATE_STRING, dateToString);
1196        termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
1197        termValues.put(OLEConstants.PATTERN, pattern);
1198        termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
1199        termValues.put(OLEConstants.ITEM_LOCATION, itemCircLoction);
1200        termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
1201        if(requestPatronId == null ){
1202            termValues.put(OLEConstants.IS_PATRON_POSITION_ONE, OLEConstants.FALSE);
1203        }
1204        else if (oleLoanDocument.getPatronId().equals(requestPatronId) || (oleLoanDocument.getProxyPatronId() != null && oleLoanDocument.getProxyPatronId().equals(requestPatronId))) {
1205            termValues.put(OLEConstants.IS_PATRON_POSITION_ONE, OLEConstants.TRUE );
1206            termValues.put(OLEConstants.REQUEST_TYPE, requestType);
1207        }else{
1208            termValues.put(OLEConstants.IS_PATRON_POSITION_ONE, OLEConstants.FALSE);
1209            termValues.put(OLEConstants.REQUEST_TYPE, requestType);
1210        }
1211      /*  termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());*/
1212        termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
1213        termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
1214        termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
1215        termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
1216        termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
1217        termValues.put(OLEConstants.REPLACEMENT_FEE_EXIST, oleLoanDocument.isReplacementFeeExist());
1218        termValues.put(OLEConstants.OVERDUE_FINE_EXIST, oleLoanDocument.isOverdueFineExist());
1219        termValues.put(OLEConstants.DIFF_PATRON_FLD, oleLoanDocument.isDifferentPatron());
1220        termValues.put(OLEConstants.ITEM_DAMAGED_STATUS_FLD, oleLoanDocument.isItemDamagedStatus());
1221        termValues.put(OLEConstants.ITEM_MISING_PICS_FLAG_FLD, oleLoanDocument.isMissingPieceFlag());
1222        termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
1223        termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
1224        Long krms1 = System.currentTimeMillis();
1225        EngineResults engineResults = getEngineResults(agendaName, termValues);
1226        Long krms2 = System.currentTimeMillis();
1227        Long krms3 = krms2 - krms1;
1228        LOG.info("The time taken for krms-item"+krms3);
1229        getDataCarrierService().removeData(patronId + itemId);
1230        Timestamp dueDate = (Timestamp) engineResults.getAttribute(OLEConstants.DUE_DATE);
1231        BigDecimal fineRate = (BigDecimal) engineResults.getAttribute(OLEConstants.FINE_RATE);
1232        BigDecimal maxFine = (BigDecimal) engineResults.getAttribute(OLEConstants.MAX_FINE);
1233        String circulationPolicySetId = (String) engineResults.getAttribute(OLEConstants.CIRCULATION_POLICY_SET_ID);
1234        oleLoanDocument.setCirculationPolicyId(circulationPolicySetId != null ? circulationPolicySetId : OLEConstants.NO_CIRC_POLICY_FOUND);
1235        oleLoanDocument.setFineRate(maxFine != null ? maxFine : fineRate);
1236        oleLoanDocument.getErrorsAndPermission().clear();
1237        HashMap<String, String> errorsAndPermission = new HashMap<>();
1238        if(!oleLoanDocument.isVuFindFlag()){
1239            if( oleLoanDocument.isRenewalItemFlag() && checkPendingRequestforItem(oleLoanDocument.getItemUuid())){
1240                failures.append(OLEConstants.PENDING_RQST_RENEWAL_ITM_INFO+ OLEConstants.OR);
1241            }
1242        }
1243        errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
1244        PermissionService service = KimApiServiceLocator.getPermissionService();
1245        if (dueDate == null) {
1246            oleLoanDocument.setDueDateEmpty(true);
1247        }
1248        int i = 1;
1249        if (errorsAndPermission != null) {
1250            Set<String> errorMessage = errorsAndPermission.keySet();
1251            if (errorMessage != null && errorMessage.size() > 0) {
1252                for (String errMsg : errorMessage) {
1253                    if (StringUtils.isNotEmpty(errMsg)) {
1254                        oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
1255                        if (oleLoanDocument.isRenewalItemFlag()) {
1256                            String permission = errorsAndPermission.get(errMsg);
1257                            if(operatorId == null){
1258                                if(GlobalVariables.getUserSession()!=null){
1259                                   operatorId = GlobalVariables.getUserSession().getPrincipalId();
1260                                }
1261                            }
1262                            boolean hasRenewPermission = service.hasPermission(operatorId, OLEConstants.DLVR_NMSPC, permission);
1263                            if (!hasRenewPermission) {
1264                                oleLoanDocument.setRenewPermission(false);
1265                            } else {
1266                                oleLoanDocument.setRenewPermission(true);
1267                            }
1268                            failures.append(errMsg + OLEConstants.OR);
1269                        } else {
1270                            failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
1271                        }
1272                    }
1273                }
1274            }
1275            errorsAndPermission.clear();
1276        }
1277        List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
1278        if (errorMessage != null && errorMessage.size() > 0) {
1279            for (String errMsg : errorMessage) {
1280                if (StringUtils.isNotEmpty(errMsg)) {
1281                    if (errMsg.equalsIgnoreCase("Inform the current borrower that this item has some missing pieces before proceeding with checkout.")) {
1282                        if (item != null && item.getMissingPiecesCount() != null) {
1283                            errMsg = errMsg.replace("some", item.getMissingPiecesCount());
1284                        }
1285                    }
1286                    if (oleLoanDocument.isRenewalItemFlag()) {
1287                        failures.append(errMsg + OLEConstants.OR);
1288                    } else {
1289                        if (errMsg.equalsIgnoreCase("Item status is Lost")) {
1290                            //oleLoanDocument.setStatusLost(true);
1291                            failures.append(i++ + "." + errMsg + "-" + OLEConstants.ITEMSTATUSLOST + OLEConstants.BREAK);
1292                        } else {
1293                            failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
1294                        }
1295                    }
1296                }
1297            }
1298        }
1299        if(oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.ITEM_STATUS_CHECKEDOUT)&& !oleLoanDocument.isRenewalItemFlag()){
1300            Map barMap = new HashMap();
1301            barMap.put("itemId", oleLoanDocument.getItemId());
1302            List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
1303            if (oleLoanDocuments != null && oleLoanDocuments.size()>0) {
1304                String url = "<a target=\"_blank\" href=" + OLEConstants.ASSIGN_INQUIRY_PATRON_ID + oleLoanDocuments.get(0).getPatronId() + OLEConstants.ASSIGN_PATRON_INQUIRY + ">" + oleLoanDocuments.get(0).getPatronId() + "</a>";
1305                failures.append(i++ + ". " + OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + "&nbsp;&nbsp;:&nbsp;" + url + OLEConstants.BREAK);
1306            }
1307        }
1308        getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
1309        getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
1310
1311        if(dateToString != null && dateToString.equalsIgnoreCase("null")){
1312            if(oleLoanDocument.isRenewalItemFlag() || (oleLoanDocument.isVuFindFlag() && oleLoanDocument.isRenewalItemFlag())) {
1313                failures.setLength(0);
1314                failures.append(OLEConstants.RENEWAL_INDEFINITE_INFO);
1315                oleLoanDocument.setIndefiniteCheckFlag(true);
1316            }else{
1317                oleLoanDocument.setIndefiniteCheckFlag(false);
1318            }
1319        }else{
1320            oleLoanDocument.setIndefiniteCheckFlag(false);
1321        }
1322        if (item.getItemType().getCodeValue().equalsIgnoreCase(OLEConstants.NONCIRC) || circulationPolicySetId == null) {
1323            oleLoanDocument.setNonCirculatingItem(true);
1324        }
1325        Timestamp  oldDueDate = oleLoanDocument.getLoanDueDate();
1326        if ((!oleLoanDocument.isRenewalItemFlag() || (oleLoanDocument.isRenewalItemFlag() && failures.toString().isEmpty()))) {
1327            oleLoanDocument.setLoanDueDate(dueDate != null ? dueDate : null);
1328        }
1329        if(oleLoanDocument.isRenewalItemFlag() && !oleLoanDocument.isIndefiniteCheckFlag() && oldDueDate.equals(dueDate)){
1330            failures.setLength(0);
1331            oleLoanDocument.setRenewNotFlag(true);
1332            failures.append(OLEConstants.RENEWAL_DUEDATE_SAME_INFO);
1333        }else{
1334            oleLoanDocument.setRenewNotFlag(false);
1335        }
1336        if ((!oleLoanDocument.isRenewalItemFlag() || (oleLoanDocument.isRenewalItemFlag()))) {
1337            oleLoanDocument.setRenewalLoanDueDate(dueDate != null ? dueDate : null);
1338        }
1339        if (!failures.toString().isEmpty()) {
1340            oleLoanDocument.setErrorMessage(failures.toString());
1341            return oleLoanDocument;
1342        }
1343
1344        if (oleLoanDocument.isRenewalItemFlag() && !oleLoanDocument.isIndefiniteCheckFlag() && !oleLoanDocument.isRenewNotFlag()) {
1345            if (oleLoanDocument.getNumberOfRenewals() == null) {
1346                oleLoanDocument.setNumberOfRenewals(OLEConstants.ZERO);
1347            }
1348            String noOfRenewal = "" + (Integer.parseInt(oleLoanDocument.getNumberOfRenewals()) + 1);
1349            if(noOfRenewal!=null && !noOfRenewal.isEmpty()){
1350                oleLoanDocument.setNumberOfOverdueNoticesSent("0");
1351            }
1352            oleLoanDocument.setNumberOfRenewals(noOfRenewal);
1353            oleLoanDocument.setCourtesyNoticeFlag(false);
1354            oleLoanDocument.setPastDueDate(pastDueDate);
1355            oleLoanDocument.setRenewalItemFlag(false);
1356        }
1357        Long beginSaveLoan = System.currentTimeMillis();
1358        if(oleLoanDocument.getManualRenewalDueDate()!=null && oleLoanDocument.getLoanDueDate() == null){
1359           oleLoanDocument.setLoanDueDate(oleLoanDocument.getManualRenewalDueDate());
1360        }
1361        saveLoan(oleLoanDocument);
1362        Long endSaveLoan = System.currentTimeMillis();
1363        Long timeTakenSaveLoan = endSaveLoan-beginSaveLoan;
1364        LOG.info("The Time Taken for save loan in Add Item"+timeTakenSaveLoan);
1365        return oleLoanDocument;
1366    }
1367
1368    /**
1369     * Retrieves Holding Object for given instance UUID.
1370     *
1371     * @param instanceUUID
1372     * @return
1373     * @throws Exception
1374     */
1375    public OleHoldings getOleHoldings(String instanceUUID) throws Exception {
1376        LOG.debug("--Inside getOleHoldings---");
1377
1378        Holdings holdings = new Holdings();
1379
1380
1381        holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(instanceUUID);
1382
1383
1384        HoldingOlemlRecordProcessor holdingOlemlRecordProcessor = new HoldingOlemlRecordProcessor();
1385        OleHoldings oleHoldings = holdingOlemlRecordProcessor.fromXML(holdings.getContent());
1386
1387
1388        return oleHoldings;
1389    }
1390
1391
1392    /*private boolean CheckItemStatusIsCheckedOut(Item oleItem) {
1393        LOG.debug("Inside the CheckItemStatusIsCheckedOut method");
1394        String itemStatus = oleItem.getItemStatus();
1395        if(itemStatus.equalsIgnoreCase(OLEConstants.ITEM_STATUS_CHECKEDOUT)){
1396            return true;
1397        }else {
1398            return false;
1399        }
1400    }*/
1401
1402   /* *//**
1403     * Check item barcode exist in docstore.
1404     * @param barcode
1405     * @return
1406     * @throws Exception
1407     *//*
1408    public boolean validateFastAddItem(String barcode) throws Exception{
1409        LOG.debug("Inside the validateFastAddItem method");
1410        SolrRequestReponseHandler solrRequestReponseHandler = new SolrRequestReponseHandler();
1411        List<HashMap<String, Object>> documentList = null;
1412        if(barcode != null){
1413          documentList= solrRequestReponseHandler.retriveResults(OLEConstants.ITEM_BARCODE_DISPLAY+barcode);
1414        }
1415        if(documentList != null && documentList.size() >0){
1416            return false;
1417        }else{
1418            return true;
1419        }
1420    }*/
1421
1422    /**
1423     * Compares expiration date with due date.
1424     *
1425     * @param oleLoanDocument
1426     */
1427    private void compareExpirationDateWithDueDate(OleLoanDocument oleLoanDocument) {
1428        LOG.debug("Inside the compareExpirationDateWithDueDate method");
1429        if (oleLoanDocument.getExpirationDate() != null && oleLoanDocument.getLoanDueDate()!=null) {
1430            Timestamp expirationDate = new Timestamp(oleLoanDocument.getExpirationDate().getTime());
1431           /* if (oleLoanDocument.getLoanDueDate() == null) {
1432                oleLoanDocument.setLoanDueDate(expirationDate);
1433            } else*/
1434            if (expirationDate.compareTo(oleLoanDocument.getLoanDueDate()) < 0) {
1435                oleLoanDocument.setLoanDueDate(expirationDate);
1436            }
1437        }
1438    }
1439
1440
1441    public EngineResults getEngineResults(String agendaName, HashMap<String, Object> termValues) throws Exception {
1442        Long begin = System.currentTimeMillis();
1443        LOG.debug("Inside the getEngineResults method");
1444        EngineResults engineResult = null;
1445        try {
1446            Engine engine = KrmsApiServiceLocator.getEngine();
1447            ContextDefinition contextDefinition = KrmsRepositoryServiceLocator.getContextBoService().getContextByNameAndNamespace("OLE-CONTEXT","OLE");
1448            AgendaDefinition agendaDefinition = KrmsRepositoryServiceLocator.getAgendaBoService().getAgendaByNameAndContextId(agendaName,contextDefinition.getId());
1449            HashMap<String, String> map = new HashMap<String, String>();
1450            map.put(OLEConstants.AGENDA_NAME,agendaDefinition.getName());
1451            List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
1452
1453            SelectionCriteria selectionCriteria =
1454                    SelectionCriteria.createCriteria(null, getSelectionContext(contextDefinition.getName()), getAgendaContext(agendaName));
1455/*
1456            HashMap<String, Object> agendaValue = new HashMap<String, Object>();
1457            agendaValue.put(OLEConstants.NAME_NM, agendaName);
1458            List<AgendaBo> agendaBos = (List<AgendaBo>) getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
1459            AgendaBo agendaBo = agendaBos.get(0);
1460            HashMap<String, String> map = new HashMap<String, String>();
1461            map.put(OLEConstants.AGENDA_NAME, agendaBo.getName());
1462            List<MatchBo> matchBos = (List<MatchBo>) getBusinessObjectService().findMatching(MatchBo.class, map);
1463
1464            SelectionCriteria selectionCriteria =
1465                    SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()), getAgendaContext(agendaName));*/
1466
1467            Long end = System.currentTimeMillis();
1468            Long timeTaken = end - begin;
1469            LOG.info("-----------TimeTaken to complete inside KRMS Call-----------"+timeTaken);
1470            ExecutionOptions executionOptions = new ExecutionOptions();
1471            executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
1472
1473            Facts.Builder factBuilder = Facts.Builder.create();
1474
1475            for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
1476                MatchBo matchBo = matchBoIterator.next();
1477                factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
1478            }
1479            long b1 = System.currentTimeMillis();
1480            engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
1481            long b2 = System.currentTimeMillis();
1482            long tot = b2 - b1;
1483            LOG.info("-----------TimeTaken to complete Only KRMS Call -----------"+tot);
1484        } catch (Exception krmsException) {
1485            LOG.error("-----------KRMS EXCEPTION------------------", krmsException);
1486
1487            throw new RuntimeException(krmsException);
1488        }
1489        Long end = System.currentTimeMillis();
1490        Long timeTaken = end - begin;
1491        LOG.info("-----------TimeTaken to complete KRMS Call-----------"+agendaName+"-------"+timeTaken);
1492        return engineResult;
1493    }
1494
1495    /**
1496     * This method returns selectionContext using contextName.
1497     *
1498     * @param contextName
1499     * @return Map
1500     * @throws Exception
1501     */
1502    protected Map<String, String> getSelectionContext(String contextName) throws Exception {
1503        LOG.debug("Inside the getSelectionContext method");
1504        Map<String, String> selector = new HashMap<String, String>();
1505        selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
1506        selector.put(NAME_SELECTOR, contextName);
1507        return selector;
1508    }
1509
1510    /**
1511     * This method returns agendaContext using agendaName.
1512     *
1513     * @param agendaName
1514     * @return Map
1515     * @throws Exception
1516     */
1517    protected Map<String, String> getAgendaContext(String agendaName) throws Exception {
1518        LOG.debug("Inside the getAgendaContext method");
1519        Map<String, String> selector = new HashMap<String, String>();
1520        selector.put(NAME_SELECTOR, agendaName);
1521        return selector;
1522    }
1523
1524
1525    /**
1526     * This method returns ItemTypeId using itemTypeName.
1527     *
1528     * @param itemTypeCode
1529     * @return OleInstanceItemType
1530     * @throws Exception
1531     */
1532    public OleInstanceItemType getItemTypeIdByItemType(String itemTypeCode) throws Exception {
1533        LOG.debug("Inside the getItemTypeIdByItemType method");
1534        Map barMap = new HashMap();
1535        barMap.put(OLEConstants.OleInstanceItemType.INSTANCE_ITEM_TYPE_CD, itemTypeCode);
1536        List<OleInstanceItemType> matchingItemType = (List<OleInstanceItemType>) getBusinessObjectService().findMatching(OleInstanceItemType.class, barMap);
1537        return matchingItemType.get(0);
1538    }
1539
1540
1541    /**
1542     * This method returns LoanStatusId.
1543     *
1544     * @return String
1545     * @throws Exception
1546     */
1547    private String getLoanStatusId() throws Exception {
1548        LOG.debug("Inside the getLoanStatusId method");
1549        Map barMap1 = new HashMap();
1550        barMap1.put(OLEConstants.OleItemAvailableStatus.ITEM_AVAILABLE_STATUS_CD, OLEConstants.ITEM_STATUS_CHECKEDOUT);
1551        List<OleItemAvailableStatus> matchingOleLoanStatus = (List<OleItemAvailableStatus>) getBusinessObjectService().findMatching(OleItemAvailableStatus.class, barMap1);
1552        if (matchingOleLoanStatus.size() > 0)
1553            return matchingOleLoanStatus.get(0).getItemAvailableStatusId();
1554        return null;
1555    }
1556
1557    /**
1558     * sets the value for location levels in Loan Document.
1559     *
1560     * @param locationLevelName
1561     * @param locationCode
1562     * @param oleLoanDoc
1563     * @return OleLoanDocument
1564     * @throws Exception
1565     */
1566    private OleLoanDocument populateLocationLevels(StringBuffer location,StringBuffer locationCodeBuff ,String locationLevelName, String locationCode, String locationName, OleLoanDocument oleLoanDoc) throws Exception {
1567        LOG.debug("Inside the setLocation method");
1568        if (locationCode != null) {
1569            if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_SHELVING)) {
1570                location.append(locationName);
1571                locationCodeBuff.append(locationCode);
1572                oleLoanDoc.setItemLocation(locationCode);
1573            } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_COLLECTION)) {
1574
1575                location.append(locationName + "-");
1576                locationCodeBuff.append(locationCode + "/");
1577                oleLoanDoc.setItemCollection(locationCode);
1578
1579            } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_LIBRARY)) {
1580                location.append(locationName + "-");
1581                locationCodeBuff.append(locationCode + "/");
1582                oleLoanDoc.setItemLibrary(locationCode);
1583            } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_INSTITUTION)) {
1584                location.append(locationName + "-");
1585                locationCodeBuff.append(locationCode + "/");
1586                oleLoanDoc.setItemInstitution(locationCode);
1587            } else if (locationLevelName.equalsIgnoreCase(OLEConstants.LOCATION_LEVEL_CAMPUS)) {
1588                location.append(locationName + "-");
1589                locationCodeBuff.append(locationCode + "/");
1590                oleLoanDoc.setItemCampus(locationCode);
1591            }
1592        }
1593        return oleLoanDoc;
1594
1595    }
1596
1597    /**
1598     * This method returns location details.
1599     *
1600     * @param oleItem
1601     * @param oleLoanDoc
1602     * @throws Exception
1603     */
1604    public void getLocation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument oleLoanDoc) throws Exception {
1605        LOG.debug("Inside the getLocation method");
1606        try {
1607            Location physicalLocation = oleItem.getLocation();
1608            LocationLevel locationLevel = null;
1609            locationLevel = physicalLocation.getLocationLevel();
1610            populateLocation(oleLoanDoc, locationLevel);
1611        } catch (Exception itemException) {
1612            LOG.error("--------------Invalid Item location data.---------------");
1613            try {
1614                OleHoldings oleHoldings = getOleHoldings(oleLoanDoc.getInstanceUuid());
1615                if (oleHoldings != null) {
1616                    Location physicalLocation = oleHoldings.getLocation();
1617                    LocationLevel locationLevel = null;
1618                    locationLevel = physicalLocation.getLocationLevel();
1619                    populateLocation(oleLoanDoc, locationLevel);
1620                }
1621            } catch (Exception holdingException) {
1622                LOG.error("--------------Invalid Holding location data.---------------" + holdingException, holdingException);
1623                throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
1624            }
1625        }
1626    }
1627
1628    /**
1629     * This method returns location details.
1630     *
1631     * @param oleItem
1632     * @param oleLoanDoc
1633     * @throws Exception
1634     */
1635    public void getLocation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument oleLoanDoc,org.kuali.ole.docstore.common.document.Item item) throws Exception {
1636        LOG.debug("Inside the getLocation method");
1637        try {
1638            Location physicalLocation = oleItem.getLocation();
1639            LocationLevel locationLevel = null;
1640            locationLevel = physicalLocation.getLocationLevel();
1641            populateLocation(oleLoanDoc, locationLevel);
1642        } catch (Exception itemException) {
1643            LOG.error("--------------Invalid Item location data.---------------");
1644            try {
1645                OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
1646                if (oleHoldings != null) {
1647                    Location physicalLocation = oleHoldings.getLocation();
1648                    LocationLevel locationLevel = null;
1649                    locationLevel = physicalLocation.getLocationLevel();
1650                    populateLocation(oleLoanDoc, locationLevel);
1651                }
1652            } catch (Exception holdingException) {
1653                LOG.error("--------------Invalid Holding location data.---------------" + holdingException, holdingException);
1654                throw new Exception(ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.INVAL_LOC));
1655            }
1656        }
1657    }
1658
1659    /**
1660     * Populate location levels.
1661     *
1662     * @param oleLoanDocument
1663     * @param locationLevel
1664     * @throws Exception
1665     */
1666    public void populateLocation(OleLoanDocument oleLoanDocument, LocationLevel locationLevel) throws Exception {
1667        LOG.debug("Inside the getOleLocationLevel method");
1668        StringBuffer location = new StringBuffer();
1669        StringBuffer locationCodeBuff = new StringBuffer();
1670        while (locationLevel.getLocationLevel() != null) {
1671            OleLocationLevel oleLocationLevel = getCircDeskLocationResolver().getLocationLevelByName(locationLevel.getLevel());
1672            OleLocation oleLocation = new OleLocation();
1673            if (!"".equals(locationLevel.getName())) {
1674                oleLocation = getCircDeskLocationResolver().getLocationByLocationCode(locationLevel.getName());
1675                oleLoanDocument.setOleLocation(oleLocation);
1676            }
1677            populateLocationLevels(location, locationCodeBuff, oleLocationLevel.getLevelName(), oleLocation.getLocationCode(), oleLocation.getLocationName(), oleLoanDocument);
1678            OleCirculationDesk oleCirculationDesk = getCircDeskLocationResolver().getCirculationDeskByLocationId(oleLocation.getLocationId());
1679            if(oleCirculationDesk!=null){
1680                oleLoanDocument.setLocationCode(oleCirculationDesk.getCirculationDeskCode());
1681                oleLoanDocument.setRouteToLocationName(oleCirculationDesk.getCirculationDeskPublicName());
1682            }
1683            locationLevel = locationLevel.getLocationLevel();
1684        }
1685
1686        oleLoanDocument.setItemLocation(locationLevel.getName());
1687        OleLocation oleLocation = getCircDeskLocationResolver().getLocationByLocationCode(oleLoanDocument.getItemLocation());
1688        OleCirculationDesk oleCirculationDesk = getCircDeskLocationResolver().getCirculationDeskByLocationId(oleLocation.getLocationId());
1689        OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
1690        OleCirculationDesk pickUpCircDesk = oleDeliverRequestBo != null && oleDeliverRequestBo.getPickUpLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId()) : null;
1691        OleCirculationDesk destinationCircDesk = oleDeliverRequestBo != null && oleDeliverRequestBo.getCirculationLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleDeliverRequestBo.getCirculationLocationId()) : null;
1692        if (pickUpCircDesk != null) {
1693            oleLoanDocument.setLocationCode(pickUpCircDesk.getCirculationDeskCode());
1694            oleLoanDocument.setRouteToLocationName(pickUpCircDesk.getCirculationDeskPublicName());
1695        } else if (destinationCircDesk != null) {
1696            oleLoanDocument.setLocationCode(destinationCircDesk.getCirculationDeskCode());
1697            oleLoanDocument.setRouteToLocationName(destinationCircDesk.getCirculationDeskPublicName());
1698        } else if (oleCirculationDesk != null) {
1699            oleLoanDocument.setLocationCode(oleCirculationDesk.getCirculationDeskCode());
1700            oleLoanDocument.setRouteToLocationName(oleCirculationDesk.getCirculationDeskPublicName());
1701        } else {
1702            oleLoanDocument.setRouteToLocationName(oleLocation.getLocationName());
1703        }
1704        location.append(oleLocation.getLocationName());
1705        locationCodeBuff.append(oleLocation.getLocationCode());
1706        oleLoanDocument.setLocation(location.toString());
1707        oleLoanDocument.setOleLocationCode(locationCodeBuff.toString());
1708        // }
1709    }
1710
1711
1712    /**
1713     * This method sets Title,loan Status,loan approver,loan operator,borrowerLimit and Item Unavailable in Loan Document..
1714     *
1715     * @param oleLoanDocument
1716     * @return OleLoanDocument
1717     * @throws Exception
1718     */
1719    public OleLoanDocument setLoan(OleLoanDocument oleLoanDocument) throws Exception {
1720        LOG.debug("Inside the setLoan method");
1721        if (StringUtils.isEmpty(oleLoanDocument.getTitle())) {
1722            org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
1723            org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
1724            SearchResponse searchResponse = null;
1725            if (oleLoanDocument.getBibUuid() == null) {
1726                if (oleLoanDocument.getItemId() != null) {
1727                    search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, oleLoanDocument.getItemId()), ""));
1728                } else {
1729                    search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.ID, oleLoanDocument.getItemUuid()), ""));
1730                }
1731                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
1732                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.TITLE));
1733                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.AUTHOR));
1734            } else {
1735                search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), Bib.ID, oleLoanDocument.getBibUuid()), ""));
1736                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(DocType.BIB.getCode(), Bib.TITLE));
1737                search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), Bib.AUTHOR));
1738            }
1739            searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
1740            for (SearchResult searchResult : searchResponse.getSearchResults()) {
1741                for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
1742                    String fieldName = searchResultField.getFieldName();
1743                    String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
1744                    if (fieldName.equalsIgnoreCase(Bib.TITLE) && !fieldValue.isEmpty()) {
1745                        oleLoanDocument.setTitle(fieldValue);
1746                    } else if (fieldName.equalsIgnoreCase(Bib.AUTHOR) && !fieldValue.isEmpty()) {
1747                        oleLoanDocument.setAuthor(fieldValue);
1748                    }
1749                }
1750            }
1751        }
1752        oleLoanDocument.setLoanStatusId(getLoanStatusId());
1753        //commented for jira OLE-5675
1754        if (!oleLoanDocument.isRenewalItemFlag()) {
1755            oleLoanDocument.setCreateDate(new Timestamp(new Date().getTime()));
1756        }
1757        String principalId = "";
1758        if (oleLoanDocument.getLoanOperatorId() == null) {
1759            oleLoanDocument.setLoanOperatorId(principalId);
1760        }
1761        if (GlobalVariables.getUserSession() != null) {
1762            principalId = GlobalVariables.getUserSession().getPrincipalId();
1763            if (!principalId.equals(GlobalVariables.getUserSession().getPrincipalId())) {
1764                oleLoanDocument.setLoanOperatorId(principalId);
1765            } else {
1766                oleLoanDocument.setLoanOperatorId(principalId);
1767            }
1768        }
1769        return oleLoanDocument;
1770    }
1771
1772    /**
1773     * persist the loan document and update item status to docstore.
1774     *
1775     * @param oleLoanDocument
1776     */
1777    public void saveLoan(OleLoanDocument oleLoanDocument) throws Exception {
1778        LOG.debug("Inside the saveLoan method");
1779        if (oleLoanDocument != null) {
1780            if (oleLoanDocument.getProxyPatronId() != null) {
1781                String proxyPatronId = oleLoanDocument.getProxyPatronId();
1782                oleLoanDocument.setProxyPatronId(oleLoanDocument.getPatronId());
1783                oleLoanDocument.setPatronId(proxyPatronId);
1784            }
1785            if (oleLoanDocument.getFineRate() != null) {
1786                if (oleLoanDocument.getOlePatron() == null) {
1787                    oleLoanDocument.setOlePatron(getOlePatronDocument(oleLoanDocument.getPatronId()));
1788                }
1789                if (oleLoanDocument.getFineRate().intValue() > 0)
1790                    generatePatronBillPayment(oleLoanDocument, OLEConstants.OVERDUE_FINE, oleLoanDocument.getFineRate());
1791            }
1792            compareExpirationDateWithDueDate(oleLoanDocument);
1793            getBusinessObjectService().save(oleLoanDocument);
1794            if (oleLoanDocument.isRequestPatron() || (!oleLoanDocument.isRequestPatron() && oleLoanDocument.getOleRequestId() != null && !"".equalsIgnoreCase(oleLoanDocument.getOleRequestId()))) {
1795                try {
1796                    String operatorId = (oleLoanDocument.getLoanApproverId() != null && !oleLoanDocument.getLoanApproverId().isEmpty()) ? oleLoanDocument.getLoanApproverId() : oleLoanDocument.getLoanOperatorId();
1797                    getOleDeliverRequestDocumentHelperService().deleteRequest(oleLoanDocument.getOleRequestId(), oleLoanDocument.getItemUuid(), operatorId, oleLoanDocument.getLoanId(), ConfigContext.getCurrentContextConfig().getProperty(OLEConstants.REQUEST_FULFILLED));
1798                    OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
1799                    if (oleDeliverRequestBo != null && oleDeliverRequestBo.getRequestTypeCode() != null &&
1800                            (oleDeliverRequestBo.getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_DELIVERY) ||
1801                                    oleDeliverRequestBo.getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_HOLD))) {
1802                        getDocstoreUtil().isItemAvailableInDocStore(oleDeliverRequestBo);
1803                        getOleDeliverRequestDocumentHelperService().executeEngineResults(oleDeliverRequestBo);
1804                        oleLoanDocument.setSuccessMessage(OLEConstants.DUE_DATE_INFO);
1805                    }
1806                }catch (Exception request){
1807                    RollBackLoanRecord(oleLoanDocument);
1808                    LOG.error("Exception occured while handling the request "+request.getMessage());
1809                    throw new Exception("Exception occured while handling the request.");
1810                }
1811            }
1812            if(oleLoanDocument.getLoanId()!=null) {
1813                org.kuali.ole.docstore.common.document.content.instance.Item oleItem = oleLoanDocument.getOleItem();
1814                if (oleItem != null) {
1815                    oleItem.setCurrentBorrower(oleLoanDocument.getPatronId());
1816                    oleItem.setProxyBorrower(oleLoanDocument.getProxyPatronId());
1817                    oleItem.setCheckOutDateTime(convertDateToString(oleLoanDocument.getCreateDate(), "MM/dd/yyyy HH:mm:ss"));
1818                    if (oleLoanDocument.getLoanDueDate() != null) {
1819                        oleItem.setDueDateTime(convertToString(oleLoanDocument.getLoanDueDate()));
1820                    } else {
1821                        oleItem.setDueDateTime("");
1822                    }
1823                    oleItem.setNumberOfRenew(Integer.parseInt(oleLoanDocument.getNumberOfRenewals()));
1824                    postLoan(oleItem);
1825                }
1826                if (getItemStatus() != null) {
1827                    oleLoanDocument.setItemStatus(getItemStatus());
1828                }
1829                getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
1830                getOleDeliverNoticeHelperService().generateDeliverNotices(oleLoanDocument);
1831            }
1832        }
1833    }
1834
1835    /**
1836     * This method is used to convert the date to string based on the given input format
1837     * @param format
1838     * @param date
1839     * @return
1840     */
1841    public String convertDateToString(Date date ,String format){
1842        LOG.info("Date Format : " +format + "Date : " + date);
1843        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
1844        String dateValue ="";
1845         try{
1846            dateValue = simpleDateFormat.format(date);
1847        }catch(Exception e){
1848             LOG.error(e,e);
1849         }
1850        LOG.info("Formatted Date : " + dateValue);
1851       return dateValue;
1852    }
1853
1854    public String convertToString(Timestamp date) {
1855//        Timestamp timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).format(date).concat(" ").concat(new SimpleDateFormat("HH:mm:ss").format(new Date())));
1856        SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
1857        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1858        Date itemDate = null;
1859        try {
1860            itemDate = format2.parse(date.toString());
1861        } catch (ParseException e) {
1862            LOG.error("format string to Date " + e);
1863        }
1864        return format1.format(itemDate).toString();
1865    }
1866
1867    public Collection getLoanObjectsFromDAO(List<OleLoanDocument> loanDocuments,String patronId){
1868        List<String> itemIds = new ArrayList<>();
1869        for(OleLoanDocument loanDocument : loanDocuments){
1870            itemIds.add(loanDocument.getItemUuid());
1871        }
1872        Collection loanObjects = getOleLoanDocumentDaoOjb().getLoanDocumentsUsingItemIdsAndPatronId(patronId,itemIds);
1873        return loanObjects;
1874    }
1875
1876    public Collection getLoanObjectFromDAOForRenewal(List<String> barcode,String patronId){
1877        Collection loanObjects = getOleLoanDocumentDaoOjb().getLoanDocumentsUsingItemBarcodeAndPatronIdForRenewal(patronId, barcode);
1878        return loanObjects;
1879    }
1880
1881    public OleLoanDocument getLoanDocumentsUsingItemIdAndPatronId(String itemId ,String patronId){
1882        Map loanMap = new HashMap();
1883        loanMap.put("itemUuid",itemId);
1884        loanMap.put("patronId",patronId);
1885        List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class,loanMap);
1886        return oleLoanDocuments!=null && oleLoanDocuments.size()>0 ? oleLoanDocuments.get(0):null;
1887    }
1888    /**
1889     * Update loan due date in loan record.
1890     *
1891     * @param updateDueDate
1892     * @throws Exception
1893     */
1894    public boolean updateLoan(List<OleLoanDocument> updateDueDate, String patronId, boolean claimsReturn, boolean removeClaimsReturnFlag,String borrowerCode) throws Exception {
1895        Collection loanObjects = getLoanObjectsFromDAO(updateDueDate, patronId);
1896        int i = 0;
1897        LOG.debug("Inside the updateLoan method");
1898        if (loanObjects != null && loanObjects.size() > 0) {
1899            for (Object loanObject : loanObjects) {
1900                OleLoanDocument oleLoanDocument = (OleLoanDocument) loanObject;
1901                OleLoanDocument existingLoanObject = updateDueDate.size() > i ? updateDueDate.get(i) : null;
1902                if (existingLoanObject != null) {
1903                    existingLoanObject.setCheckNo(false);
1904                    if (existingLoanObject.getLoanDueDateToAlter() != null) {
1905                        Timestamp timestamp;
1906                        Pattern pattern;
1907                        Matcher matcher;
1908                        SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OlePatron.PATRON_MAINTENANCE_DATE_FORMAT);
1909                        boolean timeFlag = false;
1910                        if (existingLoanObject.getLoanDueDateTimeToAlter() != null && !existingLoanObject.getLoanDueDateTimeToAlter().isEmpty()) {
1911                            String[] str = existingLoanObject.getLoanDueDateTimeToAlter().split(":");
1912                            pattern = Pattern.compile(OLEConstants.TIME_24_HR_PATTERN);
1913                            matcher = pattern.matcher(existingLoanObject.getLoanDueDateTimeToAlter());
1914                            timeFlag = matcher.matches();
1915                            if (timeFlag) {
1916                                if (str != null && str.length <= 2) {
1917                                    existingLoanObject.setLoanDueDateTimeToAlter(existingLoanObject.getLoanDueDateTimeToAlter() + OLEConstants.CHECK_IN_TIME_MS);
1918                                }
1919                                timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
1920                                        format(existingLoanObject.getLoanDueDateToAlter()).concat(" ").concat(existingLoanObject.getLoanDueDateTimeToAlter()));
1921                            } else {
1922                                return false;
1923                            }
1924                        } else if (fmt.format(existingLoanObject.getLoanDueDateToAlter()).compareTo(fmt.format(new Date())) == 0) {
1925                            String defaultCloseTime = getParameter(OLEParameterConstants.DEF_CLOSE_TIME);
1926                            timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
1927                                    format(new Date()).concat(" ").concat(defaultCloseTime));
1928                        } else {
1929                            String defaultCloseTime = getParameter(OLEParameterConstants.DEF_CLOSE_TIME);
1930                            timestamp = Timestamp.valueOf(new SimpleDateFormat(OLEConstants.CHECK_IN_DATE_TIME_FORMAT).
1931                                    format(existingLoanObject.getLoanDueDateToAlter()).concat(" ").concat(defaultCloseTime));
1932                        }
1933                        existingLoanObject.setLoanDueDate(timestamp);
1934                        oleLoanDocument.setLoanDueDate(timestamp);
1935                    }else if (existingLoanObject.getLoanDueDateTimeToAlter() == null || existingLoanObject.getLoanDueDateTimeToAlter().isEmpty()) {
1936                        existingLoanObject.setLoanDueDate(null);
1937                        oleLoanDocument.setLoanDueDate(null);
1938                    }
1939                    if (claimsReturn && existingLoanObject != null) {
1940                        oleLoanDocument.setClaimsReturnNote(existingLoanObject.getClaimsReturnNote());
1941                        oleLoanDocument.setClaimsReturnedDate(existingLoanObject.getClaimsReturnedDate());
1942                        oleLoanDocument.setClaimsReturnedIndicator(existingLoanObject.isClaimsReturnedIndicator());
1943                    }
1944                    oleLoanDocument.setCourtesyNoticeFlag(false);
1945                    getBusinessObjectService().save(oleLoanDocument);
1946                    i++;
1947                    String itemXmlContent = getItemXML(existingLoanObject.getItemUuid());
1948                    org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(existingLoanObject.getItemUuid());
1949
1950                    org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXmlContent);
1951                    if (claimsReturn && !removeClaimsReturnFlag) {
1952                        updateClaimsReturnedHistory(oleItem,existingLoanObject,patronId);
1953                        oleItem.setClaimsReturnedFlag(existingLoanObject.isClaimsReturnedIndicator());
1954                        if (existingLoanObject.getClaimsReturnedDate() != null) {
1955                            oleItem.setClaimsReturnedFlagCreateDate(convertToString(existingLoanObject.getClaimsReturnedDate()));
1956                        }
1957                        oleItem.setClaimsReturnedNote(existingLoanObject.getClaimsReturnNote());
1958                        getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(oleItem.getItemIdentifier());
1959                    } else if (removeClaimsReturnFlag) {
1960                        oleItem.setClaimsReturnedFlag(false);
1961                        oleItem.setClaimsReturnedFlagCreateDate(null);
1962                        oleItem.setClaimsReturnedNote(null);
1963                    } else {
1964                        if (existingLoanObject.getLoanDueDate() != null) {
1965                            oleItem.setDueDateTime(convertToString(existingLoanObject.getLoanDueDate()));
1966                        }
1967                    }
1968                    item.setId(existingLoanObject.getItemUuid());
1969                    item.setCategory(OLEConstants.WORK_CATEGORY);
1970                    item.setType(DocType.ITEM.getCode());
1971                    item.setFormat(OLEConstants.OLEML_FORMAT);
1972                    item.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
1973                    getDocstoreClientLocator().getDocstoreClient().updateItem(item);
1974                    if(!claimsReturn){
1975                        Map<String,String> locationMap = existingLoanObject.getItemFullLocation()!= null ?
1976                                getCircDeskLocationResolver().getLocationMap(existingLoanObject.getItemFullLocation()) : new HashMap<String,String>();
1977                        if(oleLoanDocument.getOleCirculationDesk()==null){
1978                            OleCirculationDesk oleCirculationDesk = oleLoanDocument.getCirculationLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId()) : null;
1979                            oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
1980                        }
1981                        if(existingLoanObject.getItemTypeName()==null){
1982                            if(oleItem!=null){
1983                                if(oleItem.getTemporaryItemType()!=null){
1984                                    existingLoanObject.setItemTypeName(oleItem.getTemporaryItemType().getCodeValue());
1985                                }else if(oleItem.getItemType()!=null){
1986                                    existingLoanObject.setItemTypeName(oleItem.getItemType().getCodeValue());
1987                                }
1988                            }
1989                        }
1990                        if(locationMap.size()>0){
1991                            existingLoanObject.setItemLibrary(locationMap.get(OLEConstants.ITEM_LIBRARY));
1992                            existingLoanObject.setItemInstitution(locationMap.get(OLEConstants.ITEM_INSTITUTION));
1993                            existingLoanObject.setItemCampus(locationMap.get(OLEConstants.ITEM_CAMPUS));
1994                            existingLoanObject.setItemCollection(locationMap.get(OLEConstants.ITEM_COLLECTION));
1995                            existingLoanObject.setItemLocation(locationMap.get(OLEConstants.ITEM_SHELVING));
1996                        }
1997                    }
1998                    getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
1999                    getOleDeliverNoticeHelperService().generateDeliverNotices(oleLoanDocument.getPatronId(), oleLoanDocument.getItemUuid(),
2000                            oleLoanDocument.getOleCirculationDesk()!=null ? oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode() : null,
2001                            borrowerCode,existingLoanObject.getItemTypeName(), existingLoanObject.getItemStatus(),
2002                            existingLoanObject.isClaimsReturnedIndicator() ? OLEConstants.TRUE : OLEConstants.FALSE,
2003                            oleLoanDocument.getRepaymentFeePatronBillId() != null ? OLEConstants.TRUE : OLEConstants.FALSE,
2004                            existingLoanObject.getItemLocation(), existingLoanObject.getItemCollection(), existingLoanObject.getItemLibrary(),
2005                            existingLoanObject.getItemCampus(), existingLoanObject.getItemInstitution(), oleLoanDocument.getLoanDueDate(),oleLoanDocument.getLoanId());
2006                }
2007            }
2008        }
2009        return true;
2010    }
2011
2012
2013    public void updateItem(List<OleLoanDocument> loanList, boolean claimsReturn, boolean removeClaimsReturnFlag) throws Exception {
2014        if (loanList != null && !loanList.isEmpty()) {
2015            for (int existingLoan = 0; existingLoan < loanList.size(); existingLoan++) {
2016                OleLoanDocument oleLoanDocument = (OleLoanDocument) loanList.get(existingLoan);
2017                if (oleLoanDocument != null) {
2018                    String itemXmlContent = getItemXML(oleLoanDocument.getItemUuid());
2019                    org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2020                    org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXmlContent);
2021                    if (claimsReturn && !removeClaimsReturnFlag) {
2022                        updateClaimsReturnedHistory(oleItem,oleLoanDocument,oleLoanDocument.getPatronId());
2023                        oleItem.setClaimsReturnedFlag(oleLoanDocument.isClaimsReturnedIndicator());
2024                        if (oleLoanDocument.getClaimsReturnedDate() != null) {
2025                            oleItem.setClaimsReturnedFlagCreateDate(convertToString(oleLoanDocument.getClaimsReturnedDate()));
2026                        }
2027                        oleItem.setClaimsReturnedNote(oleLoanDocument.getClaimsReturnNote());
2028                        getOleDeliverRequestDocumentHelperService().cancelPendingRequestForClaimsReturnedItem(oleItem.getItemIdentifier());
2029                    } else if (removeClaimsReturnFlag) {
2030                        oleItem.setClaimsReturnedFlag(false);
2031                        oleItem.setClaimsReturnedFlagCreateDate(null);
2032                        oleItem.setClaimsReturnedNote(null);
2033                    } else {
2034                        if (oleLoanDocument.getLoanDueDate() != null) {
2035                            oleItem.setDueDateTime(convertToString(oleLoanDocument.getLoanDueDate()));
2036                        }
2037                    }
2038                    item.setId(oleLoanDocument.getItemUuid());
2039                    item.setCategory(OLEConstants.WORK_CATEGORY);
2040                    item.setType(DocType.ITEM.getCode());
2041                    item.setFormat(OLEConstants.OLEML_FORMAT);
2042                    item.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
2043                    getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2044
2045                    //LOG.info(itemRecordUpdateResponse);
2046                }
2047            }
2048        }
2049    }
2050
2051    /**
2052     * Compares the checked items from existing and current loan session and form a common list.
2053     *
2054     * @param loanList
2055     * @param existingLoanList
2056     * @param claimsFlag
2057     * @param claimsReturnNote
2058     * @return
2059     */
2060    public List<OleLoanDocument> setListValues(List<OleLoanDocument> loanList, List<OleLoanDocument> existingLoanList, boolean claimsFlag, String claimsReturnNote, boolean removeClaimsReturnFlag) {
2061        LOG.debug("Inside the setListValues method");
2062        List<OleLoanDocument> commonList = new ArrayList<OleLoanDocument>();
2063        if (loanList != null && !loanList.isEmpty()) {
2064            for (int curremtLoan = 0; curremtLoan < loanList.size(); curremtLoan++) {
2065                OleLoanDocument oleLoanDocument = (OleLoanDocument) loanList.get(curremtLoan);
2066                if (oleLoanDocument.isCheckNo()) {
2067                    if (claimsFlag) {
2068                        oleLoanDocument.setClaimsReturnNote(claimsReturnNote);
2069                        oleLoanDocument.setClaimsReturnedIndicator(claimsFlag);
2070                        oleLoanDocument.setClaimsReturnedDate(new Timestamp(new Date().getTime()));
2071                    } else if (removeClaimsReturnFlag) {
2072                        oleLoanDocument.setClaimsReturnedIndicator(false);
2073                        oleLoanDocument.setClaimsReturnedDate(null);
2074                        oleLoanDocument.setClaimsReturnNote(null);
2075                    } else {
2076                        if (oleLoanDocument.getLoanDueDate() != null) {
2077                        oleLoanDocument.setPastDueDate(oleLoanDocument.getLoanDueDate());
2078                        oleLoanDocument.setLoanDueDateToAlter(new Date(oleLoanDocument.getLoanDueDate().getTime()));
2079                        }
2080                    }
2081                    commonList.add(oleLoanDocument);
2082                }
2083            }
2084        }
2085        if (existingLoanList != null && !existingLoanList.isEmpty()) {
2086            for (int existingLoan = 0; existingLoan < existingLoanList.size(); existingLoan++) {
2087                OleLoanDocument oleLoanDocument = (OleLoanDocument) existingLoanList.get(existingLoan);
2088                if (oleLoanDocument.isCheckNo()) {
2089                    if (claimsFlag) {
2090                        oleLoanDocument.setClaimsReturnNote(claimsReturnNote);
2091                        oleLoanDocument.setClaimsReturnedIndicator(true);
2092                        oleLoanDocument.setClaimsReturnedDate(new Timestamp(new Date().getTime()));
2093                    } else if (removeClaimsReturnFlag) {
2094                        oleLoanDocument.setClaimsReturnedIndicator(false);
2095                        oleLoanDocument.setClaimsReturnedDate(null);
2096                        oleLoanDocument.setClaimsReturnNote(null);
2097                    } else {
2098                        if (oleLoanDocument.getLoanDueDate() != null) {
2099                            oleLoanDocument.setPastDueDate(oleLoanDocument.getLoanDueDate());
2100                            oleLoanDocument.setLoanDueDateToAlter(new Date(oleLoanDocument.getLoanDueDate().getTime()));
2101                        }
2102                    }
2103                commonList.add(oleLoanDocument);
2104            }
2105        }
2106        }
2107
2108        return commonList;
2109    }
2110
2111    /**
2112     * This method creates and return itemContent using OleItem
2113     *
2114     * @param oleItem
2115     * @return String
2116     * @throws Exception
2117     */
2118    public String buildItemContent(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
2119        LOG.debug("Inside the buildItemContent method");
2120        ItemStatus itemStatus = new ItemStatus();
2121        itemStatus.setCodeValue(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2122        itemStatus.setFullValue(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2123        this.setItemStatus(OLEConstants.ITEM_STATUS_CHECKEDOUT);
2124        oleItem.setItemStatus(itemStatus);
2125        oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
2126        String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
2127        return itemContent;
2128    }
2129
2130    private void RollBackLoanRecord(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception{
2131        Map<String, String> criteria = new HashMap<String, String>();
2132        criteria.put("itemId", oleItem.getAccessInformation().getBarcode());
2133        List<OleLoanDocument> oleLoanDocument = (List<OleLoanDocument>)  KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class,criteria);
2134        if(oleLoanDocument.size()>0) {
2135            KRADServiceLocator.getBusinessObjectService().delete(oleLoanDocument.get(0));
2136        }
2137    }
2138
2139    private void RollBackLoanRecord(OleLoanDocument oleLoanDocument) throws Exception{
2140        Map<String, String> criteria = new HashMap<String, String>();
2141        criteria.put("itemId", oleLoanDocument.getItemId());
2142        List<OleLoanDocument> loanDocument = (List<OleLoanDocument>)  KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class,criteria);
2143        if(loanDocument.size()>0) {
2144            KRADServiceLocator.getBusinessObjectService().delete(loanDocument.get(0));
2145        }
2146    }
2147
2148    /**
2149     * This method invokes docStore to store item and returns itemRecordUpdateResponse.
2150     *
2151     * @param oleItem
2152     * @throws Exception
2153     */
2154    public void postLoan(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
2155        LOG.debug("Inside the postLoan method");
2156        try {
2157            String itemUuid = oleItem.getItemIdentifier();
2158            String itemXmlContent = buildItemContent(oleItem);
2159            Item item = new ItemOleml();
2160            item.setId(itemUuid);
2161            item.setContent(itemXmlContent);
2162            item.setCategory(OLEConstants.WORK_CATEGORY);
2163            item.setType(DocType.ITEM.getCode());
2164            item.setFormat(OLEConstants.OLEML_FORMAT);
2165            item.setStaffOnly(oleItem.isStaffOnlyFlag());
2166            getDocstoreClientLocator().getDocstoreClient().updateItem(item);
2167        } catch (Exception e) {
2168            RollBackLoanRecord(oleItem);
2169            LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
2170            throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
2171        }
2172    }
2173
2174
2175    public BibliographicRecord getBibliographicRecord(String title, String author) {
2176        LOG.debug("Inside the getBibliographicRecord method");
2177
2178        BibliographicRecord bibliographicRecord = new BibliographicRecord();
2179
2180        List<DataField> dataFieldList = new ArrayList<DataField>();
2181        DataField titleDataField = new DataField();
2182        titleDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_245);
2183        List<SubField> subFields = new ArrayList<SubField>();
2184        SubField subField = new SubField();
2185        subField.setCode(OLEConstants.A);
2186        subField.setValue(title);
2187        subFields.add(subField);
2188        titleDataField.setSubFields(subFields);
2189        dataFieldList.add(titleDataField);
2190
2191        if (author != null && !author.trim().isEmpty()) {
2192            DataField authorDataField = new DataField();
2193            authorDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_100);
2194            subFields = new ArrayList<SubField>();
2195            subField = new SubField();
2196            subField.setCode(OLEConstants.A);
2197            subField.setValue(author);
2198            subFields.add(subField);
2199            authorDataField.setSubFields(subFields);
2200            dataFieldList.add(authorDataField);
2201        }
2202        bibliographicRecord.setDatafields(dataFieldList);
2203        return bibliographicRecord;
2204
2205    }
2206
2207    public BibMarcRecord getBibMarcRecord(String title, String author) {
2208        LOG.debug("Inside the getBibliographicRecord method");
2209
2210        BibMarcRecord bibMarcRecord = new BibMarcRecord();
2211        List<org.kuali.ole.docstore.common.document.content.bib.marc.DataField> dataFieldList = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.DataField>();
2212        org.kuali.ole.docstore.common.document.content.bib.marc.DataField titleDataField = new org.kuali.ole.docstore.common.document.content.bib.marc.DataField();
2213        titleDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_245);
2214        List<org.kuali.ole.docstore.common.document.content.bib.marc.SubField> subFields = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.SubField>();
2215        org.kuali.ole.docstore.common.document.content.bib.marc.SubField subField = new org.kuali.ole.docstore.common.document.content.bib.marc.SubField();
2216        subField.setCode(OLEConstants.A);
2217        subField.setValue(title);
2218        subFields.add(subField);
2219        titleDataField.setSubFields(subFields);
2220        dataFieldList.add(titleDataField);
2221
2222        if (author != null && !author.trim().isEmpty()) {
2223            org.kuali.ole.docstore.common.document.content.bib.marc.DataField authorDataField = new org.kuali.ole.docstore.common.document.content.bib.marc.DataField();
2224            authorDataField.setTag(OLEConstants.MARC_EDITOR_TITLE_100);
2225            subFields = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.SubField>();
2226            subField = new org.kuali.ole.docstore.common.document.content.bib.marc.SubField();
2227            subField.setCode(OLEConstants.A);
2228            subField.setValue(author);
2229            subFields.add(subField);
2230            authorDataField.setSubFields(subFields);
2231            dataFieldList.add(authorDataField);
2232        }
2233
2234        bibMarcRecord.setDataFields(dataFieldList);
2235        return bibMarcRecord;
2236    }
2237
2238    public OleHoldings getHoldingRecord(OleLoanFastAdd oleLoanFastAdd) {
2239        OleHoldings oleHolding = new OleHoldings();
2240        LocationLevel locationLevel = new LocationLevel();
2241        locationLevel = getCircDeskLocationResolver().createLocationLevel(oleLoanFastAdd.getLocationName(), locationLevel);
2242        Location location = new Location();
2243        location.setPrimary(OLEConstants.TRUE);
2244        location.setStatus(OLEConstants.PERMANENT);
2245        location.setLocationLevel(locationLevel);
2246
2247        oleHolding.setLocation(location);
2248        oleHolding.setCallNumber(getCallNumber(oleLoanFastAdd));
2249        oleHolding.setPrimary(OLEConstants.TRUE);
2250        //oleHolding.setExtension(getExtension());
2251        return oleHolding;
2252    }
2253
2254    public org.kuali.ole.docstore.common.document.content.instance.Item getItemRecord(OleLoanFastAdd oleLoanFastAdd) {
2255        LOG.debug("Inside the getItemRecord method");
2256        org.kuali.ole.docstore.common.document.content.instance.Item item = new org.kuali.ole.docstore.common.document.content.instance.Item();
2257
2258        ItemType itemType = new ItemType();
2259        itemType.setCodeValue(oleLoanFastAdd.getItemType());
2260        item.setItemType(itemType);
2261        item.setCallNumber(getCallNumber(oleLoanFastAdd));
2262        item.setCopyNumberLabel(oleLoanFastAdd.getCopyNumber());
2263        item.setEnumeration(oleLoanFastAdd.getEnumeration());
2264        item.setCheckinNote(oleLoanFastAdd.getCheckinNote());
2265        item.setFastAddFlag(true);
2266        item.setNumberOfPieces(oleLoanFastAdd.getNumberOfPieces());
2267    /* LocationLevel locationLevel=new LocationLevel();
2268        locationLevel.setName(oleLoanFastAdd.getLocationName());
2269     Location value=new Location();
2270*/
2271
2272
2273        List<Note> notes = new ArrayList<Note>();
2274        Note note = new Note();
2275        note.setValue(oleLoanFastAdd.getNote());
2276        notes.add(note);
2277        item.setNote(notes);
2278
2279        AccessInformation accessInformation = new AccessInformation();
2280        accessInformation.setBarcode(oleLoanFastAdd.getBarcode());
2281
2282        item.setAccessInformation(accessInformation);
2283        OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(getParameter(OLEParameterConstants.FAST_ADD_ITEM_DEFAULT_STATUS));
2284        ItemStatus itemStatus = new ItemStatus();
2285        itemStatus.setCodeValue(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusCode() : null);
2286        itemStatus.setFullValue(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusCode() : null);
2287        item.setItemStatus(itemStatus);
2288        item.setCopyNumber(oleLoanFastAdd.getCopyNumber());
2289        //item.setExtension(getExtension());
2290
2291        return item;
2292    }
2293
2294    public OleItemAvailableStatus validateAndGetItemStatus(String itemStatusCode) {
2295        Map criteriaMap = new HashMap();
2296        criteriaMap.put(OLEConstants.ITEM_STATUS_CODE, itemStatusCode);
2297        OleItemAvailableStatus itemAvailableStatus = getBusinessObjectService().findByPrimaryKey(OleItemAvailableStatus.class, criteriaMap);
2298        return itemAvailableStatus;
2299    }
2300
2301    public boolean canOverrideLoan(String principalId) {
2302        LOG.debug("Inside the canOverrideLoan method");
2303        PermissionService service = KimApiServiceLocator.getPermissionService();
2304        return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_OVERRIDE_LOAN);
2305    }
2306
2307    /*public boolean canLoan(String principalId) {
2308        LOG.debug("Inside the canLoan method");
2309        PermissionService service = KimApiServiceLocator.getPermissionService();
2310        return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN);
2311    }*/
2312
2313    public boolean hasCirculationDesk(String principalId) {
2314        boolean hasCirculationDesk = false;
2315        String circkDesk = null;
2316        Map<String, String> userMap = new HashMap<String, String>();
2317        userMap.put("operatorId", principalId);
2318        List<OleCirculationDeskDetail> oleCirculationDeskDetails = (List<OleCirculationDeskDetail>) KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, userMap);
2319        if (oleCirculationDeskDetails != null && oleCirculationDeskDetails.size() > 0) {
2320            hasCirculationDesk = true;
2321        }
2322        return hasCirculationDesk;
2323    }
2324
2325    public boolean canEdit(String principalId) {
2326        PermissionService service = KimApiServiceLocator.getPermissionService();
2327        return service.hasPermission(principalId, OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.EDIT_PATRON);
2328    }
2329
2330    public String patronNameURL(String loginUser, String patronId) {
2331        boolean canEdit = canEdit(loginUser);
2332        String patronNameURL = "";
2333        if (canEdit) {
2334            patronNameURL = OLEConstants.ASSIGN_EDIT_PATRON_ID + patronId + OLEConstants.ASSIGN_PATRON_MAINTENANCE_EDIT;
2335        } else {
2336            patronNameURL = OLEConstants.ASSIGN_INQUIRY_PATRON_ID + patronId + OLEConstants.ASSIGN_PATRON_INQUIRY;
2337        }
2338        return patronNameURL;
2339    }
2340
2341    public boolean checkOverRidePermission(String principalId, OleLoanForm oleLoanForm) {
2342        LOG.debug("Inside the checkOverRidePermission method");
2343        boolean overRideFlag = true;
2344        PermissionService service = KimApiServiceLocator.getPermissionService();
2345        if (oleLoanForm.getErrorsAndPermission() != null) {
2346            Set<String> errorMessages = oleLoanForm.getErrorsAndPermission().keySet();
2347            for (String errorMessage : errorMessages) {
2348                if (StringUtils.isNotEmpty(errorMessage)) {
2349                    String permission = oleLoanForm.getErrorsAndPermission().get(errorMessage);
2350                    boolean hasPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, permission);
2351                    if (!hasPermission) {
2352                        if (errorMessage.equalsIgnoreCase(OLEConstants.GENERAL_BLOCK_MESSAGE)) {
2353                            errorMessage = errorMessage + " " + OLEConstants.SEMI_COLON + " " + oleLoanForm.getDummyLoan().getOlePatron().getGeneralBlockNotes();
2354                        }
2355                        oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2356                                errorMessage + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + errorMessage + OLEConstants.BREAK);
2357                        overRideFlag = false;
2358                    }
2359                }
2360            }
2361            if (StringUtils.isNotEmpty(oleLoanForm.getMessage())) {
2362                if (oleLoanForm.getMessage().contains(OLEConstants.OVERDUE_DAY_LIMIT_ERROR)) {
2363                    boolean hasOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.PATRON_OVERDUE_DAY);
2364                    if (!hasOverdueDayPermission) {
2365                        oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2366                                OLEConstants.OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK);
2367                        overRideFlag = false;
2368                    }
2369                }
2370                if (oleLoanForm.getMessage().contains(OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR)) {
2371                    boolean hasRecalledOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.PATRON_RECALLED_OVERDUE_DAY);
2372                    if (!hasRecalledOverdueDayPermission) {
2373                        oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2374                                OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.RECALL_OVERDUE_DAY_LIMIT_ERROR + OLEConstants.BREAK);
2375                        overRideFlag = false;
2376                    }
2377                }
2378                if (oleLoanForm.getMessage().contains(OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION)) {
2379                    boolean hasRecalledOverdueDayPermission = service.hasPermission(principalId, OLEConstants.DLVR_NMSPC,OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION);
2380                    if (!hasRecalledOverdueDayPermission) {
2381                        oleLoanForm.setOverrideErrorMessage(oleLoanForm.getOverrideErrorMessage() == null ?
2382                                OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + OLEConstants.BREAK : oleLoanForm.getOverrideErrorMessage() + OLEConstants.ITEM_STATUS_LOANED_ANOTHER_PATRON_PERMISSION + OLEConstants.BREAK);
2383                        overRideFlag = false;
2384                    }
2385                }
2386            }
2387        }
2388        return overRideFlag;
2389    }
2390
2391    public boolean itemValidation(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) {
2392        LOG.debug("Inside the itemValidation method");
2393        boolean itemValidation = true;
2394        if (oleItem == null)
2395            return false;
2396        else if ("".equals(oleItem.getItemType()) || oleItem.getItemType() == null)
2397            itemValidation = itemValidation && false;
2398        else if ("".equals(oleItem.getItemStatus()) || oleItem.getItemStatus() == null || validateAndGetItemStatus(oleItem.getItemStatus().getCodeValue()) == null)
2399            itemValidation = itemValidation && false;
2400
2401        return itemValidation;
2402    }
2403
2404
2405    public void deletePatronUserNote(String patronId, String patronNoteTypeId) throws Exception {
2406        LOG.debug("Inside the deletePatronUserNote method");
2407        HashMap<String, String> map = new HashMap<String, String>();
2408        map.put(OLEConstants.OlePatron.PATRON_ID, patronId);
2409        map.put(OLEConstants.PATRON_NOTE_TYPE_ID, patronNoteTypeId);
2410        getBusinessObjectService().deleteMatching(OlePatronNotes.class, map);
2411    }
2412
2413    /**
2414     * Return the loaned Items
2415     *
2416     * @param itemBarcode
2417     * @param oleLoanDocument
2418     * @return OleLoanDocument
2419     */
2420    public OleLoanDocument returnLoan(String itemBarcode, OleLoanDocument oleLoanDocument) throws Exception {
2421        LOG.debug("Inside the returnLoan method");
2422        long begin = System.currentTimeMillis();
2423        org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
2424
2425        if (itemBarcode != null && !itemBarcode.isEmpty()) {
2426
2427            org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
2428            SearchResponse searchResponse = null;
2429            search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, itemBarcode), ""));
2430
2431
2432            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), OLEConstants.ID));
2433            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.HOLDINGSIDENTIFIER));
2434            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
2435            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.TITLE));
2436            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.AUTHOR));
2437            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Item.LOCATION));
2438            search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.DESTINATION_FIELD_LOCATION_LEVEL_1));
2439            searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
2440            if (searchResponse.getSearchResults() != null && searchResponse.getSearchResults().size() > 0) {
2441
2442                for (SearchResult searchResult : searchResponse.getSearchResults()) {
2443                    boolean isItemLevelLocationExist = false;
2444                    for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
2445                        String fieldName = searchResultField.getFieldName();
2446                        String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
2447
2448                        if (fieldName.equalsIgnoreCase(Holdings.HOLDINGSIDENTIFIER) && !fieldValue.isEmpty()) {
2449                            oleLoanDocument.setInstanceUuid(fieldValue);
2450                        } else if (fieldName.equalsIgnoreCase(OLEConstants.ID) && !fieldValue.isEmpty()) {
2451                            oleLoanDocument.setItemUuid(fieldValue);
2452                        } else if (fieldName.equalsIgnoreCase(Bib.BIBIDENTIFIER) && !fieldValue.isEmpty()) {
2453                            oleLoanDocument.setBibUuid(fieldValue);
2454                        } else if (fieldName.equalsIgnoreCase(Bib.TITLE) && !fieldValue.isEmpty()) {
2455                            oleLoanDocument.setTitle(fieldValue);
2456                        } else if (fieldName.equalsIgnoreCase(Bib.AUTHOR) && !fieldValue.isEmpty()) {
2457                            oleLoanDocument.setAuthor(fieldValue);
2458                        } else if (fieldName.equalsIgnoreCase(Item.LOCATION) && !fieldValue.isEmpty()) {
2459                            oleLoanDocument.setItemLevelLocationExist(true);
2460                            isItemLevelLocationExist = true;
2461                            oleLoanDocument.setLocation(fieldValue);
2462                        } else if (fieldName.equalsIgnoreCase(Holdings.DESTINATION_FIELD_LOCATION_LEVEL_1) && !fieldValue.isEmpty()) {
2463                            if (!isItemLevelLocationExist) {
2464                                oleLoanDocument.setLocation(fieldValue);
2465                            }
2466                        }
2467
2468                    }
2469                }
2470            } else {
2471                throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
2472            }
2473
2474
2475        } else {
2476            item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2477
2478
2479            oleLoanDocument.setBibUuid(item.getHolding().getBib().getId());
2480            oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
2481            oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
2482
2483            oleLoanDocument.setInstanceUuid(item.getHolding().getId());
2484            oleLoanDocument.setItemUuid(item.getId());
2485            oleLoanDocument.setItemLocation(item.getLocation());
2486        }
2487
2488
2489        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = null;
2490        String itemXml = null;
2491        if(item.getContent()==null){
2492            item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
2493        }
2494        itemXml = item.getContent()!=null ? item.getContent() : getItemXML(oleLoanDocument.getItemUuid());
2495
2496        oleItem = getItemPojo(itemXml);
2497        OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
2498        boolean itemValidation = itemValidation(oleItem);
2499        if (!itemValidation)
2500            throw new Exception(OLEConstants.INVAL_ITEM);
2501        oleLoanDocument.setOleItem(oleItem);
2502        try {
2503           /* if(oleItem.getCallNumber()!=null && !StringUtils.isEmpty(oleItem.getCallNumber().getNumber())){
2504                oleLoanDocument.setItemCallNumber(getItemCallNumber(oleItem.getCallNumber()));
2505            }else {
2506                oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
2507            }*/
2508            oleLoanDocument.setItemCallNumber(getItemCallNumber(oleItem.getCallNumber(),oleHoldings.getCallNumber()));
2509            oleLoanDocument.setHoldingsLocation(getLocations(oleHoldings.getLocation()));
2510            getCopyNumber(oleItem,oleHoldings,oleLoanDocument);
2511            oleLoanDocument.setEnumeration(oleItem.getEnumeration());
2512            oleLoanDocument.setChronology(oleItem.getChronology());
2513            String status = oleItem.getItemStatus().getCodeValue();
2514            oleLoanDocument.setItemLoanStatus(status);
2515            oleLoanDocument.setItemPrice(new BigDecimal(oleItem.getPrice() != null && !oleItem.getPrice().isEmpty() ? oleItem.getPrice() : OLEConstants.ZERO));
2516        } catch (Exception e) {
2517            LOG.error("Exception", e);
2518            if (oleLoanDocument.isRenewalItemFlag()) {
2519                oleLoanDocument.setErrorMessage(OLEConstants.ITM_STS_NT_AVAL);
2520                return oleLoanDocument;
2521            } else
2522                throw new Exception(OLEConstants.ITM_STS_NT_AVAL);
2523        }
2524        /*if(oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.NOT_CHECK_OUT_STATUS)){
2525            throw new Exception(OLEConstants.ITM_CHECKIN_MSG);
2526        }*/
2527        oleLoanDocument.setItemId(itemBarcode);
2528        if (oleItem.getTemporaryItemType() != null && oleItem.getTemporaryItemType().getCodeValue() != "") {
2529            OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(oleItem.getTemporaryItemType().getCodeValue());
2530            oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
2531            oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2532        }
2533        else if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
2534            OleInstanceItemType oleInstanceItemType = getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
2535            oleLoanDocument.setOleInstanceItemType(oleInstanceItemType);
2536            oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
2537        }
2538        getLocation(oleItem, oleLoanDocument,item);
2539        if (oleLoanDocument.getLocation() == null || (oleLoanDocument.getLocation() != null && oleLoanDocument.getLocation().equalsIgnoreCase(""))) {
2540            getDefaultHoldingLocation(oleLoanDocument);
2541        }
2542        if (oleLoanDocument.getOleLocation() != null && oleLoanDocument.getOleLocation().getLocationId() != null) {
2543            /*Map<String, String> map = new HashMap<String, String>();
2544            map.put("parentLocationId", oleLoanDocument.getOleLocation().getLocationId());
2545            map.put("locationCode", oleLoanDocument.getItemLocation());
2546            List<OleLocation> oleLocations = (List<OleLocation>) getBusinessObjectService().findMatching(OleLocation.class, map);*/
2547            OleLocation oleLocation = getCircDeskLocationResolver().getLocationByParentIdAndLocationCode(oleLoanDocument.getOleLocation().getLocationId(),oleLoanDocument.getItemLocation());
2548            oleLoanDocument.setLocationId(oleLocation != null ? oleLocation.getLocationId() : oleLoanDocument.getOleLocation().getLocationId());
2549        }
2550        OleCirculationDesk oleCirculationDesk = null;
2551        if (oleLoanDocument.getCirculationLocationId() != null) {
2552            oleCirculationDesk = getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
2553            oleLoanDocument.setOleCirculationDesk(oleCirculationDesk);
2554        }
2555        OleDeliverRequestBo oleDeliverRequestBo = getPrioritizedRequest(oleLoanDocument.getItemUuid());
2556        /*Removed for the jira -4139 Damaged Checkin option from return view screen */
2557        /*if (oleLoanDocument.isDamagedCheckInOption()) {
2558            updateItemStatus(oleItem, OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2559            OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2560            oleLoanDocument.setItemStatus(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusName() : null);
2561            oleLoanDocument.setItemStatusCode(OLEConstants.ITEM_STATUS_RETURNED_DAMAGED);
2562            oleLoanDocument.setRouteToLocation(getCirculationDeskDefaultValue(oleLoanDocument.getLocationId()));
2563            oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo != null ? oleDeliverRequestBo : null);
2564            return oleLoanDocument;
2565        }*/
2566        oleLoanDocument.setItemDamagedStatus(oleItem.isItemDamagedStatus());
2567        if (!oleLoanDocument.isSkipDamagedCheckIn()) {
2568            if (oleLoanDocument.isItemDamagedStatus()) {
2569                return oleLoanDocument;
2570            }
2571        }
2572        List<OleLocation> oleLocations = new ArrayList<OleLocation>();
2573        if (oleCirculationDesk.getOleCirculationDeskLocations() != null) {
2574            for (OleCirculationDeskLocation oleCirculationDeskLocation : oleCirculationDesk.getOleCirculationDeskLocations()) {
2575                if(oleCirculationDeskLocation.getCirculationPickUpDeskLocation()==null || (oleCirculationDeskLocation.getCirculationPickUpDeskLocation()!=null && oleCirculationDeskLocation.getCirculationPickUpDeskLocation().trim().isEmpty())){
2576                oleLocations.add(oleCirculationDeskLocation.getLocation());
2577                }
2578            }
2579        } else {
2580            throw new Exception(OLEConstants.NO_LOC_CIR_DESK);
2581        }
2582        StringBuffer location = new StringBuffer();
2583        for (OleLocation oleLocation : oleLocations) {
2584            String operatorsCirculationLocation = getCircDeskLocationResolver().getFullPathLocation(oleLocation, getCircDeskLocationResolver().getLocationLevelIds());
2585            location.append(operatorsCirculationLocation).append(OLEConstants.DELIMITER_HASH);
2586        }
2587        String operatorsCirculationLocation = location.toString();
2588        if (LOG.isDebugEnabled()){
2589            LOG.debug("operatorsCirculationLocation---->" + operatorsCirculationLocation);
2590        }
2591        String shelvingLagTime = oleCirculationDesk.getShelvingLagTime() != null ? oleCirculationDesk.getShelvingLagTime() : getParameter(OLEConstants.SHELVING_LAG_TIME);
2592        Integer shelvingLagTimInt = new Integer(shelvingLagTime.isEmpty() ? OLEConstants.ZERO : shelvingLagTime);
2593        oleLoanDocument.setOperatorsCirculationLocation(operatorsCirculationLocation);
2594        String digitRoutine = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE);
2595        String pattern = getParameter(OLEParameterConstants.ITEM_DIGIT_ROUTINE_PATTERN);
2596        String agendaName = OLEConstants.CHECK_IN_AGENDA_NM;
2597        HashMap<String, Object> termValues = new HashMap<String, Object>();
2598        termValues.put(OLEConstants.SHEL_LAG_TIME, shelvingLagTimInt);
2599        StringBuffer failures = new StringBuffer();
2600        EngineResults engineResults = null;
2601        String requestType = null;
2602        OlePatronDocument oleRequestPatron = null;
2603
2604        if (oleDeliverRequestBo != null) {
2605            oleLoanDocument.setOleDeliverRequestBo(oleDeliverRequestBo);
2606            requestType = oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode();
2607            oleRequestPatron = getOlePatronDocument(oleDeliverRequestBo.getBorrowerId());
2608            OleCirculationDesk pickUpCircDesk = oleDeliverRequestBo.getPickUpLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId()) : null;
2609            String pickUpLocationFullPath = getCircDeskLocationResolver().circulationDeskLocations(pickUpCircDesk);
2610            OleCirculationDesk destinationCircDesk = oleDeliverRequestBo.getCirculationLocationId() != null ? getCircDeskLocationResolver().getOleCirculationDesk(oleDeliverRequestBo.getCirculationLocationId()) : null;
2611            String destinationLocationFullPath = getCircDeskLocationResolver().circulationDeskLocations(destinationCircDesk);
2612            termValues.put(OLEConstants.ITEM_PICKUP_LOCATION, pickUpLocationFullPath);
2613            termValues.put(OLEConstants.DESTINATION_LOCATION, destinationLocationFullPath);
2614            termValues.put(OLEConstants.REQUEST_TYPE, requestType);
2615            if (pickUpCircDesk != null) {
2616                oleLoanDocument.setRouteToLocation(pickUpCircDesk.getCirculationDeskCode());
2617                oleLoanDocument.setRouteToLocationName(pickUpCircDesk.getCirculationDeskPublicName());
2618            } else if (destinationCircDesk != null) {
2619                oleLoanDocument.setRouteToLocation(destinationCircDesk.getCirculationDeskCode());
2620                oleLoanDocument.setRouteToLocationName(destinationCircDesk.getCirculationDeskPublicName());
2621            } else {
2622                // oleLoanDocument.setRouteToLocation(oleCirculationDesk!=null?oleCirculationDesk.getCirculationDeskCode():null);
2623                oleLoanDocument.setRouteToLocation(oleLoanDocument.getLocationCode());
2624            }
2625            oleLoanDocument.setOleRequestPatron(oleRequestPatron);
2626        } else {
2627            //oleLoanDocument.setRouteToLocation(oleCirculationDesk!=null?oleCirculationDesk.getCirculationDeskCode():null);
2628            oleLoanDocument.setRouteToLocation(oleLoanDocument.getLocationCode());
2629        }
2630        termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
2631        termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
2632        termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
2633        termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
2634        termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
2635        termValues.put(OLEConstants.OleDeliverRequest.CLAIMS_RETURNED_FLAG, oleItem.isClaimsReturnedFlag());
2636        termValues.put(OLEConstants.REPLACEMENT_FEE_EXIST, oleLoanDocument.isReplacementFeeExist());
2637        String itemFullPathLocation = getCircDeskLocationResolver().getFullPathLocation(getCircDeskLocationResolver().getLocationByLocationCode(oleLoanDocument.getItemLocation()),getCircDeskLocationResolver().getLocationLevelIds());
2638        oleLoanDocument.setItemFullPathLocation(itemFullPathLocation);
2639        String patronId = oleLoanDocument.getPatronId()!=null ?  oleLoanDocument.getPatronId() : "";
2640        String itemId = oleLoanDocument.getItemId()!=null ?  oleLoanDocument.getItemId() : "";
2641        termValues.put(OLEConstants.PATRON_ID_POLICY, patronId);
2642        termValues.put(OLEConstants.ITEM_ID_POLICY, itemId);
2643        if (oleLoanDocument.getOlePatron() == null) {
2644            getDataCarrierService().addData(patronId+itemId, true);
2645            termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
2646            termValues.put(OLEConstants.ITEM_LOCATION, itemFullPathLocation);
2647            termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
2648            termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());
2649            termValues.put(OLEConstants.IS_ITEM_PRICE, oleLoanDocument.getItemPrice().compareTo(OLEConstants.BIGDECIMAL_DEF_VALUE) <= 0 ? OLEConstants.TRUE : OLEConstants.FALSE);
2650            termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
2651            termValues.put(OLEConstants.PATTERN, pattern);
2652            engineResults = getEngineResults(agendaName, termValues);
2653        } else {
2654            getDataCarrierService().removeData(patronId+itemId);
2655            getDataCarrierService().addData(OLEConstants.HOURS_DIFF, getOleCirculationPolicyService().getHoursDiff(oleLoanDocument.getLoanDueDate(), oleLoanDocument.getCheckInDate()));
2656            getDataCarrierService().addData("DUEDATE", oleLoanDocument.getLoanDueDate());
2657            getDataCarrierService().addData("CHECKINDATE", oleLoanDocument.getCheckInDate());
2658            termValues.put(OLEConstants.ITEM_BARCODE, itemBarcode);
2659            termValues.put(OLEConstants.BORROWER_TYPE, oleLoanDocument.getBorrowerTypeCode());
2660            termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemTypeName());
2661            termValues.put(OLEConstants.ITEM_LOCATION, itemFullPathLocation);
2662            termValues.put(OLEConstants.CIRCULATION_LOCATION, operatorsCirculationLocation);
2663            termValues.put(OLEConstants.ITEMS_DUE_DATE, oleLoanDocument.getLoanDueDate());
2664            termValues.put(OLEConstants.ITEM_STATUS, oleLoanDocument.getItemLoanStatus());
2665            termValues.put(OLEConstants.DELIVERY_PRIVILEGES, oleLoanDocument.getOlePatron().isDeliveryPrivilege() ? OLEConstants.TRUE : OLEConstants.FALSE);
2666            termValues.put(OLEConstants.IS_ITEM_PRICE, oleLoanDocument.getItemPrice().compareTo(OLEConstants.BIGDECIMAL_DEF_VALUE) <= 0 ? OLEConstants.TRUE : OLEConstants.FALSE);
2667            termValues.put(OLEConstants.DIGIT_ROUTINE, digitRoutine);
2668            termValues.put(OLEConstants.PATTERN, pattern);
2669            engineResults = getEngineResults(agendaName, termValues);
2670            BigDecimal fineRate = (BigDecimal) engineResults.getAttribute(OLEConstants.FINE_RATE);
2671            Boolean checkOut = (Boolean) engineResults.getAttribute(OLEConstants.CHECKOUT);
2672            BigDecimal maxFine = (BigDecimal) engineResults.getAttribute(OLEConstants.MAX_FINE);
2673            oleLoanDocument.setFineRate(maxFine != null ? maxFine : fineRate);
2674            oleLoanDocument.setCheckOut(checkOut != null ? checkOut : false);
2675        }
2676        getDataCarrierService().removeData(patronId+itemId);
2677        HashMap<String, String> errorsAndPermission = new HashMap<>();
2678        errorsAndPermission = (HashMap<String, String>) engineResults.getAttribute(OLEConstants.ERRORS_AND_PERMISSION);
2679        PermissionService service = KimApiServiceLocator.getPermissionService();
2680        int i = 1;
2681        if (errorsAndPermission != null) {
2682            Set<String> errorMessage = errorsAndPermission.keySet();
2683            if (errorMessage != null && errorMessage.size() > 0) {
2684                for (String errMsg : errorMessage) {
2685                    if (StringUtils.isNotEmpty(errMsg)) {
2686                        oleLoanDocument.getErrorsAndPermission().putAll(errorsAndPermission);
2687                        if (errorMessage != null && errorMessage.size() > 0) {
2688                            for (String errorMsg : errorMessage) {
2689                                failures.append(i++ + ". " + errorMsg + OLEConstants.BREAK);
2690                            }
2691                        }
2692                    }
2693                }
2694            }
2695            errorsAndPermission.clear();
2696        }
2697        List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
2698        String itemStatusCode = (String) engineResults.getAttribute(OLEConstants.ITEM_STATUS);
2699        BigDecimal replacementBill = (BigDecimal) engineResults.getAttribute(OLEConstants.REPLACEMENT_BILL);
2700        oleLoanDocument.setReplacementBill(replacementBill);
2701        if (itemStatusCode != null) {
2702            oleLoanDocument.setItemStatusCode(itemStatusCode);
2703        }
2704        if (errorMessage != null && errorMessage.size() > 0) {
2705            for (String errMsg : errorMessage) {
2706                failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
2707            }
2708        }
2709        getDataCarrierService().addData(OLEConstants.ERROR_ACTION, null);
2710        getDataCarrierService().addData(OLEConstants.ERRORS_AND_PERMISSION, null);
2711        boolean returnLoan = false;
2712        if (!failures.toString().isEmpty()) {
2713            oleLoanDocument.setErrorMessage(failures.toString());
2714            returnLoan = true;
2715        }
2716        if (requestType != null && requestType.equalsIgnoreCase(OLEConstants.COPY_REQUEST)) {
2717            oleLoanDocument.setCopyRequest(true);
2718            returnLoan = true;
2719        }
2720        if (returnLoan || oleItem.isClaimsReturnedFlag()) {
2721            return oleLoanDocument;
2722
2723        }
2724        oleLoanDocument = returnLoan(oleLoanDocument);
2725        long end = System.currentTimeMillis();
2726        long total = end - begin;
2727        LOG.info("Time taken Inside returnloan"+total);
2728        return oleLoanDocument;
2729    }
2730
2731    public OleDeliverRequestBo getPrioritizedRequest(String itemUuid) {
2732        LOG.debug("Inside the getPrioritizedRequest method");
2733        Map requestMap = new HashMap();
2734        requestMap.put("itemUuid", itemUuid);
2735        requestMap.put("borrowerQueuePosition", 1);
2736        List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2737        return oleDeliverRequestBos != null && oleDeliverRequestBos.size() > 0 ? oleDeliverRequestBos.get(0) : null;
2738    }
2739
2740    public OleDeliverRequestBo getCurrentQueue(String patronid, String itemUuid) throws Exception {
2741        LOG.debug("Inside the getCurrentQueue method");
2742        Map requestMap = new HashMap();
2743        requestMap.put("borrowerId", patronid);
2744        requestMap.put("itemUuid", itemUuid);
2745        List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
2746        return oleDeliverRequestBos != null && oleDeliverRequestBos.size() > 0 ? oleDeliverRequestBos.get(0) : null;
2747    }
2748
2749
2750
2751    public String generatePatronBillPayment(OleLoanDocument oleLoanDocument, String feeTypeName, BigDecimal fineAmount) {
2752        long begin = System.currentTimeMillis();
2753        StringBuffer contentForSendMail = new StringBuffer();
2754        LOG.debug("Inside the generatePatronBillPayment method");
2755
2756        PatronBillPayment patronBillPayment;
2757        OlePaymentStatus olePaymentStatus = getPaymentStatus();
2758        FeeType feeType = new FeeType();
2759        feeType.setFeeType(getFeeTypeId(feeTypeName));
2760        feeType.setFeeAmount(new KualiDecimal(fineAmount));
2761        feeType.setItemBarcode(oleLoanDocument.getItemId());
2762        feeType.setItemType(oleLoanDocument.getItemTypeName());
2763        feeType.setItemTitle(oleLoanDocument.getTitle());
2764        feeType.setItemUuid(oleLoanDocument.getItemUuid());
2765        feeType.setPaymentStatus(olePaymentStatus.getPaymentStatusId());
2766        feeType.setBalFeeAmount(new KualiDecimal(fineAmount));
2767        feeType.setFeeSource(OLEConstants.SYSTEM);
2768        feeType.setDueDate(oleLoanDocument.getLoanDueDate());
2769        feeType.setCheckInDate(oleLoanDocument.getCheckInDate());
2770        feeType.setCheckOutDate(oleLoanDocument.getCreateDate());
2771        List<FeeType> feeTypes = new ArrayList<FeeType>();
2772        feeTypes.add(feeType);
2773        Date billdate = new Date();
2774
2775        patronBillPayment = new PatronBillPayment();
2776        patronBillPayment.setBillDate(oleLoanDocument.getCheckInDate() != null ? new java.sql.Date(oleLoanDocument.getCheckInDate().getTime()) : new java.sql.Date(billdate.getTime()));
2777        patronBillPayment.setFeeType(feeTypes);
2778        //patronBillPayment.setMachineId(oleLoanDocument.getMachineId());  //commented for jira OLE-5675
2779        patronBillPayment.setPatronId(oleLoanDocument.getPatronId());
2780        patronBillPayment.setProxyPatronId(oleLoanDocument.getProxyPatronId());
2781        patronBillPayment.setTotalAmount(new KualiDecimal(fineAmount));
2782        patronBillPayment.setUnPaidBalance(new KualiDecimal(fineAmount));
2783
2784       /* }*/
2785
2786        PatronBillPayment patronBillPayments = getBusinessObjectService().save(patronBillPayment);
2787
2788        Map<String, String> patronMap = new HashMap<String, String>();
2789        BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
2790        patronMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
2791        List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
2792        OlePatronDocument olePatronDocument = olePatronDocumentList.get(0);
2793        String patronMail = "";
2794        try {
2795            patronMail = getOlePatronHelperService().getPatronHomeEmailId(olePatronDocument.getEntity().getEntityTypeContactInfos().get(0));
2796        } catch (Exception e) {
2797            LOG.error("Ecxeption while getting patron home mail id", e);
2798        }
2799        OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
2800        contentForSendMail.append(oleDeliverBatchService.generateMailContentFromPatronBill(oleLoanDocument, olePatronDocument, feeTypeName, String.valueOf(fineAmount), patronBillPayment));
2801        OleMailer oleMail = GlobalResourceLoader.getService("oleMailer");
2802        String replyToEmail = getCircDeskLocationResolver().getReplyToEmail(oleLoanDocument.getItemLocation());
2803        if (replyToEmail != null) {
2804            oleMail.sendEmail(new EmailFrom(replyToEmail), new EmailTo(patronMail), new EmailSubject(feeTypeName), new EmailBody(contentForSendMail.toString()), true);
2805        } else {
2806            oleMail.sendEmail(new EmailFrom(getParameter(OLEParameterConstants.NOTICE_FROM_MAIL)), new EmailTo(patronMail), new EmailSubject(feeTypeName), new EmailBody(contentForSendMail.toString()), true);
2807        }
2808        if (LOG.isInfoEnabled()){
2809            LOG.info("Mail send successfully to " + patronMail);
2810        }
2811        String billNumber = patronBillPayments.getBillNumber();
2812        long end = System.currentTimeMillis();
2813        long total = end - begin;
2814        LOG.info("Time taken Inside generatePatronBillPayment"+total);
2815        return billNumber;
2816    }
2817
2818    private OlePaymentStatus getPaymentStatus() {
2819        LOG.debug("Inside the getPaymentStatus method");
2820        Map statusMap = new HashMap();
2821        statusMap.put("paymentStatusName", OLEConstants.PAYMENT_STATUS_OUTSTANDING);
2822        List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
2823        return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
2824    }
2825
2826    private String getFeeTypeId(String feeTypeName) {
2827        LOG.debug("Inside the getOverdueFeeTypeId method");
2828        Map feeMap = new HashMap();
2829        feeMap.put("feeTypeName", feeTypeName);
2830        List<OleFeeType> oleFeeTypes = (List<OleFeeType>) getBusinessObjectService().findMatching(OleFeeType.class, feeMap);
2831        return oleFeeTypes != null && oleFeeTypes.size() > 0 ? oleFeeTypes.get(0).getFeeTypeId() : null;
2832    }
2833
2834    public OleLoanDocument returnLoan(OleLoanDocument oleLoanDocument) throws Exception {
2835        LOG.debug("Inside the returnLoan method");
2836        long begin = System.currentTimeMillis();
2837        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = oleLoanDocument.getOleItem();
2838        OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
2839        OlePatronDocument oleRequestPatron = oleLoanDocument.getOleRequestPatron();
2840        String circulationLocationId = oleLoanDocument.getCirculationLocationId();
2841        Integer numberOfPieces = Integer.parseInt(oleItem != null && oleItem.getNumberOfPieces() != null && !oleItem.getNumberOfPieces().isEmpty() ? oleItem.getNumberOfPieces() : "0");
2842        if (!oleLoanDocument.isContinueCheckIn() && numberOfPieces > 1) {
2843            oleLoanDocument.setItemNumberOfPieces(numberOfPieces);
2844            oleLoanDocument.setNumberOfPieces(true);
2845            return oleLoanDocument;
2846        }
2847        if (oleLoanDocument.getFineRate() != null && oleLoanDocument.getFineRate().compareTo(BigDecimal.ZERO) > 0) {
2848            generatePatronBillPayment(oleLoanDocument, OLEConstants.OVERDUE_FINE, oleLoanDocument.getFineRate());
2849            oleLoanDocument.setBillName(oleLoanDocument.getFineRate().toString());
2850            updateReplacementFeeBill(oleLoanDocument);
2851        }
2852        if (oleLoanDocument.getReplacementBill() != null && oleLoanDocument.getFineRate() != null && oleLoanDocument.getFineRate().compareTo(BigDecimal.ZERO) > 0) {
2853            generatePatronBillPayment(oleLoanDocument, OLEConstants.REPLACEMENT_FEE, oleLoanDocument.getReplacementBill());
2854            BigDecimal fineRate = oleLoanDocument.getFineRate() != null ? oleLoanDocument.getFineRate() : OLEConstants.BIGDECIMAL_DEF_VALUE;
2855            oleLoanDocument.setBillName(oleLoanDocument.getReplacementBill().add(fineRate).toString());
2856            if (oleItem.isStaffOnlyFlag()) {
2857                oleItem.setStaffOnlyFlag(false);
2858            }
2859        }
2860        if (oleLoanDocument.getRepaymentFeePatronBillId() != null) {
2861            if (oleItem.isStaffOnlyFlag()) {
2862                oleItem.setStaffOnlyFlag(false);
2863            }
2864            oleLoanDocument.setBillName(OLEConstants.REPLACEMENT_FEE);
2865        }
2866        if (oleLoanDocument.getItemStatusCode() != null) {
2867            incrementNumberOfCirculations(oleLoanDocument);
2868            oleItem.setCurrentBorrower(null);
2869            oleItem.setDueDateTime(null);
2870            oleItem.setCheckOutDateTime(null);
2871            updateItemStatus(oleItem, oleLoanDocument.getItemStatusCode());
2872            //updateMissingPiecesItemInfo(oleLoanDocument);
2873            OleItemAvailableStatus itemAvailableStatus = validateAndGetItemStatus(oleLoanDocument.getItemStatusCode());
2874            oleLoanDocument.setItemStatus(itemAvailableStatus != null ? itemAvailableStatus.getItemAvailableStatusName() : null);
2875        }
2876        if (olePatronDocument != null) {
2877            createCirculationHistoryAndTemporaryHistoryRecords(oleLoanDocument);
2878            try {
2879             // getOleDeliverNoticeHelperService().deleteDeliverNotices(oleLoanDocument.getLoanId());
2880              getBusinessObjectService().delete(oleLoanDocument);
2881             }catch (Exception rollback){
2882                rollbackCirculationHistoryAndTempHistory(oleLoanDocument);
2883                LOG.error("Problem occured while returing an item"+rollback);
2884                throw new Exception("Problem occured while returing an item");
2885            }
2886        }
2887        OleDeliverRequestBo oleDeliverRequestBo = oleLoanDocument.getOleDeliverRequestBo();
2888        OleLoanDocument checkOutLoanDocument;
2889        if (oleLoanDocument.isCheckOut()) {
2890            checkOutLoanDocument = checkOutItem(oleRequestPatron, oleItem, circulationLocationId, oleLoanDocument.getCheckInDate(), oleDeliverRequestBo);
2891            checkOutLoanDocument.setCheckOut(true);
2892            checkOutLoanDocument.setBackGroundCheckOut(true);
2893            checkOutLoanDocument.setRouteToLocation(oleLoanDocument.getRouteToLocation());
2894            checkOutLoanDocument.setOleCirculationDesk(oleLoanDocument.getOleCirculationDesk());
2895            return checkOutLoanDocument;
2896        }
2897        if (oleLoanDocument.getItemStatusCode() != null && oleLoanDocument.getItemStatusCode().equalsIgnoreCase(OLEConstants.RECENTLY_RETURNED)) {
2898            createOrUpdateRecentlyReturnedRecord(oleLoanDocument.getItemUuid(), oleLoanDocument.getOleCirculationDesk().getCirculationDeskId());
2899        }
2900        long end = System.currentTimeMillis();
2901        long total = end - begin;
2902        LOG.info("Time taken Inside inner returnloan"+total);
2903        return oleLoanDocument;
2904    }
2905
2906    private void rollbackCirculationHistoryAndTempHistory(OleLoanDocument oleLoanDocument) {
2907        Map<String, String> criteria = new HashMap<String, String>();
2908        criteria.put("loanId", oleLoanDocument.getLoanId());
2909        List<OleCirculationHistory> oleCirculationHistoryList = (List<OleCirculationHistory>)  KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationHistory.class,criteria);
2910        if(oleCirculationHistoryList.size()>0) {
2911            KRADServiceLocator.getBusinessObjectService().delete(oleCirculationHistoryList.get(0));
2912        }
2913        Map map = new HashMap();
2914        map.put("olePatronId",oleLoanDocument.getPatronId());
2915        map.put("itemId",oleLoanDocument.getItemId());
2916        List<OleTemporaryCirculationHistory> oleTemporaryCirculationHistoryList = (List<OleTemporaryCirculationHistory>)  KRADServiceLocator.getBusinessObjectService().findMatching(OleTemporaryCirculationHistory.class,map);
2917        if(oleTemporaryCirculationHistoryList.size()>0) {
2918            KRADServiceLocator.getBusinessObjectService().delete(oleTemporaryCirculationHistoryList.get(0));
2919        }
2920        try {
2921            org.kuali.ole.docstore.common.document.content.instance.Item oleItem = checkItemStatusForItemBarcode(oleLoanDocument.getItemId());
2922            if (oleItem != null && oleItem.getItemStatus() != null && !oleItem.getItemStatus().getCodeValue().equalsIgnoreCase(OLEConstants.ITEM_STATUS_CHECKEDOUT)) {
2923                rollbackItemStatus(oleItem, OLEConstants.ITEM_STATUS_CHECKEDOUT, oleLoanDocument.getItemId());
2924            }
2925        }catch (Exception rollback){
2926            LOG.error("Exception occured during returning an item records " + rollback.getMessage());
2927        }
2928
2929
2930    }
2931
2932    private void createOrUpdateRecentlyReturnedRecord(String itemUUID, String circulationDeskId) {
2933        HashMap<String, String> map = new HashMap<String, String>();
2934        map.put("itemUuid", itemUUID);
2935        OleRecentlyReturned oleRecentlyReturned = getBusinessObjectService().findByPrimaryKey(OleRecentlyReturned.class, map);
2936        if (oleRecentlyReturned != null) {
2937            oleRecentlyReturned.setCirculationDeskId(circulationDeskId);
2938        } else {
2939            oleRecentlyReturned = new OleRecentlyReturned();
2940            oleRecentlyReturned.setCirculationDeskId(circulationDeskId);
2941            oleRecentlyReturned.setItemUuid(itemUUID);
2942        }
2943        getBusinessObjectService().save(oleRecentlyReturned);
2944    }
2945
2946    public void incrementNumberOfCirculations(OleLoanDocument oleLoanDocument) {
2947        org.kuali.ole.docstore.common.document.content.instance.Item item = oleLoanDocument.getOleItem();
2948        NumberOfCirculations numberOfCirculations = item.getNumberOfCirculations();
2949        if (numberOfCirculations == null) {
2950            numberOfCirculations = new NumberOfCirculations();
2951            numberOfCirculations.setCheckInLocation(new ArrayList<CheckInLocation>());
2952        }
2953        List<CheckInLocation> checkInLocations = numberOfCirculations.getCheckInLocation();
2954        CheckInLocation checkInLocation = null;
2955        int count = 1;
2956        for (CheckInLocation checkInLoc : checkInLocations) {
2957            if (checkInLoc.getName() != null && checkInLoc.getName().equals(oleLoanDocument.getItemFullPathLocation())) {
2958                if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty()) {
2959                    if (checkInLoc.getInHouseCount() != null) {
2960                        if (oleLoanDocument.getItemStatusCode().equals("INTRANSIT") || oleLoanDocument.getItemStatusCode().equals("INTRANSIT-FOR-HOLD") || oleLoanDocument.getItemStatusCode().equals("INTRANSIT-PER-STAFF-REQUEST")) {
2961                            count = checkInLoc.getInHouseCount();
2962                        } else {
2963                            count = checkInLoc.getInHouseCount() + 1;
2964                        }
2965                    }
2966                } else {
2967                    if (checkInLoc.getCount() != null) {
2968                        count = checkInLoc.getCount() + 1;
2969                    }
2970                }
2971                checkInLocation = checkInLoc;
2972                break;
2973            }
2974        }
2975        if (checkInLocation == null) {
2976            checkInLocation = new CheckInLocation();
2977            checkInLocation.setName(oleLoanDocument.getItemFullPathLocation());
2978            if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty())
2979                checkInLocation.setInHouseCount(count);
2980            else
2981                checkInLocation.setCount(count);
2982            checkInLocations.add(checkInLocation);
2983        } else {
2984            if (oleLoanDocument.getLoanId() == null || oleLoanDocument.getLoanId().isEmpty())
2985                checkInLocation.setInHouseCount(count);
2986            else
2987                checkInLocation.setCount(count);
2988        }
2989        if (item.getNumberOfCirculations() != null) {
2990            oleLoanDocument.getOleItem().getNumberOfCirculations().setCheckInLocation(checkInLocations);
2991        } else {
2992            numberOfCirculations.setCheckInLocation(checkInLocations);
2993            oleLoanDocument.getOleItem().setNumberOfCirculations(numberOfCirculations);
2994        }
2995
2996    }
2997
2998    private OleLoanDocument checkOutItem(OlePatronDocument olePatronDocument, org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String circulationLocationId, Timestamp checkInDate, OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
2999        long begin = System.currentTimeMillis();
3000        LOG.debug("Inside the checkOutItem method");
3001        OleLoanDocument oleLoanDocument = new OleLoanDocument();
3002        oleLoanDocument.setOlePatron(olePatronDocument);
3003        oleLoanDocument.setPatronId(olePatronDocument.getOlePatronId());
3004        oleLoanDocument.setCirculationLocationId(circulationLocationId);
3005        oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3006        oleLoanDocument.setBorrowerTypeName(olePatronDocument.getBorrowerTypeName());
3007        oleLoanDocument.setBorrowerTypeCode(olePatronDocument.getBorrowerTypeCode());
3008        addLoan(olePatronDocument.getBarcode(), oleItem.getAccessInformation().getBarcode(), oleLoanDocument,null);
3009        //  deleteRequestRecord(oleDeliverRequestBo);
3010        OleItemAvailableStatus oleItemAvailableStatus = validateAndGetItemStatus(oleLoanDocument.getOleItem().getItemStatus().getCodeValue());
3011        oleLoanDocument.setItemStatus(oleItemAvailableStatus != null ? oleItemAvailableStatus.getItemAvailableStatusName() : null);
3012        oleLoanDocument.setItemStatusCode(oleLoanDocument.getOleItem().getItemStatus().getCodeValue());
3013        oleLoanDocument.setCheckInDate(checkInDate);
3014        long end = System.currentTimeMillis();
3015        long total = end - begin;
3016        LOG.info("Time taken Inside checkOutItem"+total);
3017        return oleLoanDocument;
3018    }
3019
3020    public void deleteRequestRecord(OleDeliverRequestBo oleDeliverRequestBo) {
3021        getOleDeliverRequestDocumentHelperService().cancelDocument(oleDeliverRequestBo);
3022    }
3023
3024    public void createCirculationHistoryAndTemporaryHistoryRecords(OleLoanDocument oleLoanDocument) throws Exception{
3025        LOG.debug("Inside the createCirculationHistoryAndTemporaryHistoryRecords method");
3026        try {
3027            OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
3028            OleCirculationHistory oleCirculationHistory = new OleCirculationHistory();
3029            oleCirculationHistory.setLoanId(oleLoanDocument.getLoanId());
3030            oleCirculationHistory.setCirculationPolicyId(oleLoanDocument.getCirculationPolicyId());
3031            oleCirculationHistory.setBibAuthor(oleLoanDocument.getAuthor());
3032            oleCirculationHistory.setBibTitle(oleLoanDocument.getTitle());
3033            oleCirculationHistory.setCheckInDate(oleLoanDocument.getCheckInDate() != null ? oleLoanDocument.getCheckInDate() : new Timestamp(System.currentTimeMillis()));
3034            //oleCirculationHistory.setCheckInMachineId(oleLoanDocument.getMachineId());  //commented for jira OLE-5675
3035            oleCirculationHistory.setCreateDate(oleLoanDocument.getCreateDate());
3036            oleCirculationHistory.setCirculationLocationId(oleLoanDocument.getCirculationLocationId());
3037            oleCirculationHistory.setDueDate(oleLoanDocument.getLoanDueDate());
3038            oleCirculationHistory.setItemId(oleLoanDocument.getItemId());
3039            //oleCirculationHistory.setMachineId(oleLoanDocument.getMachineId());      //commented for jira OLE-5675
3040            oleCirculationHistory.setNumberOfOverdueNoticesSent(oleLoanDocument.getNumberOfOverdueNoticesSent());
3041            oleCirculationHistory.setNumberOfRenewals(oleLoanDocument.getNumberOfRenewals());
3042            oleCirculationHistory.setStatisticalCategory(olePatronDocument.getStatisticalCategory());
3043            oleCirculationHistory.setRepaymentFeePatronBillId(oleLoanDocument.getRepaymentFeePatronBillId());
3044            oleCirculationHistory.setProxyPatronId(olePatronDocument.getProxyPatronId());
3045            oleCirculationHistory.setPatronTypeId(oleLoanDocument.getBorrowerTypeId());
3046            oleCirculationHistory.setPatronId(oleLoanDocument.getPatronId());
3047            oleCirculationHistory.setPastDueDate(oleLoanDocument.getPastDueDate());
3048            oleCirculationHistory.setOverdueNoticeDate(oleLoanDocument.getOverDueNoticeDate());
3049            oleCirculationHistory.setOleRequestId(oleLoanDocument.getOleRequestId());
3050            oleCirculationHistory.setItemUuid(oleLoanDocument.getItemUuid());
3051            if(oleLoanDocument.isItemLevelLocationExist()){
3052
3053            oleCirculationHistory.setItemLocation(getLocationId(oleLoanDocument.getItemFullPathLocation()));
3054            }
3055            oleCirculationHistory.setHoldingsLocation(getLocationId(oleLoanDocument.getHoldingsLocation()));
3056            getBusinessObjectService().save(oleCirculationHistory);
3057
3058            OleTemporaryCirculationHistory oleTemporaryCirculationHistory = new OleTemporaryCirculationHistory();
3059            oleTemporaryCirculationHistory.setCirculationLocationId(oleLoanDocument.getCirculationLocationId());
3060            oleTemporaryCirculationHistory.setOlePatronId(oleLoanDocument.getPatronId());
3061            oleTemporaryCirculationHistory.setItemId(oleLoanDocument.getItemId());
3062            oleTemporaryCirculationHistory.setCheckInDate(oleLoanDocument.getCheckInDate() != null ? oleLoanDocument.getCheckInDate() : new Timestamp(System.currentTimeMillis()));
3063            oleTemporaryCirculationHistory.setItemUuid(oleLoanDocument.getItemUuid());
3064            oleTemporaryCirculationHistory.setDueDate(oleLoanDocument.getLoanDueDate());
3065            oleTemporaryCirculationHistory.setCheckOutDate(oleLoanDocument.getCreateDate());
3066            getBusinessObjectService().save(oleTemporaryCirculationHistory);
3067        }catch (Exception tempHistoryException){
3068            LOG.error(tempHistoryException.getMessage());
3069            throw new Exception("Unable to record the transaction in temporary circulation history.");
3070        }
3071
3072    }
3073
3074    /**
3075     * This method invokes docStore to store item and returns itemRecordUpdateResponse.
3076     *
3077     * @param oleItem
3078     * @param itemStatus
3079     * @throws Exception
3080     */
3081    public void updateItemStatus(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatus) throws Exception {
3082        LOG.debug("Inside the updateItemStatus method");
3083        try {
3084            String itemUuid = oleItem.getItemIdentifier();
3085            String itemXmlContent = buildItemContentWithItemStatus(oleItem, itemStatus);
3086            if (LOG.isDebugEnabled()){
3087                LOG.debug("itemXmlContent" + itemXmlContent);
3088            }
3089            Item item = new ItemOleml();
3090            item.setId(itemUuid);
3091            item.setContent(itemXmlContent);
3092            item.setCategory(OLEConstants.WORK_CATEGORY);
3093            item.setType(DocType.ITEM.getCode());
3094            item.setFormat(OLEConstants.OLEML_FORMAT);
3095            getDocstoreClientLocator().getDocstoreClient().updateItem(item);
3096        } catch (Exception e) {
3097            LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
3098            throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
3099        }
3100    }
3101
3102    /**
3103     * This method invokes docStore to remove check in note and store item.
3104     *
3105     * @param oleItem
3106     * @throws Exception
3107     */
3108    public void removeCheckInNote(org.kuali.ole.docstore.common.document.content.instance.Item oleItem) throws Exception {
3109        LOG.debug("Inside the removeCheckInNote method");
3110        try {
3111            String itemUuid = oleItem.getItemIdentifier();
3112            oleItem.setCheckinNote("");
3113            String itemXmlContent = getItemOlemlRecordProcessor().toXML(oleItem);
3114            Item item = new ItemOleml();
3115            item.setId(itemUuid);
3116            item.setContent(itemXmlContent);
3117            item.setCategory(OLEConstants.WORK_CATEGORY);
3118            item.setType(DocType.ITEM.getCode());
3119            item.setFormat(OLEConstants.OLEML_FORMAT);
3120            getDocstoreClientLocator().getDocstoreClient().updateItem(item);
3121        } catch (Exception e) {
3122            LOG.error("removeCheckInNote" + e, e);
3123            throw new Exception("Exception in removeCheckInNote method" + e);
3124        }
3125    }
3126
3127    /**
3128     * This method creates and return itemContent using OleItem
3129     *
3130     * @param oleItem
3131     * @param itemStatus
3132     * @return String
3133     * @throws Exception
3134     */
3135    public String buildItemContentWithItemStatus(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatus) throws Exception {
3136        LOG.debug("Inside the buildItemContentWithItemStatus method");
3137        ItemStatus itemStatus1 = new ItemStatus();
3138        itemStatus1.setCodeValue(itemStatus);
3139        itemStatus1.setFullValue(itemStatus);
3140        oleItem.setItemStatus(itemStatus1);
3141        oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
3142        String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
3143        return itemContent;
3144    }
3145
3146    public OleLoanDocument getOleLoanDocumentUsingItemUUID(String itemUuid) {
3147        LOG.debug("Inside the getOleLoanDocumentUsingItemBarcode method");
3148        OleLoanDocument oleLoanDocument = null;
3149        Map barMap = new HashMap();
3150        barMap.put(OLEConstants.ITEM_UUID, itemUuid);
3151        List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
3152        if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3153            oleLoanDocument = oleLoanDocuments.get(0);
3154            barMap = new HashMap();
3155            barMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
3156            OlePatronDocument olePatronDocument = getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, barMap);
3157            oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3158            OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
3159            oleLoanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
3160            oleLoanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
3161            oleLoanDocument.setOlePatron(olePatronDocument);
3162        }
3163        return oleLoanDocument;
3164    }
3165
3166    public OleLoanDocument getOleLoanDocumentUsingItemBarcode(String itemBarcode) {
3167        LOG.debug("Inside the getOleLoanDocumentUsingItemBarcode method");
3168        OleLoanDocument oleLoanDocument = null;
3169        Map barMap = new HashMap();
3170        barMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemBarcode);
3171        List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, barMap);
3172        if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3173            oleLoanDocument = oleLoanDocuments.get(0);
3174           /* barMap = new HashMap();
3175            barMap.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());*/
3176            OlePatronDocument olePatronDocument = oleLoanDocument.getOlePatron();
3177            oleLoanDocument.setBorrowerTypeId(olePatronDocument.getBorrowerType());
3178            OleBorrowerType oleBorrowerType = olePatronDocument.getOleBorrowerType();
3179            oleLoanDocument.setBorrowerTypeName(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeName() != null ? oleBorrowerType.getBorrowerTypeName() : null);
3180            oleLoanDocument.setBorrowerTypeCode(oleBorrowerType != null && oleBorrowerType.getBorrowerTypeCode() != null ? oleBorrowerType.getBorrowerTypeCode() : null);
3181            oleLoanDocument.setOlePatron(olePatronDocument);
3182        }
3183        return oleLoanDocument;
3184    }
3185
3186    public OlePatronDocument getOlePatronDocument(String patronId) {
3187        LOG.debug("Inside the getOlePatronDocument method");
3188        Map barMap = new HashMap();
3189        barMap = new HashMap();
3190        barMap.put(OLEConstants.OlePatron.PATRON_ID, patronId);
3191        List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) getBusinessObjectService().findMatching(OlePatronDocument.class, barMap);
3192        return olePatronDocumentList != null && olePatronDocumentList.size() > 0 ? olePatronDocumentList.get(0) : null;
3193    }
3194
3195    /**
3196     * This method returns PatronLoanedItem using itemId
3197     *
3198     * @param itemId
3199     * @return List
3200     * @throws Exception
3201     */
3202    public OleLoanDocument getPatronRenewalItem(String itemId) throws Exception {
3203        LOG.debug("Inside the getPatronRenewalItem method");
3204        Map itemBarMap = new HashMap();
3205        itemBarMap.put(OLEConstants.OleDeliverRequest.ITEM_ID, itemId);
3206        List<OleLoanDocument> matchingLoan = (List<OleLoanDocument>) getBusinessObjectService().findMatching(OleLoanDocument.class, itemBarMap);
3207        OleLoanDocument oleLoanDocument = matchingLoan.get(0);
3208        setBibInfo(oleLoanDocument);
3209        Map map = new HashMap();
3210        map.put(OLEConstants.OlePatron.PATRON_ID, oleLoanDocument.getPatronId());
3211        OlePatronDocument olePatronDocument = (OlePatronDocument) getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, map);
3212        oleLoanDocument.setBorrowerTypeId(olePatronDocument.getOleBorrowerType().getBorrowerTypeId());
3213        oleLoanDocument.setBorrowerTypeName(olePatronDocument.getOleBorrowerType().getBorrowerTypeName());
3214        oleLoanDocument.setBorrowerTypeCode(olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
3215        return oleLoanDocument;
3216    }
3217
3218    public void setBibInfo(OleLoanDocument oleLoanDocument) throws Exception {
3219        LOG.debug("Inside the setBibInfo method");
3220        String itemUuid = oleLoanDocument.getItemId();
3221        org.kuali.ole.docstore.common.document.Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUuid);
3222        oleLoanDocument.setTitle(item.getHolding().getBib().getTitle());
3223        oleLoanDocument.setAuthor(item.getHolding().getBib().getAuthor());
3224        oleLoanDocument.setInstanceUuid(item.getHolding().getId());
3225        oleLoanDocument.setItemUuid(item.getId());
3226        String itemXml = item.getContent()!=null ? item.getContent() : getItemXML(item.getId());
3227        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXml);
3228        OleHoldings oleHoldings = new HoldingOlemlRecordProcessor().fromXML(item.getHolding().getContent());
3229        /*if(oleItem.getCallNumber()!=null && !StringUtils.isEmpty(oleItem.getCallNumber().getNumber())){
3230            oleLoanDocument.setItemCallNumber(getItemCallNumber(oleItem.getCallNumber()));
3231        }else {
3232            oleLoanDocument.setItemCallNumber(getItemCallNumber(oleHoldings.getCallNumber()));
3233        }*/
3234        oleLoanDocument.setItemCallNumber(getItemCallNumber(oleItem.getCallNumber(),oleHoldings.getCallNumber()));
3235        getLocation(oleItem, oleLoanDocument,item);
3236    }
3237
3238    /**
3239     * This method will return url for view link in patron record.
3240     *
3241     * @return Url
3242     */
3243
3244    public String getUrl(String patronId) {
3245        String url = "patronbill?viewId=BillView&amp;methodToCall=start&amp;patronId=" + patronId;
3246        return url;
3247    }
3248
3249    public boolean checkPendingRequestforItem(String itemUUID) {
3250        if (getOleDeliverRequestDocumentHelperService().getOleDeliverRequestBo(itemUUID) != null)
3251            return true;
3252        return false;
3253    }
3254
3255    public String getParameter(String name) {
3256        ParameterKey parameterKey = ParameterKey.create(OLEConstants.APPL_ID, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,name);
3257        Parameter parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
3258        if(parameter==null){
3259            parameterKey = ParameterKey.create(OLEConstants.APPL_ID_OLE, OLEConstants.DLVR_NMSPC, OLEConstants.DLVR_CMPNT,name);
3260            parameter = CoreServiceApiServiceLocator.getParameterRepositoryService().getParameter(parameterKey);
3261        }
3262        return parameter!=null?parameter.getValue():null;
3263    }
3264
3265    public OleLoanDocument overrideSaveLoanForRenewal(OleLoanDocument oleLoanDocument) throws Exception {
3266        if(!oleLoanDocument.isIndefiniteCheckFlag() && !oleLoanDocument.isRenewNotFlag()) {
3267            Date pastDueDate = oleLoanDocument.getLoanDueDate();
3268            if (oleLoanDocument.getRenewalLoanDueDate() != null) {
3269                oleLoanDocument.setLoanDueDate(oleLoanDocument.getRenewalLoanDueDate());
3270            } else {
3271                oleLoanDocument.setLoanDueDate(oleLoanDocument.getManualRenewalDueDate());
3272                oleLoanDocument.setManualRenewalDueDate(null);
3273                oleLoanDocument.setNonCirculatingItem(false);
3274            }
3275            compareExpirationDateWithDueDate(oleLoanDocument);
3276            if (oleLoanDocument.isRenewalItemFlag()) {
3277                if (oleLoanDocument.getNumberOfRenewals() == null)
3278                    oleLoanDocument.setNumberOfRenewals("0");
3279                String noOfRenewal = "" + (Integer.parseInt(oleLoanDocument.getNumberOfRenewals()) + 1);
3280                if (noOfRenewal != null && !noOfRenewal.isEmpty()) {
3281                    oleLoanDocument.setNumberOfOverdueNoticesSent("0");
3282                }
3283                oleLoanDocument.setNumberOfRenewals(noOfRenewal);
3284                oleLoanDocument.setCourtesyNoticeFlag(false);
3285                oleLoanDocument.setPastDueDate(pastDueDate);
3286                oleLoanDocument.setRenewalItemFlag(false);
3287                saveLoan(oleLoanDocument);
3288            }
3289        }
3290        return oleLoanDocument;
3291    }
3292
3293    /**
3294     * This method returns DefaultCirculationDesk using principleId
3295     *
3296     * @param principleId
3297     * @return OleCirculationDeskDetail
3298     */
3299    public OleCirculationDeskDetail getDefaultCirculationDesk(String principleId) {
3300        LOG.debug("Inside the getDefaultCirculationDesk method");
3301        Map barMap = new HashMap();
3302        barMap.put(OLEConstants.OPTR_ID, principleId);
3303        List<OleCirculationDeskDetail> oleCirculationDeskDetails = (List<OleCirculationDeskDetail>) getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, barMap);
3304        for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3305            if (oleCirculationDeskDetail.isDefaultLocation()) {
3306                return oleCirculationDeskDetail;
3307            }
3308        }
3309        return null;
3310    }
3311
3312    public boolean isValidCirculationDesk() {
3313        String value = getCircDesk();
3314        if (value==null) {
3315            return false;
3316        }
3317        circDeskId = value;
3318        return true;
3319    }
3320
3321    public boolean isAuthorized(String principalId) {
3322        Map<String, String> userMap = new HashMap<String, String>();
3323        userMap.put("operatorId", principalId);
3324        Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(principalId);
3325        return principal != null;
3326    }
3327
3328    public CallNumber getCallNumber(OleLoanFastAdd oleLoanFastAdd) {
3329        CallNumber callNumber = new CallNumber();
3330        callNumber.setNumber(oleLoanFastAdd.getCallNumber());
3331        callNumber.setPrefix(oleLoanFastAdd.getCallNumberPrefix());
3332        ShelvingScheme shelvingScheme = new ShelvingScheme();
3333        shelvingScheme.setCodeValue(oleLoanFastAdd.getCallNumberType());
3334        callNumber.setShelvingScheme(shelvingScheme);
3335        return callNumber;
3336    }
3337
3338    public boolean checkPermissionForRemoveNote(String principalId) {
3339        PermissionService service = KimApiServiceLocator.getPermissionService();
3340        return service.hasPermission(principalId, OLEConstants.DLVR_NMSPC, OLEConstants.CAN_REMOVE_NOTE);
3341    }
3342
3343    public OleNoticeBo getNotice(OleLoanDocument oleLoanDocument) {
3344
3345        OleLocation oleLocation = null;
3346        OleLoanDocument newLoanDocument;
3347        OleCirculationDesk oleCirculationDesk = null;
3348        Map<String, String> patronMap = new HashMap<String, String>();
3349        patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleLoanDocument.getPatronId());
3350        List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
3351        if (patronDocumentList.size() == 0) {
3352            return null;
3353        }
3354        OlePatronDocument olePatronDocument = patronDocumentList.get(0);
3355        EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
3356
3357        if (oleLoanDocument.getCirculationLocationId() != null) {
3358            oleCirculationDesk = getCircDeskLocationResolver().getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
3359            oleLocation = oleCirculationDesk != null ? oleCirculationDesk.getOleCirculationDeskLocations().get(0).getLocation() : null;
3360        }
3361        String locationName = oleLocation != null ? oleLocation.getLocationName() : null;
3362        OleNoticeBo oleNoticeBo = new OleNoticeBo();
3363        oleNoticeBo.setTitle(oleLoanDocument.getTitle() != null ? oleLoanDocument.getTitle() : "");
3364        oleNoticeBo.setAuthor(oleLoanDocument.getAuthor() != null ? oleLoanDocument.getAuthor() : "");
3365        oleNoticeBo.setItemId(oleLoanDocument.getItemId() != null ? oleLoanDocument.getItemId() : "");
3366        oleNoticeBo.setNoticeName("Return With Missing Piece Notice");
3367        oleNoticeBo.setNoticeSpecificContent("The following item(s) returned by you is missing one or more of its pieces.Please return the missing piece(s) to the library shown above or contact the library about this matter to avoid incurring any penalties.");
3368        oleNoticeBo.setCirculationDeskAddress("");
3369        oleNoticeBo.setCirculationDeskEmailAddress("");
3370        if (oleCirculationDesk != null)
3371            oleNoticeBo.setCirculationDeskName(oleCirculationDesk.getCirculationDeskPublicName());
3372        oleNoticeBo.setCirculationDeskPhoneNumber("");
3373        oleNoticeBo.setItemCallNumber(oleLoanDocument.getItemCallNumber() != null ? oleLoanDocument.getItemCallNumber() : "");
3374        oleNoticeBo.setItemShelvingLocation(oleLoanDocument.getItemLocation() != null ? oleLoanDocument.getItemLocation() : "");
3375        oleNoticeBo.setVolumeNumber(oleLoanDocument.getItemVolumeNumber() != null ? oleLoanDocument.getItemVolumeNumber() : "");
3376        oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + "  " + olePatronDocument.getEntity().getNames().get(0).getLastName());
3377        oleNoticeBo.setOleItem(oleLoanDocument.getOleItem());
3378        try {
3379            newLoanDocument = this.getPatronPreferredAddress(entityTypeContactInfoBo, oleLoanDocument);
3380            newLoanDocument = this.getPatronHomeEmailId(entityTypeContactInfoBo, oleLoanDocument);
3381            newLoanDocument = this.getPatronHomePhoneNumber(entityTypeContactInfoBo, oleLoanDocument);
3382            oleNoticeBo.setPatronAddress(newLoanDocument.getPreferredAddress() != null ? newLoanDocument.getPreferredAddress() : "");
3383            oleNoticeBo.setPatronEmailAddress(newLoanDocument.getEmail() != null ? newLoanDocument.getEmail() : "");
3384            oleNoticeBo.setPatronPhoneNumber(newLoanDocument.getPhoneNumber() != null ? newLoanDocument.getPhoneNumber() : "");
3385        } catch (Exception e) {
3386            LOG.error("Exception occured while setting patron Details" + e, e);
3387        }
3388
3389        return oleNoticeBo;
3390
3391    }
3392
3393    public String getCircDeskId() {
3394        return circDeskId;
3395    }
3396
3397    public void setCircDeskId(String circDeskId) {
3398        this.circDeskId = circDeskId;
3399    }
3400
3401    public List<String> getLoanUserList(List<String> loginUserList, StringBuffer buffer) {
3402        int count = loginUserList.size() - 1;
3403        String user = loginUserList.size() > 0 ? loginUserList.get(count) : "";
3404        if (!user.equalsIgnoreCase(buffer.toString())) {
3405            loginUserList.add(buffer.toString());
3406        }
3407        return loginUserList;
3408    }
3409
3410    public void setErrorFlagForItem(OleLoanDocument oleLoanDocument, OleLoanForm oleLoanForm) {
3411        boolean hasRole = false;
3412        Role role;
3413        RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
3414        List<String> roles = new ArrayList<>();
3415        role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_ONE);
3416        roles.add(role.getId());
3417        role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_TWO);
3418        roles.add(role.getId());
3419
3420        hasRole = roleServiceImpl.principalHasRole(GlobalVariables.getUserSession().getPrincipalId(), roles, null);
3421        if (StringUtils.isNotEmpty(oleLoanForm.getRoleName())) {
3422            if (oleLoanDocument.isBlockCheckinItem()) {
3423                oleLoanForm.setBlockItem(true);
3424                oleLoanForm.setBlockPatron(false);
3425            }
3426        } else if (StringUtils.isEmpty(oleLoanForm.getRoleName()) && !hasRole) {
3427            oleLoanForm.setBlockItem(true);
3428            oleLoanForm.setBlockPatron(false);
3429        } else {
3430            oleLoanForm.setBlockItem(true);
3431            oleLoanForm.setBlockPatron(true);
3432        }
3433    }
3434
3435    public void setErrorFlagForPatron(OleLoanDocument oleLoanDocument, OleLoanForm oleLoanForm) {
3436        boolean hasRole = false;
3437        RoleServiceImpl roleServiceImpl = new RoleServiceImpl();
3438        List<String> roles = new ArrayList<>();
3439
3440        if (StringUtils.isEmpty(oleLoanForm.getRoleName()) && oleLoanForm.getRoleName() == null) {
3441            Role role = roleServiceImpl.getRoleByNamespaceCodeAndName(OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CIRC_DESK_ATTENDANT_ONE);
3442            roles.add(role.getId());
3443            hasRole = roleServiceImpl.principalHasRole(GlobalVariables.getUserSession().getPrincipalId(), roles, null);
3444        }
3445        if (hasRole) {
3446            oleLoanForm.setBlockItem(true);
3447            oleLoanForm.setBlockPatron(true);
3448        } else {
3449            oleLoanForm.setBlockItem(false);
3450            oleLoanForm.setBlockPatron(true);
3451        }
3452    }
3453
3454
3455    public String getCircDesk() {
3456        String circkDesk = null;
3457        Map<String, String> userMap = new HashMap<String, String>();
3458        userMap.put("operatorId", GlobalVariables.getUserSession().getPrincipalId());
3459        Collection<OleCirculationDeskDetail> oleCirculationDeskDetails = KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDeskDetail.class, userMap);
3460
3461        for (OleCirculationDeskDetail oleCirculationDeskDetail : oleCirculationDeskDetails) {
3462            if (oleCirculationDeskDetail.isDefaultLocation() && oleCirculationDeskDetail.getOleCirculationDesk().isActive()) {
3463                circkDesk = (oleCirculationDeskDetail.getOleCirculationDesk().getCirculationDeskId());
3464                break;
3465            }
3466        }
3467        return circkDesk;
3468    }
3469
3470    public void checkReplacementFineExist(OleLoanDocument oleLoanDocument) {
3471        Map<String, String> map = new HashMap<String, String>();
3472        map.put(OLEConstants.ITEM_BARCODE, oleLoanDocument.getItemId());
3473        map.put(OLEConstants.FEE_TYPE_FIELD, getOleFeeTypeCode(OLEConstants.FEE_TYPE_CODE_REPL_FEE));
3474        List<FeeType> feeTypes = (List<FeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(FeeType.class, map);
3475        if (feeTypes != null && feeTypes.size() > 0) {
3476           /* feeTypes.get(feeTypes.size())
3477            oleLoanDocument.setReplacementFeeExist(true);*/
3478            for(FeeType feeType:feeTypes){
3479                if(feeType.getBalFeeAmount().isGreaterThan(new KualiDecimal(0.00))){
3480                    oleLoanDocument.setReplacementFeeExist(true);
3481                    break;
3482                }
3483            }
3484        }
3485
3486    }
3487
3488    public void checkOverdueExist(OleLoanDocument oleLoanDocument) {
3489        Map<String, String> map = new HashMap<String, String>();
3490        map.put(OLEConstants.ITEM_BARCODE, oleLoanDocument.getItemId());
3491        map.put(OLEConstants.FEE_TYPE_FIELD, getOleFeeTypeCode(OLEConstants.FEE_TYPE_CODE_OVERDUE));
3492        List<FeeType> feeTypes = (List<FeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(FeeType.class, map);
3493        if (feeTypes != null && feeTypes.size() > 0) {
3494            for (FeeType feeType : feeTypes) {
3495                if (feeType.getBalFeeAmount().compareTo(OLEConstants.KUALI_BIGDECIMAL_DEF_VALUE) != 0) {
3496                    oleLoanDocument.setOverdueFineExist(true);
3497                    break;
3498                }
3499            }
3500        }
3501
3502    }
3503
3504    public String getOleFeeTypeCode(String typeCode){
3505        Map<String, String> map = new HashMap<String, String>();
3506        map.put(OLEConstants.FEE_TYPE_CODE, typeCode);
3507        List<OleFeeType> feeTypes = (List<OleFeeType>) KRADServiceLocator.getBusinessObjectService().findMatching(OleFeeType.class, map);
3508        if(CollectionUtils.isNotEmpty(feeTypes)){
3509            return feeTypes.get(0).getFeeTypeId();
3510        }
3511        return "";
3512    }
3513
3514    public void isItemLoanedByDifferentPatron(OleLoanDocument oleLoanDocument) {
3515        Map<String, String> map = new HashMap<String, String>();
3516        map.put(OLEConstants.OleDeliverRequest.ITEM_ID, oleLoanDocument.getItemId());
3517        List<OleLoanDocument> oleLoanDocuments = (List<OleLoanDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class, map);
3518        if (oleLoanDocuments != null && oleLoanDocuments.size() > 0) {
3519            for (OleLoanDocument loanDocument : oleLoanDocuments) {
3520                if (loanDocument.getItemId().equalsIgnoreCase(oleLoanDocument.getItemId()) && (oleLoanDocument.getPatronId() != loanDocument.getPatronId())) {
3521                    oleLoanDocument.setDifferentPatron(true);
3522                    break;
3523                }
3524            }
3525        }
3526    }
3527
3528    public void checkItemDamagedStatus(OleLoanDocument oleLoanDocument) {
3529        if (oleLoanDocument.getOleItem().isItemDamagedStatus()) {
3530            oleLoanDocument.setItemDamagedStatus(true);
3531        }
3532    }
3533
3534    public void isMissingPieceFlagActive(OleLoanDocument oleLoanDocument) {
3535        if (oleLoanDocument.getOleItem().isMissingPieceFlag()) {
3536            oleLoanDocument.setMissingPieceFlag(true);
3537        }
3538    }
3539
3540    public boolean isClaimsReturnedItem(String itemBarcode, OleLoanDocument oleLoanDocument) throws Exception {
3541       /* Map itemUuid = QueryServiceImpl.getInstance().getItemDetails(itemBarcode, oleLoanDocument.getItemUuid());
3542        oleLoanDocument.setInstanceUuid((String) itemUuid.get(OLEConstants.INSTANCE_UUID));
3543        oleLoanDocument.setItemUuid((String) itemUuid.get(OLEConstants.ITEM_UUID));
3544        oleLoanDocument.setBibUuid((String) itemUuid.get(OLEConstants.BIB_UUID));*/
3545        LOG.debug("Inside the addLoan method");
3546        org.kuali.ole.docstore.common.document.Item item = new ItemOleml();
3547        org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
3548        SearchResponse searchResponse = null;
3549        search_Params.getSearchConditions().add(search_Params.buildSearchCondition("phrase", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), item.ITEM_BARCODE, itemBarcode), ""));
3550        search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), "ItemIdentifier_display"));
3551        search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Holdings.HOLDINGSIDENTIFIER));
3552        search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.ITEM.getCode(), Bib.BIBIDENTIFIER));
3553        if (itemBarcode != null && !itemBarcode.isEmpty()) {
3554            searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
3555            if (searchResponse.getSearchResults() != null && searchResponse.getSearchResults().size() > 0) {
3556                for (SearchResult searchResult : searchResponse.getSearchResults()) {
3557                    for (SearchResultField searchResultField : searchResult.getSearchResultFields()) {
3558                        String fieldName = searchResultField.getFieldName();
3559                        String fieldValue = searchResultField.getFieldValue() != null ? searchResultField.getFieldValue() : "";
3560
3561                        if (fieldName.equalsIgnoreCase( Holdings.HOLDINGSIDENTIFIER) && !fieldValue.isEmpty()) {
3562                            oleLoanDocument.setInstanceUuid(fieldValue);
3563                        } else if (fieldName.equalsIgnoreCase( Bib.BIBIDENTIFIER) && !fieldValue.isEmpty()) {
3564                            oleLoanDocument.setBibUuid(fieldValue);
3565                        } else {
3566                            oleLoanDocument.setItemUuid(fieldValue);
3567                        }
3568
3569                    }
3570                }
3571            } else {
3572                throw new Exception(OLEConstants.ITM_BARCD_NT_AVAL_DOC);
3573            }
3574
3575
3576        } else {
3577
3578            item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(oleLoanDocument.getItemUuid());
3579
3580
3581            oleLoanDocument.setInstanceUuid(item.getHolding().getId());
3582            oleLoanDocument.setItemUuid(item.getId());
3583            oleLoanDocument.setBibUuid(item.getHolding().getBib().getId());
3584        }
3585        String itemXml = getItemXML(oleLoanDocument.getItemUuid());
3586        org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getItemPojo(itemXml);
3587
3588        org.kuali.ole.docstore.common.document.Item itemXML = new ItemOleml();
3589        itemXML.setContent(getItemOlemlRecordProcessor().toXML(oleItem));
3590        if (oleItem.isClaimsReturnedFlag()) {
3591            return true;
3592        }
3593        return false;
3594    }
3595
3596    public OleLoanForm processLoan(OleLoanForm oleLoanForm, OleLoanDocument oleLoanDocument) throws Exception {
3597        oleLoanDocument.setPatronId(oleLoanForm.getPatronId());
3598        oleLoanDocument.setProxyPatronId(oleLoanForm.getProxyPatronId());
3599        oleLoanDocument.setRealPatronBarcode(oleLoanForm.getRealPatronBarcode());
3600        oleLoanDocument.setRealPatronType(oleLoanForm.getRealPatronType());
3601        oleLoanDocument.setCirculationLocationId(oleLoanForm.getCirculationDesk());
3602        oleLoanDocument.setBorrowerTypeId(oleLoanForm.getBorrowerTypeId());
3603        oleLoanDocument.setBorrowerTypeName(oleLoanForm.getBorrowerType());
3604        oleLoanDocument.setBorrowerTypeCode(oleLoanForm.getBorrowerCode());
3605        List<OleLoanDocument> existingItemList = new ArrayList<OleLoanDocument>();
3606        oleLoanDocument = addLoan(oleLoanForm.getPatronBarcode(), oleLoanForm.getItem(), oleLoanDocument,null);
3607        oleLoanForm.setItemUuid(oleLoanDocument.getItemUuid());
3608        oleLoanForm.setNonCirculatingFlag(oleLoanDocument.isNonCirculatingItem());
3609        oleLoanForm.setInstanceUuid(oleLoanDocument.getInstanceUuid());
3610        oleLoanForm.setOleItem(oleLoanDocument.getOleItem());
3611        oleLoanForm.setDueDateMap(oleLoanDocument.getLoanDueDate());
3612        oleLoanForm.setMessage(oleLoanDocument.getErrorMessage());
3613        oleLoanForm.setRoleName(oleLoanDocument.getRoleName());
3614        oleLoanForm.getErrorsAndPermission().putAll(oleLoanDocument.getErrorsAndPermission());
3615        if (oleLoanForm.getPatronName() == null) {
3616            oleLoanForm.setPatronName(oleLoanDocument.getPatronName());
3617        }
3618        if(oleLoanForm.getRealPatronName()!=null){
3619            oleLoanDocument.setRealPatronName(oleLoanForm.getRealPatronName());
3620        }
3621        if (oleLoanDocument.getErrorMessage() == null) {
3622            existingItemList.add(oleLoanDocument);
3623            oleLoanForm.setBlockItem(false);
3624            oleLoanForm.setBlockPatron(false);
3625            oleLoanForm.setItem("");
3626            oleLoanForm.setInformation("");
3627        } else {
3628            oleLoanForm.setDueDateEmpty(oleLoanDocument.isDueDateEmpty());
3629            oleLoanForm.setDummyLoan(oleLoanDocument);
3630            oleLoanForm.setSuccess(false);
3631            if (oleLoanDocument.getOleItem() != null) {
3632                oleLoanForm.setDescription(oleLoanDocument.getOleItem().getCheckinNote());
3633            }
3634            oleLoanForm.setInformation("");
3635            setErrorFlagForItem(oleLoanDocument, oleLoanForm);
3636        }
3637        if (oleLoanForm.getLoanList() != null && !oleLoanForm.getLoanList().isEmpty()) {
3638            existingItemList.addAll(oleLoanForm.getLoanList());
3639        }
3640        if (oleLoanDocument.getItemLoanStatus() != null && oleLoanDocument.getItemLoanStatus().equalsIgnoreCase(OLEConstants.ITEM_STATUS_LOST)) {
3641            oleLoanForm.setBlockUser(true);
3642        }
3643        else if (oleLoanDocument.isOverdueFineExist() && oleLoanDocument.isDifferentPatron()) {
3644            oleLoanForm.setBlockUser(true);
3645        }else {
3646            oleLoanForm.setBlockUser(false);
3647        }
3648        oleLoanForm.setLoanList(existingItemList);
3649        List<OleLoanDocument> oleLoanDocumentList = new ArrayList<OleLoanDocument>();
3650        oleLoanDocumentList.add(oleLoanDocument);
3651
3652        if (getParameter(OLEConstants.PRINT_DUE_DATE_PER_TRANSACTION).equalsIgnoreCase("Yes")) {
3653            oleLoanForm.setDueDateSlip(true);
3654        }
3655        oleLoanForm.setItemFocus(true);
3656        oleLoanForm.setPatronFocus(false);
3657        String audioOption = getParameter(OLEConstants.AUDIO_OPTION);
3658        oleLoanForm.setAudioEnable(audioOption != null && !audioOption.isEmpty() && audioOption.equalsIgnoreCase(OLEConstants.TRUE));
3659        oleLoanForm.setItemUuid(null);
3660        oleLoanForm.setInstanceUuid(null);
3661        oleLoanForm.setSuccessMessage(oleLoanDocument.getSuccessMessage());
3662        return oleLoanForm;
3663    }
3664
3665    public void updateMissingPiecesItemInfo(OleLoanDocument oleLoanDocument) throws Exception {
3666        LOG.debug("Inside the updateItemStatus method for missing pieces");
3667        try {
3668            String itemXmlContent = getItemXML(oleLoanDocument.getItemUuid());
3669            org.kuali.ole.docstore.common.document.content.instance.Item item = getItemPojo(itemXmlContent);
3670            boolean isMissingPieceFlagEnabled=(item != null && item.isMissingPieceFlag())?true:false;
3671            item.setMissingPieceFlag(true);
3672            SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
3673            String parsedDate = df.format((new Date()));
3674            item.setMissingPieceEffectiveDate(parsedDate);
3675            if (oleLoanDocument.getMissingPieceNote() != null && !oleLoanDocument.getMissingPieceNote().isEmpty()) {
3676                item.setMissingPieceFlagNote(oleLoanDocument.getMissingPieceNote());
3677            }
3678            int newMissingPieceCount = 0;
3679            if (oleLoanDocument.getMissingPiecesCount() != null && !oleLoanDocument.getMissingPiecesCount().equalsIgnoreCase("")) {
3680                newMissingPieceCount = Integer.parseInt(oleLoanDocument.getMissingPiecesCount());
3681            }
3682            if (newMissingPieceCount == 0) {
3683                item.setMissingPiecesCount(item.getMissingPiecesCount());
3684            } else {
3685                if (oleLoanDocument.getOleItem() != null && oleLoanDocument.getOleItem().getMissingPiecesCount() != null && (!oleLoanDocument.getOleItem().getMissingPiecesCount().equalsIgnoreCase(""))) {
3686                    int oldMissingPieceCount = Integer.parseInt(item.getMissingPiecesCount());
3687                    item.setMissingPiecesCount(oldMissingPieceCount + newMissingPieceCount + "");
3688                } else {
3689                    item.setMissingPiecesCount(newMissingPieceCount + "");
3690                }
3691            }
3692            oleLoanDocument.setOleItem(item);
3693            if (item.isMissingPieceFlag() && !isMissingPieceFlagEnabled) {
3694                MissingPieceItemRecord missingPieceItemRecord = new MissingPieceItemRecord();
3695                missingPieceItemRecord.setMissingPieceFlagNote(oleLoanDocument.getMissingPieceNote());
3696                missingPieceItemRecord.setMissingPieceCount(oleLoanDocument.getMissingPiecesCount());
3697                missingPieceItemRecord.setMissingPieceDate(parsedDate);
3698                missingPieceItemRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
3699                missingPieceItemRecord.setPatronBarcode(oleLoanDocument.getPatronBarcode());
3700                missingPieceItemRecord.setItemId(oleLoanDocument.getItemUuid());
3701                if (CollectionUtils.isNotEmpty(item.getMissingPieceItemRecordList())) {
3702
3703                    item.getMissingPieceItemRecordList().add(missingPieceItemRecord);
3704                } else {
3705                    List<MissingPieceItemRecord> missingPieceItemRecords = new ArrayList<MissingPieceItemRecord>();
3706                    missingPieceItemRecords.add(missingPieceItemRecord);
3707                    item.setMissingPieceItemRecordList(missingPieceItemRecords);
3708                }
3709            }else{
3710                if(item.isMissingPieceFlag() && isMissingPieceFlagEnabled){
3711                    MissingPieceItemRecord missingPieceItemRecord = new MissingPieceItemRecord();
3712                    missingPieceItemRecord.setMissingPieceFlagNote(oleLoanDocument.getMissingPieceNote());
3713                    missingPieceItemRecord.setMissingPieceCount(oleLoanDocument.getMissingPiecesCount());
3714                    missingPieceItemRecord.setMissingPieceDate(parsedDate);
3715                    missingPieceItemRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
3716                    missingPieceItemRecord.setPatronBarcode(oleLoanDocument.getPatronBarcode());
3717                    missingPieceItemRecord.setItemId(oleLoanDocument.getItemUuid());
3718                    if(CollectionUtils.isNotEmpty(item.getMissingPieceItemRecordList())){
3719
3720                        item.getMissingPieceItemRecordList().add(missingPieceItemRecord);
3721                    } else {
3722                        List<MissingPieceItemRecord> missingPieceItemRecords=new ArrayList<MissingPieceItemRecord>();
3723                        missingPieceItemRecords.add(missingPieceItemRecord);
3724                        item.setMissingPieceItemRecordList(missingPieceItemRecords);
3725                    }
3726                }
3727            }
3728            itemXmlContent = getItemOlemlRecordProcessor().toXML(item);
3729            if (LOG.isDebugEnabled()){
3730                LOG.debug("itemXmlContent" + itemXmlContent);
3731            }
3732            Item oleItem = new ItemOleml();
3733            oleItem.setContent(itemXmlContent);
3734            oleItem.setCategory(OLEConstants.WORK_CATEGORY);
3735            oleItem.setType(DocType.ITEM.getCode());
3736            oleItem.setFormat(OLEConstants.OLEML_FORMAT);
3737            oleItem.setId(oleLoanDocument.getItemUuid());
3738            getDocstoreClientLocator().getDocstoreClient().updateItem(oleItem);
3739        } catch (Exception e) {
3740            LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
3741            throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
3742        }
3743    }
3744
3745
3746   /* public HashMap<String,Integer> getItemTypeMap(List<OleLoanDocument> oleLoanDocuments,OleLoanDocument currentLoan){
3747        Long begin = System.currentTimeMillis();
3748        HashMap<String,Integer> itemTypeMap = new HashMap<>();
3749        for(OleLoanDocument oleLoanDocument : oleLoanDocuments){
3750            if(itemTypeMap.containsKey(oleLoanDocument.getItemType())){
3751                Integer count = itemTypeMap.get(oleLoanDocument.getItemType());
3752                count++;
3753                itemTypeMap.put(oleLoanDocument.getItemType(),count);
3754            }else{
3755                itemTypeMap.put(oleLoanDocument.getItemType(),1);
3756            }
3757        }
3758        if(itemTypeMap.containsKey(currentLoan.getItemType())){
3759            Integer count = itemTypeMap.get(currentLoan.getItemType());
3760            count++;
3761            itemTypeMap.put(currentLoan.getItemType(),count);
3762        }else{
3763            itemTypeMap.put(currentLoan.getItemType(),1);
3764        }
3765        Long end = System.currentTimeMillis();
3766        Long timeTaken = end - begin;
3767        LOG.info("The Time Taken for getItemTypeMap in Add Item"+timeTaken);
3768        return itemTypeMap;
3769    }*/
3770
3771
3772    public HashMap<String,Integer> getItemTypeFromCurrentLoan(HashMap<String,Integer> itemTypeMap,OleLoanDocument currentLoan){
3773        if(itemTypeMap!=null){
3774            if(itemTypeMap.containsKey(currentLoan.getItemType())){
3775                Integer count = itemTypeMap.get(currentLoan.getItemType());
3776                count++;
3777                itemTypeMap.put(currentLoan.getItemType(),count);
3778            }else{
3779                itemTypeMap.put(currentLoan.getItemType(),1);
3780            }
3781        }
3782        return itemTypeMap;
3783    }
3784
3785    private String getPaymentStatusId(String paymentStatusCode) throws Exception{
3786        Map<String,String> mapPayStatus = new HashMap();
3787        mapPayStatus.put(OLEConstants.PAY_STATUS_CODE,paymentStatusCode);
3788        List<OlePaymentStatus> patronBillPayments = (List<OlePaymentStatus>)getBusinessObjectService().findMatching(OlePaymentStatus.class, mapPayStatus);
3789        return CollectionUtils.isNotEmpty(patronBillPayments)?patronBillPayments.get(0).getPaymentStatusId():"";
3790    }
3791
3792    public boolean checkPatronBill(String patronId)throws Exception{
3793        Map map = new HashMap();
3794        map.put(OLEConstants.PTRN_ID, patronId);
3795        map.put(OLEConstants.FEE_TYPE_PAY_STATUS, getPaymentStatusId(OLEConstants.PAY_STATUS_OUTSTANDING_CODE));
3796        List<PatronBillPayment> patronBillPayments = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, map);
3797        if (patronBillPayments != null && patronBillPayments.size() > 0) {
3798            return true;
3799        } else {
3800            map.clear();
3801            map.put(OLEConstants.PTRN_ID, patronId);
3802            map.put(OLEConstants.FEE_TYPE_PAY_STATUS, getPaymentStatusId(OLEConstants.PAY_STATUS_PART_CODE));
3803            List<PatronBillPayment> payments = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, map);
3804            if (payments != null && payments.size() > 0) {
3805                return true;
3806            }
3807        }
3808        return false;
3809    }
3810
3811    public String getItemStatus() {
3812        return itemStatus;
3813    }
3814
3815    public void setItemStatus(String itemStatus) {
3816        this.itemStatus = itemStatus;
3817    }
3818
3819
3820    /**
3821     * This method is used to set the check-in date in the replacement fee bill generated throuigh batch job
3822     * @param oleLoanDocument
3823     */
3824
3825    public void updateReplacementFeeBill(OleLoanDocument oleLoanDocument){
3826        long begin = System.currentTimeMillis();
3827        if(LOG.isInfoEnabled()){
3828       LOG.info("Inside the updateReplacementFee for the patron barcode :"+oleLoanDocument.getPatronBarcode() + "Item Barcode : " +oleLoanDocument.getItemId() );
3829        }
3830        Map map=new HashMap<String,String>();
3831        map.put(OLEConstants.FEE_TYPE_PATRON_ID,oleLoanDocument.getPatronId());
3832        map.put(OLEConstants.ITEM_BARCODE,oleLoanDocument.getItemId());
3833        map.put(OLEConstants.FEE_TYPE_FIELD, "2");
3834        List<FeeType> feeTypeList = (List<FeeType>) getBusinessObjectService().findMatching(FeeType.class, map);
3835        if(feeTypeList!=null && feeTypeList.size()>0){
3836            for(FeeType feeType:feeTypeList){
3837            if(feeType.getDueDate()!=null && oleLoanDocument.getLoanDueDate()!=null){
3838                if(feeType.getDueDate().getTime()==oleLoanDocument.getLoanDueDate().getTime()){
3839                    feeType.setCheckInDate(oleLoanDocument.getCheckInDate());
3840                    getBusinessObjectService().save(feeType);
3841                    break;
3842                }
3843            }
3844
3845            }
3846        }
3847        long end = System.currentTimeMillis();
3848        long total = end - begin;
3849        LOG.info("Time taken Inside updateReplacementFeeBill"+total);
3850    }
3851
3852    public OleLoanDocumentDaoOjb getOleLoanDocumentDaoOjb() {
3853        if(oleLoanDocumentDaoOjb == null){
3854            oleLoanDocumentDaoOjb = (OleLoanDocumentDaoOjb)SpringContext.getBean("oleLoanDao");
3855        }
3856        return oleLoanDocumentDaoOjb;
3857    }
3858
3859    public void setOleLoanDocumentDaoOjb(OleLoanDocumentDaoOjb oleLoanDocumentDaoOjb) {
3860        this.oleLoanDocumentDaoOjb = oleLoanDocumentDaoOjb;
3861    }
3862
3863    public void validateCalanderForCirculationDesk(String circulationDeskLocationId) throws Exception{
3864        OleCirculationDesk oleCirculationDesk = getCircDeskLocationResolver().getOleCirculationDesk(circulationDeskLocationId);
3865        if (oleCirculationDesk != null && oleCirculationDesk.getCalendarGroupId() != null) {
3866            OleCalendarService oleCalendarService = new OleCalendarServiceImpl();
3867            OleCalendar oleCalendar = oleCalendarService.getActiveCalendar(new Timestamp(System.currentTimeMillis()), oleCirculationDesk.getCalendarGroupId());
3868            if (oleCalendar == null) {
3869                throw new Exception("Calendar does not exist");
3870            }
3871        }
3872       /* getDataCarrierService().addData(OLEConstants.GROUP_ID, oleCirculationDesk != null ? oleCirculationDesk.getCalendarGroupId() : "");*/
3873    }
3874
3875    public OleLoanDocument retrieveByPatronAndItem(String patronId,String itemBarcode) throws Exception{
3876        LOG.debug("Inside the retrieveByPatronAndItem method");
3877        Long b1 = System.currentTimeMillis();
3878        List<OleLoanDocument> patronLoanedItemBySolr = getOleLoanDocumentsFromSolrBuilder().getPatronLoanedItemBySolr(patronId, itemBarcode);
3879        Long b2 = System.currentTimeMillis();
3880        Long b3 = b2-b1;
3881        LOG.info("The Time taken retrieveByPatronAndItem--"+b3);
3882        return patronLoanedItemBySolr!=null && patronLoanedItemBySolr.size()>0 ? patronLoanedItemBySolr.get(0) : null;
3883    }
3884
3885    private OleLoanDocumentsFromSolrBuilder getOleLoanDocumentsFromSolrBuilder() {
3886        if (null == oleLoanDocumentsFromSolrBuilder) {
3887            oleLoanDocumentsFromSolrBuilder = new OleLoanDocumentsFromSolrBuilder();
3888        }
3889        return oleLoanDocumentsFromSolrBuilder;
3890    }
3891
3892    public void setOleLoanDocumentsFromSolrBuilder(OleLoanDocumentsFromSolrBuilder oleLoanDocumentsFromSolrBuilder) {
3893        this.oleLoanDocumentsFromSolrBuilder = oleLoanDocumentsFromSolrBuilder;
3894    }
3895
3896    public OLEDeliverNoticeHelperService getOleDeliverNoticeHelperService() {
3897        return oleDeliverNoticeHelperService;
3898    }
3899
3900    public void setOleDeliverNoticeHelperService(OLEDeliverNoticeHelperService oleDeliverNoticeHelperService) {
3901        this.oleDeliverNoticeHelperService = oleDeliverNoticeHelperService;
3902    }
3903
3904
3905
3906
3907
3908    public void updateInTransitHistory(OleLoanDocument oleLoanDocument,String routeToLocation){
3909        if (StringUtils.isNotEmpty(oleLoanDocument.getItemStatusCode()) && (oleLoanDocument.getItemStatusCode().equalsIgnoreCase(OLEConstants.ITEM_STATUS_IN_TRANSIT) || oleLoanDocument.getItemStatusCode().equalsIgnoreCase(OLEConstants.ITEM_STATUS_IN_TRANSIT_HOLD))) {
3910            OLELoanIntransitRecordHistory oleLoanIntransitRecordHistory = new OLELoanIntransitRecordHistory();
3911            oleLoanIntransitRecordHistory.setItemBarcode(oleLoanDocument.getItemId());
3912            oleLoanIntransitRecordHistory.setItemUUID(oleLoanDocument.getItemUuid());
3913            OleLocation oleLocation=null;
3914            try{
3915                oleLocation = getCircDeskLocationResolver().getLocationByLocationCode(oleLoanDocument.getItemLocation());
3916            }
3917            catch (Exception e){
3918                LOG.error("Exception while fetching OleLocation based on item location" +e);
3919            }
3920            String routeTo = routeToLocation != null ? routeToLocation :
3921                    (oleLoanDocument.getRouteToLocation() != null ? oleLoanDocument.getRouteToLocation() :
3922                            (oleLocation != null ? oleLocation.getLocationCode() : null));
3923            oleLoanIntransitRecordHistory.setRouteCirculationDesk(routeTo);
3924            oleLoanIntransitRecordHistory.setOperator(GlobalVariables.getUserSession().getPrincipalId());
3925            oleLoanIntransitRecordHistory.setHomeCirculationDesk(oleLoanDocument.getOleCirculationDesk().getCirculationDeskCode());
3926            oleLoanIntransitRecordHistory.setReturnedDateTime(oleLoanDocument.getCheckInDate());
3927            KRADServiceLocator.getBusinessObjectService().save(oleLoanIntransitRecordHistory);
3928        }
3929    }
3930
3931    public DateTimeService getDateTimeService() {
3932        return (DateTimeService)SpringContext.getService("dateTimeService");
3933    }
3934
3935    public void updateClaimsReturnedHistory(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument loanObject, String patronId) {
3936        ItemClaimsReturnedRecord itemClaimsReturnedRecord = new ItemClaimsReturnedRecord();
3937        List<ItemClaimsReturnedRecord> itemClaimsReturnedRecords = new ArrayList<>();
3938        Map<String,String> criteria = new HashMap<>();
3939        criteria.put("olePatronId",patronId);
3940        OlePatronDocument olePatronDocument = getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class,criteria);
3941        String patronBarcode = olePatronDocument.getBarcode();
3942        if(!oleItem.isClaimsReturnedFlag()){
3943            if (loanObject.getClaimsReturnedDate() != null) {
3944                itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(convertToString(loanObject.getClaimsReturnedDate()));
3945            }
3946            else{
3947                DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
3948                itemClaimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
3949            }
3950            itemClaimsReturnedRecord.setClaimsReturnedNote(loanObject.getClaimsReturnNote());
3951            itemClaimsReturnedRecord.setClaimsReturnedPatronBarcode(patronBarcode);
3952            itemClaimsReturnedRecord.setClaimsReturnedOperatorId(GlobalVariables.getUserSession().getPrincipalId());
3953            itemClaimsReturnedRecord.setItemId(loanObject.getItemUuid());
3954            if(oleItem.getItemClaimsReturnedRecords() != null && oleItem.getItemClaimsReturnedRecords().size() > 0){
3955                oleItem.getItemClaimsReturnedRecords().add(itemClaimsReturnedRecord);
3956            }
3957            else{
3958                itemClaimsReturnedRecords.add(itemClaimsReturnedRecord);
3959                oleItem.setItemClaimsReturnedRecords(itemClaimsReturnedRecords);
3960            }
3961        }else{
3962            Map<String,String> map = new HashMap<>();
3963            map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(loanObject.getItemUuid()));
3964            List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord> claimsReturnedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord>) getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemClaimsReturnedRecord.class, map, "claimsReturnedId", true);
3965            List<ItemClaimsReturnedRecord> itemClaimsReturnedRecordList = new ArrayList<>();
3966            for(int index=0 ; index < claimsReturnedRecordList.size() ; index++){
3967                ItemClaimsReturnedRecord claimsReturnedRecord = new ItemClaimsReturnedRecord();
3968                if(index == claimsReturnedRecordList.size()-1){
3969                    if (loanObject.getClaimsReturnedDate() != null) {
3970                        claimsReturnedRecord.setClaimsReturnedFlagCreateDate(convertToString(loanObject.getClaimsReturnedDate()));
3971                    }
3972                    else{
3973                        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
3974                        claimsReturnedRecord.setClaimsReturnedFlagCreateDate(df.format(getDateTimeService().getCurrentDate()));
3975                    }
3976                    claimsReturnedRecord.setClaimsReturnedNote(loanObject.getClaimsReturnNote());
3977                    claimsReturnedRecord.setClaimsReturnedPatronBarcode(patronBarcode);
3978                    claimsReturnedRecord.setClaimsReturnedOperatorId(GlobalVariables.getUserSession().getPrincipalId());
3979                    claimsReturnedRecord.setItemId(loanObject.getItemUuid());
3980                } else {
3981                    if (claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate() != null && !claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString().isEmpty()) {
3982                        SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
3983                        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
3984                        Date claimsReturnedDate = null;
3985                        try {
3986                            claimsReturnedDate = format2.parse(claimsReturnedRecordList.get(index).getClaimsReturnedFlagCreateDate().toString());
3987                        } catch (ParseException e) {
3988                            LOG.error("format string to Date " + e);
3989                        }
3990                        claimsReturnedRecord.setClaimsReturnedFlagCreateDate(format1.format(claimsReturnedDate).toString());
3991                    }
3992                    claimsReturnedRecord.setClaimsReturnedNote(claimsReturnedRecordList.get(index).getClaimsReturnedNote());
3993                    claimsReturnedRecord.setClaimsReturnedPatronBarcode(claimsReturnedRecordList.get(index).getClaimsReturnedPatronBarcode());
3994                    claimsReturnedRecord.setClaimsReturnedOperatorId(claimsReturnedRecordList.get(index).getClaimsReturnedOperatorId());
3995                    claimsReturnedRecord.setItemId(claimsReturnedRecordList.get(index).getItemId());
3996                }
3997                itemClaimsReturnedRecordList.add(claimsReturnedRecord);
3998            }
3999            oleItem.setItemClaimsReturnedRecords(itemClaimsReturnedRecordList);
4000        }
4001    }
4002
4003    public void updateItemDamagedHistory(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, OleLoanDocument oleLoanDocument, String patronId) {
4004        ItemDamagedRecord itemDamagedRecord = new ItemDamagedRecord();
4005        List<ItemDamagedRecord> itemDamagedRecords = new ArrayList<>();
4006        Map<String,String> criteria = new HashMap<>();
4007        criteria.put("olePatronId",patronId);
4008        OlePatronDocument olePatronDocument = getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class,criteria);
4009        String patronBarcode = olePatronDocument.getBarcode();
4010        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
4011        if(!oleItem.isItemDamagedStatus()){
4012            itemDamagedRecord.setDamagedItemNote(oleLoanDocument.getItemDamagedNote());
4013            itemDamagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
4014            itemDamagedRecord.setPatronBarcode(patronBarcode);
4015            itemDamagedRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
4016            itemDamagedRecord.setItemId(oleLoanDocument.getItemUuid());
4017            if(oleItem.getItemDamagedRecords() != null && oleItem.getItemDamagedRecords().size() > 0){
4018                oleItem.getItemDamagedRecords().add(itemDamagedRecord);
4019            } else {
4020                itemDamagedRecords.add(itemDamagedRecord);
4021                oleItem.setItemDamagedRecords(itemDamagedRecords);
4022            }
4023        } else {
4024            Map<String,String> map = new HashMap<>();
4025            map.put("itemId", DocumentUniqueIDPrefix.getDocumentId(oleLoanDocument.getItemUuid()));
4026            List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord> itemDamagedRecordList = (List<org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord>) getBusinessObjectService().findMatchingOrderBy(org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemDamagedRecord.class, map, "itemDamagedId", true);
4027            List<ItemDamagedRecord> damagedRecordList = new ArrayList<>();
4028            for(int index=0 ; index < itemDamagedRecordList.size() ; index++){
4029                ItemDamagedRecord damagedRecord = new ItemDamagedRecord();
4030                if(index == itemDamagedRecordList.size()-1){
4031                    damagedRecord.setDamagedItemNote(oleLoanDocument.getItemDamagedNote());
4032                    damagedRecord.setDamagedItemDate(df.format(getDateTimeService().getCurrentDate()));
4033                    damagedRecord.setPatronBarcode(patronBarcode);
4034                    damagedRecord.setOperatorId(GlobalVariables.getUserSession().getPrincipalId());
4035                    damagedRecord.setItemId(oleLoanDocument.getItemUuid());
4036                } else {
4037                    if (itemDamagedRecordList.get(index).getDamagedItemDate() != null && !itemDamagedRecordList.get(index).getDamagedItemDate().toString().isEmpty()) {
4038                        SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
4039                        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
4040                        Date itemDamagedDate = null;
4041                        try {
4042                            itemDamagedDate = format2.parse(itemDamagedRecordList.get(index).getDamagedItemDate().toString());
4043                        } catch (ParseException e) {
4044                            LOG.error("format string to Date " + e);
4045                        }
4046                        damagedRecord.setDamagedItemDate(format1.format(itemDamagedDate).toString());
4047                    }
4048                    damagedRecord.setDamagedItemNote(itemDamagedRecordList.get(index).getDamagedItemNote());
4049                    damagedRecord.setPatronBarcode(itemDamagedRecordList.get(index).getPatronBarcode());
4050                    damagedRecord.setOperatorId(itemDamagedRecordList.get(index).getOperatorId());
4051                    damagedRecord.setItemId(itemDamagedRecordList.get(index).getItemId());
4052                }
4053                damagedRecordList.add(damagedRecord);
4054            }
4055            oleItem.setItemDamagedRecords(damagedRecordList);
4056        }
4057    }
4058
4059    private String getLocations(Location location) {
4060        String locationName = "";
4061        String locationLevelName = "";
4062        LocationLevel locationLevel = location.getLocationLevel();
4063        if (locationLevel != null) {
4064            while (locationLevel!=null) {
4065                if (locationName.equalsIgnoreCase("") || (locationLevel.getLevel()!=null && !locationLevel.getName().equalsIgnoreCase(locationLevelName))) {
4066                    locationLevelName = locationLevel.getName();
4067                    locationName += locationLevel.getName()+"/";
4068                } else {
4069                    locationLevel = locationLevel.getLocationLevel();
4070                }
4071
4072            }
4073        }
4074        if(locationName.length()>0){
4075            locationName = locationName.substring(0,locationName.length()-1);
4076        }
4077        return locationName;
4078    }
4079
4080
4081    private String getLocationId(String itemFullLocationPath){
4082        String[] locations = itemFullLocationPath.split("/");
4083        String locationId = null;
4084        List<OleLocation> oleLocationList ;
4085        Map<String,String> locationMap;
4086        if(locations.length>0){
4087            locationMap = new HashMap<String,String>();
4088            String locationCode = locations[locations.length-1];
4089            locationMap.put("locationCode",locationCode);
4090            oleLocationList = (List<OleLocation>)getBusinessObjectService().findMatching(OleLocation.class,locationMap);
4091            if(oleLocationList!=null && oleLocationList.size()>0){
4092                locationId = oleLocationList.get(0).getLocationId();
4093            }
4094        }
4095        return locationId;
4096    }
4097
4098}
4099
4100