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