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