001package org.kuali.ole.deliver.service;
002
003import org.apache.log4j.Logger;
004import org.kuali.ole.DataCarrierService;
005import org.kuali.ole.LoanUtil;
006import org.kuali.ole.OLEConstants;
007import org.kuali.ole.OLEParameterConstants;
008import org.kuali.ole.deliver.batch.OleDeliverBatchServiceImpl;
009import org.kuali.ole.deliver.batch.OleMailer;
010import org.kuali.ole.deliver.batch.OleNoticeBo;
011import org.kuali.ole.deliver.batch.OleSms;
012import org.kuali.ole.deliver.bo.*;
013import org.kuali.ole.deliver.processor.LoanProcessor;
014import org.kuali.ole.describe.bo.OleInstanceItemType;
015import org.kuali.ole.describe.service.DocstoreHelperService;
016import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
017import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.Item;
018import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.ItemStatus;
019import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.Location;
020import org.kuali.ole.docstore.model.xmlpojo.work.instance.oleml.LocationLevel;
021import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
022import org.kuali.ole.ingest.pojo.MatchBo;
023import org.kuali.rice.core.api.mail.EmailBody;
024import org.kuali.rice.core.api.mail.EmailFrom;
025import org.kuali.rice.core.api.mail.EmailSubject;
026import org.kuali.rice.core.api.mail.EmailTo;
027import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
028import org.kuali.rice.coreservice.impl.parameter.ParameterBo;
029import org.kuali.rice.kim.api.permission.PermissionService;
030import org.kuali.rice.kim.api.services.KimApiServiceLocator;
031import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
032import org.kuali.rice.krad.service.BusinessObjectService;
033import org.kuali.rice.krad.service.KRADServiceLocator;
034import org.kuali.rice.krad.util.ObjectUtils;
035import org.kuali.rice.krms.api.KrmsApiServiceLocator;
036import org.kuali.rice.krms.api.engine.*;
037import org.kuali.rice.krms.impl.repository.AgendaBo;
038
039import java.math.BigDecimal;
040import java.sql.Timestamp;
041import java.text.DateFormat;
042import java.text.SimpleDateFormat;
043import java.util.*;
044
045/**
046 * Created with IntelliJ IDEA.
047 * User: ?
048 * Date: 10/24/12
049 * Time: 10:27 AM
050 * To change this template use File | Settings | File Templates.
051 */
052public class OleDeliverRequestDocumentHelperServiceImpl {
053    private static final Logger LOG = Logger.getLogger(OleDeliverRequestDocumentHelperServiceImpl.class);
054    private static final String NAMESPACE_CODE_SELECTOR = "namespaceCode";
055    private static final String NAME_SELECTOR = "name";
056    private final static String RULE_EVALUATED = "Rule Evaluated";
057    private final static String ROUTED_EXTERNAL = "Routed External";
058    private BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
059    private int queuePosition = 0;
060    private LoanProcessor loanProcessor = new LoanProcessor();
061    private DocstoreHelperService docstoreHelperService = new DocstoreHelperService();
062
063    private PermissionService getPermissionService() {
064        PermissionService service = KimApiServiceLocator.getPermissionService();
065        return service;
066    }
067
068    /**
069     * Gets the docstoreHelperService attribute.
070     *
071     * @return Returns the docstoreHelperService
072     */
073    private DocstoreHelperService getDocstoreHelperService() {
074        if (null == docstoreHelperService) {
075            return new DocstoreHelperService();
076        }
077        return docstoreHelperService;
078    }
079
080    /**
081     * Gets the businessObjectService attribute.
082     *
083     * @return Returns the businessObjectService
084     */
085    private BusinessObjectService getBusinessObjectService() {
086        if (null == businessObjectService) {
087            businessObjectService = KRADServiceLocator.getBusinessObjectService();
088        }
089        return businessObjectService;
090    }
091
092    public void setbusinessObjectService(BusinessObjectService businessObjectService) {
093        this.businessObjectService = businessObjectService;
094    }
095
096    public LoanProcessor getLoanProcessor() {
097        return loanProcessor;
098    }
099
100    public void setLoanProcessor(LoanProcessor loanProcessor) {
101        this.loanProcessor = loanProcessor;
102    }
103
104    /**
105     * This method is used to change the request type based on selection of  pick up  location
106     *
107     * @param oleDeliverRequestBo
108     * @return oleDeliverRequestBo
109     */
110    public OleDeliverRequestBo processRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
111
112        LOG.debug("Inside processRequestType for the Request id :" + oleDeliverRequestBo.getRequestId());
113        oleDeliverRequestBo = processPatron(oleDeliverRequestBo);
114        oleDeliverRequestBo = processItem(oleDeliverRequestBo);
115        if (oleDeliverRequestBo.getRequestTypeId() != null) {
116            if (oleDeliverRequestBo.getRequestTypeId().equals("3") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
117                oleDeliverRequestBo.setRequestTypeId("4");
118            } else if (oleDeliverRequestBo.getRequestTypeId().equals("5") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
119                oleDeliverRequestBo.setRequestTypeId("6");
120            } else if (oleDeliverRequestBo.getRequestTypeId().equals("1") && oleDeliverRequestBo.getPickUpLocationId() != null && !oleDeliverRequestBo.getPickUpLocationId().isEmpty()) {
121                oleDeliverRequestBo.setRequestTypeId("2");
122            }
123        }
124        return oleDeliverRequestBo;
125    }
126
127
128    /**
129     * This is to create a new patron object if the user enters the operator Id manually
130     *
131     * @param oleDeliverRequestBo
132     * @return deliver
133     */
134    public OleDeliverRequestBo processPatron(OleDeliverRequestBo oleDeliverRequestBo) {
135        LOG.debug("Inside processPatron");
136        OleDeliverRequestBo deliver = oleDeliverRequestBo;
137
138        if (oleDeliverRequestBo.getBorrowerBarcode() != null || oleDeliverRequestBo.getProxyBorrowerBarcode() != null) {
139            Map<String, String> patronMap = new HashMap<String, String>();
140            patronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getBorrowerBarcode());
141            List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
142            if (olePatronDocumentList != null && olePatronDocumentList.size() > 0) {
143                deliver.setOlePatron(olePatronDocumentList.get(0));
144                deliver.setBorrowerName(olePatronDocumentList.get(0).getPatronName());
145                deliver.setBorrowerId(olePatronDocumentList.get(0).getOlePatronId());
146            } else if (olePatronDocumentList != null && olePatronDocumentList.size() == 0) {
147                deliver.setBorrowerId(null);
148                deliver.setFirstName(null);
149                deliver.setLastName(null);
150                deliver.setOlePatron(null);
151                deliver.setBorrowerName(null);
152                deliver.setBorrowerBarcode(null);
153            }
154            if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
155                Map<String, String> proxyPatronMap = new HashMap<String, String>();
156                proxyPatronMap.put(OLEConstants.OleDeliverRequest.PATRON_BARCODE, oleDeliverRequestBo.getProxyBorrowerBarcode());
157                List<OlePatronDocument> oleProxyPatronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, proxyPatronMap);
158                if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() > 0) {
159                    deliver.setOleProxyPatron(oleProxyPatronDocumentList.get(0));
160                    deliver.setProxyBorrowerName(oleProxyPatronDocumentList.get(0).getPatronName());
161                    deliver.setProxyBorrowerId(oleProxyPatronDocumentList.get(0).getOlePatronId());
162                } else if (oleProxyPatronDocumentList != null && oleProxyPatronDocumentList.size() == 0) {
163                    deliver.setProxyBorrowerId(null);
164                    deliver.setProxyBorrowerName(null);
165                    deliver.setOleProxyPatron(null);
166                }
167            }
168
169        }
170
171        return deliver;
172    }
173
174    public boolean processOperator(OleDeliverRequestBo oleDeliverRequestBo) {
175        if (getPermissionService().hasPermission(oleDeliverRequestBo.getOperatorCreateId(), OLEConstants.OlePatron.PATRON_NAMESPACE, OLEConstants.CAN_LOAN)) {
176            return true;
177        }
178        return false;
179    }
180
181    /**
182     * This is to check whether the pick up location is selected for the hold type of Request
183     *
184     * @param oleDeliverRequestBo
185     * @return validRequest
186     */
187    public boolean validateRequestType(OleDeliverRequestBo oleDeliverRequestBo) {
188        LOG.debug("Inside validateRequestType");
189        boolean validRequest = true;
190        if ((oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) && (oleDeliverRequestBo.getPickUpLocationId() == null) || (oleDeliverRequestBo.getPickUpLocationId() != null && oleDeliverRequestBo.getPickUpLocationId().isEmpty())) {
191            validRequest = false;
192        }
193        return validRequest;
194    }
195
196
197    /**
198     * This is to check whether the patron is having delivery privilege or not
199     *
200     * @param oleDeliverRequestBo
201     * @return hasDeliveryPrivilege
202     */
203    public boolean validateDeliveryPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
204        LOG.debug("Inside validateDeliveryPrivilege");
205        boolean hasDeliveryPrivilege = true;
206        if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("3") || oleDeliverRequestBo.getRequestTypeId().equals("5")) {
207            if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege()) {
208                hasDeliveryPrivilege = false;
209            }
210        } else if (oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("4") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
211            if (oleDeliverRequestBo.getOlePatron() != null && !oleDeliverRequestBo.getOlePatron().isDeliveryPrivilege() && oleDeliverRequestBo.getPickUpLocationId() == null) {
212                hasDeliveryPrivilege = false;
213            }
214        }
215        return hasDeliveryPrivilege;
216    }
217
218
219    /**
220     * This is to check whether the patron is having paging privilege or not
221     *
222     * @param oleDeliverRequestBo
223     * @return hasPagePrivilege
224     */
225    public boolean validatePagingPrivilege(OleDeliverRequestBo oleDeliverRequestBo) {
226        LOG.debug("Inside validatePagingPrivilege");
227        boolean hasPagePrivilege = true;
228        if (oleDeliverRequestBo.getRequestTypeId().equals("5") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
229            if (!oleDeliverRequestBo.getOlePatron().isPagingPrivilege()) {
230                hasPagePrivilege = false;
231            }
232        }
233        return hasPagePrivilege;
234    }
235
236
237    /**
238     * This for setting the null values for the unselected requester
239     *
240     * @param oleDeliverRequestBo
241     * @return oleDeliverRequestBo
242     */
243    public OleDeliverRequestBo processRequester(OleDeliverRequestBo oleDeliverRequestBo) {
244        LOG.debug("Inside processRequester");
245        if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PATRON)) {
246            oleDeliverRequestBo.setProxyBorrowerId(null);
247            oleDeliverRequestBo.setOleProxyPatron(null);
248            oleDeliverRequestBo.setOperatorCreateId(null);
249            oleDeliverRequestBo.setOperatorCreator(null);
250        } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_PROXY_PATRON)) {
251            oleDeliverRequestBo.setOperatorCreateId(null);
252            oleDeliverRequestBo.setOperatorCreator(null);
253        } else if (oleDeliverRequestBo.getRequestCreator().equals(OLEConstants.OleDeliverRequest.REQUESTER_OPERATOR)) {
254            oleDeliverRequestBo.setProxyBorrowerId(null);
255            oleDeliverRequestBo.setOleProxyPatron(null);
256        }
257        return oleDeliverRequestBo;
258    }
259
260
261    /**
262     * This is to check whether the login patron is the proxy patron for the real patron
263     *
264     * @param oleDeliverRequestBo
265     * @return validProxy
266     */
267    public boolean isValidProxyPatron(OleDeliverRequestBo oleDeliverRequestBo) {
268        LOG.debug("Inside isValidProxyPatron");
269        boolean validProxy = true;
270        Map<String, String> proxyMap = new HashMap<String, String>();
271        proxyMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
272        proxyMap.put(OLEConstants.OleDeliverRequest.PROXY_PATRON_ID, oleDeliverRequestBo.getProxyBorrowerId());
273        if (oleDeliverRequestBo.getProxyBorrowerId() != null && !oleDeliverRequestBo.getProxyBorrowerId().isEmpty()) {
274            List<OleProxyPatronDocument> proxyPatronDocuments = (List<OleProxyPatronDocument>) businessObjectService.findMatching(OleProxyPatronDocument.class, proxyMap);
275            if (proxyPatronDocuments.size() == 0) {
276                validProxy = false;
277            }
278        }
279        return validProxy;
280    }
281
282
283    /**
284     * This is to check whether the request is already raised by the patron for this item
285     *
286     * @param oleDeliverRequestBo
287     * @return alreadyExist
288     */
289    public boolean isRequestAlreadyRaisedByPatron(OleDeliverRequestBo oleDeliverRequestBo) {
290        LOG.debug("Inside isRequestAlreadyRaised");
291        boolean alreadyExist = false;
292        Map<String, String> requestMap = new HashMap<String, String>();
293        requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, oleDeliverRequestBo.getBorrowerId());
294        requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
295        List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
296        if (deliverRequestBos != null && deliverRequestBos.size() > 0) {
297            alreadyExist = true;
298        }
299        return alreadyExist;
300    }
301
302
303    /**
304     * This is to check whether the requested item is currently in loan to the requesting patron
305     *
306     * @param oleDeliverRequestBo
307     * @return alreadyLoaned
308     */
309    public boolean isAlreadyLoaned(OleDeliverRequestBo oleDeliverRequestBo) {
310        LOG.debug("Inside isAlreadyLoaned");
311        boolean alreadyLoaned = false;
312        Map<String, String> loanMap = new HashMap<String, String>();
313        loanMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, oleDeliverRequestBo.getBorrowerId());
314        loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
315        List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) businessObjectService.findMatching(OleLoanDocument.class, loanMap);
316        if (loanDocuments != null && loanDocuments.size() > 0) {
317            alreadyLoaned = true;
318        }
319        return alreadyLoaned;
320    }
321
322
323    /**
324     * This is to check whether the item is available in the desk or not
325     *
326     * @param oleDeliverRequestBo
327     * @return itemAvailable
328     */
329    public boolean isItemAvailable(OleDeliverRequestBo oleDeliverRequestBo) {
330        LOG.debug("Inside isItemAvailable");
331        boolean itemAvailable = false;
332        Map<String, String> loanItemMap = new HashMap<String, String>();
333        loanItemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
334        List<OleLoanDocument> loanItemDocuments = (List<OleLoanDocument>) businessObjectService.findMatching(OleLoanDocument.class, loanItemMap);
335        if (loanItemDocuments.size() == 0) {
336            itemAvailable = true;
337        }
338
339        return itemAvailable;
340    }
341
342
343    /**
344     * This is to check whether the item is eligible to loan
345     *
346     * @param oleDeliverRequestBo
347     * @return itemEligible
348     */
349    public boolean isItemEligible(OleDeliverRequestBo oleDeliverRequestBo) {
350        LOG.debug("Inside isItemEligible");
351        boolean itemEligible = true;
352        Map<String, String> statusMap = new HashMap<String, String>();
353        statusMap.put(OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT, OLEConstants.OleDeliverRequest.LOSTBILLREPLACEMENT);
354        statusMap.put(OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE, OLEConstants.OleDeliverRequest.MISSINGFINALOVERDUE);
355        statusMap.put(OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN, OLEConstants.OleDeliverRequest.WITHDRAWNCLIAMSRETURN);
356
357        if (statusMap.containsKey(oleDeliverRequestBo.getItemStatus())) {
358            itemEligible = false;
359        }
360        return itemEligible;
361    }
362
363    /**
364     * This is to check whether the patron record is alive or expired
365     *
366     * @param oleDeliverRequestBo
367     * @return expired
368     */
369    public boolean isPatronRecordExpired(OleDeliverRequestBo oleDeliverRequestBo) {
370        LOG.debug("Inside isPatronExpired");
371        boolean expired = true;
372        Map<String, String> patronMap = new HashMap<String, String>();
373        patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleDeliverRequestBo.getBorrowerId());
374        List<OlePatronDocument> olePatronDocuments = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
375        if (olePatronDocuments != null && olePatronDocuments.size() > 0) {
376            SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
377            Date expirationDate = olePatronDocuments.get(0).getExpirationDate();
378            if (expirationDate != null) {
379                if ((fmt.format(expirationDate)).compareTo(fmt.format(new Date(System.currentTimeMillis()))) > 0) {
380                    expired = false;
381                } else {
382                    expired = true;
383                }
384            }
385        } else {
386            expired = false;
387        }
388        return expired;
389    }
390
391
392    /**
393     * This is for retrieving the request raised by  the patron
394     *
395     * @param olePatronId
396     * @return deliverRequestBos
397     */
398    public List<OleDeliverRequestBo> getRequestedItems(String olePatronId) {
399        LOG.debug("Inside getRequestedItems");
400        Map<String, String> requestMap = new HashMap<String, String>();
401        requestMap.put(OLEConstants.OleDeliverRequest.BORROWER_ID, olePatronId);
402        List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
403        for (int i = 0; i < deliverRequestBos.size(); i++) {
404            processItem(deliverRequestBos.get(i));
405        }
406        return deliverRequestBos;
407
408    }
409
410
411    /**
412     * This is to check the  duplicate in the queue Position while re -ordering
413     *
414     * @param itemList
415     * @return exist
416     */
417    public String validateQueuePosition(List<OleDeliverRequestBo> itemList) {
418        LOG.debug("Inside validateQueuePosition");
419        String message = OLEConstants.OleDeliverRequest.REORDER_SUCCESS;
420        List<Integer> queuePositionList = new ArrayList<Integer>();
421        if (itemList.get(0).getBorrowerQueuePosition() < 1) {
422            return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
423        }
424        queuePositionList.add(itemList.get(0).getBorrowerQueuePosition());
425
426        for (int i = 1; i < itemList.size(); i++) {
427            for (int j = 0; j < queuePositionList.size(); j++) {
428                if (itemList.get(i).getBorrowerQueuePosition() != null) {
429                    if ((itemList.get(i).getBorrowerQueuePosition() >= 1) && (itemList.get(i).getBorrowerQueuePosition() == queuePositionList.get(j))) {
430                        return OLEConstants.OleDeliverRequest.QUEUE_DUPLICATE;
431                    } else if ((itemList.get(i).getBorrowerQueuePosition() <= 0)) {
432                        return OLEConstants.OleDeliverRequest.POSITIVE_QUEUE_POSITION;
433                    }
434                }
435            }
436            queuePositionList.add(itemList.get(i).getBorrowerQueuePosition());
437        }
438        return message;
439    }
440
441    //
442
443    /**
444     * This is to check whether any request raised for the item
445     *
446     * @param oleDeliverRequestBo
447     * @return exist
448     */
449    public boolean isRequestRaised(OleDeliverRequestBo oleDeliverRequestBo) {
450        LOG.debug("Inside isRequestRaised");
451        boolean exist = false;
452        Map<String, String> requestMap = new HashMap<String, String>();
453        requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
454        List<OleDeliverRequestBo> deliverRequestBos = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
455        if (deliverRequestBos.size() > 0) {
456            exist = true;
457        }
458        return exist;
459    }
460
461
462    /**
463     * This method is used to cancel the request document
464     *
465     * @param oleDeliverRequestBo
466     */
467    public void cancelDocument(OleDeliverRequestBo oleDeliverRequestBo) {
468        LOG.debug("Inside cancelDocument");
469        Map<String, String> itemMap = new HashMap<String, String>();
470        itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
471        Map<String, String> requestMap = new HashMap<String, String>();
472        requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, oleDeliverRequestBo.getRequestId());
473        businessObjectService.deleteMatching(OleDeliverRequestBo.class, requestMap);
474        List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
475        businessObjectService.delete(oleDeliverRequestDocumentsList);
476        int queuePosition = 1;
477        for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
478            oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
479            queuePosition = queuePosition + 1;
480        }
481        businessObjectService.save(oleDeliverRequestDocumentsList);
482    }
483
484
485    /**
486     * This method is to set the item values from docstore
487     *
488     * @param oleDeliverRequestBo
489     * @return oleDeliverRequestBo
490     */
491    public OleDeliverRequestBo processItem(OleDeliverRequestBo oleDeliverRequestBo) {
492        LOG.debug("Inside processItem");
493        OleItemSearch oleItemSearch = null;
494        if (oleDeliverRequestBo.getItemType() == null) {
495            Map<String, String> itemMap = new HashMap<String, String>();
496            itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
497            List<OleItemSearch> itemSearchList = docstoreHelperService.getOleItemSearchList(itemMap);
498            if (itemSearchList != null && itemSearchList.size() > 0) {
499                oleItemSearch = itemSearchList.get(0);
500                oleDeliverRequestBo.setTitle(itemSearchList.get(0).getTitle());
501                oleDeliverRequestBo.setAuthor(itemSearchList.get(0).getAuthor());
502                oleDeliverRequestBo.setCallNumber(itemSearchList.get(0).getCallNumber());
503                oleDeliverRequestBo.setItemType(itemSearchList.get(0).getItemType());
504            }
505            try {
506                if (oleItemSearch == null) {
507                    oleItemSearch = new OleItemSearch();
508                }
509                // Map docStoreDetails = loanProcessor.getItemDetails(oleDeliverRequestBo.getItemId());
510                String itemXml = loanProcessor.getItemXML(oleDeliverRequestBo.getItemUuid());
511                Item oleItem = loanProcessor.getItemPojo(itemXml);
512                oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
513                if (oleItem.getItemStatus() != null) {
514                    oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
515                }
516                oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
517                oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
518                if (oleItem.getItemStatus() != null) {
519                    oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
520                }
521                oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
522                if (oleDeliverRequestBo.getRequestTypeId().equals("8")) {
523                    oleDeliverRequestBo.setInTransitCheckInNote(oleItem.getCheckinNote());
524                }
525            } catch (Exception e) {
526                LOG.error(OLEConstants.INVAL_LOC, e);  //To change body of catch statement use File | Settings | File Templates.
527            }
528        }
529        oleDeliverRequestBo.setOleItemSearch(oleItemSearch);
530        oleDeliverRequestBo = processItemType(oleDeliverRequestBo);
531        return oleDeliverRequestBo;
532    }
533
534    /**
535     * This method is to set the item type name  based on the item type code
536     *
537     * @param oleDeliverRequestBo
538     * @return
539     */
540    public OleDeliverRequestBo processItemType(OleDeliverRequestBo oleDeliverRequestBo) {
541        LOG.debug("Inside process Item Type");
542        Map<String, String> itemMap = new HashMap<String, String>();
543        itemMap = new HashMap<String, String>();
544        itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, oleDeliverRequestBo.getItemType());
545        List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) businessObjectService.findMatching(OleInstanceItemType.class, itemMap);
546        if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
547            OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
548            oleDeliverRequestBo.setItemTypeName(oleInstanceItemType.getInstanceItemTypeName());
549        }
550
551        return oleDeliverRequestBo;
552    }
553
554    /**
555     * This method is to retrieve the shelving location from item
556     *
557     * @param oleLocation
558     * @return locationLevelName
559     */
560    private String getShelvingLocation(Location oleLocation) {
561
562        LOG.debug("Inside getShelvingLocation");
563        String locationLevelName = "";
564        if (oleLocation != null) {
565            LocationLevel locationLevel =
566                    oleLocation.getLocationLevel();
567            while (locationLevel.getLocationLevel() != null && !locationLevel.getLevel().equalsIgnoreCase(OLEConstants.OleDeliverRequest.SHELVING)) {
568                locationLevel = locationLevel.getLocationLevel();
569            }
570            locationLevelName = locationLevel.getName();
571        }
572        return locationLevelName;
573    }
574
575
576    /**
577     * This method is to check whether the selected  request can be raised for the item
578     *
579     * @param oleDeliverRequestBo
580     * @return canRaiseRequest
581     */
582    public boolean canRaiseRequest(OleDeliverRequestBo oleDeliverRequestBo) {
583        LOG.debug("Inside canRaiseRequest");
584        boolean canRaiseRequest = true;
585        if (oleDeliverRequestBo.getRequestTypeId().equals("1") || oleDeliverRequestBo.getRequestTypeId().equals("2") || oleDeliverRequestBo.getRequestTypeId().equals("3") || oleDeliverRequestBo.getRequestTypeId().equals("4")) {
586            if (isItemAvailable(oleDeliverRequestBo)) {
587                canRaiseRequest = false;
588            }
589        } else if (oleDeliverRequestBo.getRequestTypeId().equals("5") || oleDeliverRequestBo.getRequestTypeId().equals("6")) {
590            if (!isItemAvailable(oleDeliverRequestBo)) {
591                canRaiseRequest = false;
592            }
593        }
594        return canRaiseRequest;
595    }
596
597
598    /**
599     * racle
600     * This method is to update the request id in the loan document
601     *
602     * @param oleDeliverRequestBo
603     */
604    public OleDeliverRequestBo updateLoanDocument(OleDeliverRequestBo oleDeliverRequestBo) {
605        LOG.debug("Inside updateLoanDocument");
606        Map<String, String> loanMap = new HashMap<String, String>();
607        loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
608        List<OleLoanDocument> oleLoanDocumentList = (List<OleLoanDocument>) businessObjectService.findMatching(OleLoanDocument.class, loanMap);
609        if (oleLoanDocumentList != null && oleLoanDocumentList.size() > 0 && oleLoanDocumentList.get(0) != null && oleLoanDocumentList.get(0).getOleRequestId() == null) {
610            if (oleLoanDocumentList.get(0).getLoanId() != null) {
611                // oleLoanDocumentList.get(0).setOleRequestId(oleDeliverRequestBo.getRequestId());
612                oleDeliverRequestBo.setLoanTransactionRecordNumber(oleLoanDocumentList.get(0).getLoanId());
613            }
614            //  businessObjectService.save(oleLoanDocumentList.get(0));
615
616        }
617        return oleDeliverRequestBo;
618    }
619
620    /**
621     * @param requestId
622     * @param itemUUID
623     * @param operatorId
624     * @param loanTransactionNumber
625     */
626    public void deleteRequest(String requestId, String itemUUID, String operatorId, String loanTransactionNumber) {
627        LOG.debug("Inside deleteRequest");
628        Map<String, String> requestMap = new HashMap<String, String>();
629        requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
630        createRequestHistoryRecord(requestId, operatorId, loanTransactionNumber);
631        Map<String, String> itemMap = new HashMap<String, String>();
632        itemMap.put(OLEConstants.ITEM_UUID, itemUUID);
633        List<OleDeliverRequestBo> oleDeliverRequestDocumentsList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, itemMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
634        businessObjectService.delete(oleDeliverRequestDocumentsList);
635        int queuePosition = 1;
636        for (int i = 0; i < oleDeliverRequestDocumentsList.size(); i++) {
637            oleDeliverRequestDocumentsList.get(i).setBorrowerQueuePosition(queuePosition);
638            queuePosition = queuePosition + 1;
639        }
640        businessObjectService.save(oleDeliverRequestDocumentsList);
641
642    }
643
644    /**
645     * This for retrieving the item Details from docstore
646     *
647     * @param itemUUID
648     * @return oleItemSearch
649     */
650    public OleItemSearch getItemDetails(String itemUUID) {
651        LOG.debug("Inside getItemDetails");
652        OleItemSearch oleItemSearch = getItemDetailsForPatron(itemUUID);
653        try {
654            // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
655            String itemXml = loanProcessor.getItemXML(itemUUID);
656            Item oleItem = loanProcessor.getItemPojo(itemXml);
657            if (oleItem != null && oleItem.getItemType() != null) {
658                oleItemSearch.setItemType(processItemType(oleItem.getItemType().getCodeValue()));
659            }
660            oleItemSearch.setCopyNumber(oleItem.getCopyNumber());
661            if (oleItem.getItemStatus() != null) {
662                oleItemSearch.setItemStatus(oleItem.getItemStatus().getCodeValue());
663            }
664            oleItemSearch.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
665            oleItemSearch.setVolumeNumber(oleItem.getVolumeNumber());
666        } catch (Exception e) {
667            LOG.error("Not able to retrieve information from the docstore for the Item Barcode : " + itemUUID, e);  //To change body of catch statement use File | Settings | File Templates.
668        }
669        return oleItemSearch;
670    }
671
672    /**
673     * This method is for retrieving the item details for displaying in the patron screen
674     *
675     * @param itemUUID
676     * @return OleItemSearch
677     */
678    public OleItemSearch getItemDetailsForPatron(String itemUUID) {
679        LOG.debug("Inside getItemDetailsForPatron");
680        OleItemSearch oleItemSearch;
681        try {
682
683            Map<String, String> itemMap = new HashMap<String, String>();
684            itemMap.put(OLEConstants.OleDeliverRequest.ITEM_UUID, itemUUID);
685            List<OleItemSearch> itemSearchList = docstoreHelperService.getOleItemSearchList(itemMap);
686            if (itemSearchList.size() > 0) {
687                return oleItemSearch = itemSearchList.get(0);
688            }
689        } catch (NullPointerException e) {
690            LOG.error("No item details available for the Item Barcode : " + itemUUID, e);
691        }
692
693        return new OleItemSearch();
694
695    }
696
697    /**
698     * This method is to re-order the queuePosition based on the priority while creating the request
699     *
700     * @param oleDeliverRequestBo
701     * @return OleDeliverRequestBo
702     */
703    public OleDeliverRequestBo reOrderQueuePosition(OleDeliverRequestBo oleDeliverRequestBo) {
704        LOG.debug("Inside reOrderQueuePosition");
705        List<OleDeliverRequestBo> existingRequest = new ArrayList<OleDeliverRequestBo>();
706        String queue = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.REQUEST_QUEUE);
707        List<String> orderQueue = new ArrayList<String>();
708        String[] queueArray = queue.split(";");
709        for (int i = 0; i < queueArray.length; i++) {
710            orderQueue.add(queueArray[i]);
711        }
712        List<OleDeliverRequestBo> finalList = new ArrayList<OleDeliverRequestBo>();
713        Map<String, String> recallRequestMap = new HashMap<String, String>();
714        recallRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
715        recallRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
716        Map<String, String> recallHoldRequestMap = new HashMap<String, String>();
717        recallHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
718        recallHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
719        Map<String, String> holdRequestMap = new HashMap<String, String>();
720        holdRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
721        holdRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
722        Map<String, String> holdHoldRequestMap = new HashMap<String, String>();
723        holdHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
724        holdHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
725        Map<String, String> pageRequestMap = new HashMap<String, String>();
726        pageRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
727        pageRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
728        Map<String, String> pageHoldRequestMap = new HashMap<String, String>();
729        pageHoldRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
730        pageHoldRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
731        Map<String, String> copyRequestMap = new HashMap<String, String>();
732        copyRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
733        copyRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "7");
734        Map<String, String> inTransitRequestMap = new HashMap<String, String>();
735        inTransitRequestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
736        inTransitRequestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "8");
737        List<OleDeliverRequestBo> recallList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, recallRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
738        List<OleDeliverRequestBo> recallHoldList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, recallHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
739        List<OleDeliverRequestBo> holdList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, holdRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
740        List<OleDeliverRequestBo> holdHoldList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, holdHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
741        List<OleDeliverRequestBo> pageList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, pageRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
742        List<OleDeliverRequestBo> pageHoldList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, pageHoldRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
743        List<OleDeliverRequestBo> copyList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, copyRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
744        List<OleDeliverRequestBo> inTransitList = (List<OleDeliverRequestBo>) businessObjectService.findMatchingOrderBy(OleDeliverRequestBo.class, inTransitRequestMap, OLEConstants.OleDeliverRequest.QUEUE_POSITION, true);
745        if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_DELIVERY)) {
746            recallList.add(oleDeliverRequestBo);
747        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_DELIVERY)) {
748            holdList.add(oleDeliverRequestBo);
749        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_DELIVERY)) {
750            pageList.add(oleDeliverRequestBo);
751        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.COPY)) {
752            copyList.add(oleDeliverRequestBo);
753        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.INTRANSIT)) {
754            inTransitList.add(oleDeliverRequestBo);
755        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.RECALL_HOLD)) {
756            recallHoldList.add(oleDeliverRequestBo);
757        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.HOLD_HOLD)) {
758            holdHoldList.add(oleDeliverRequestBo);
759        } else if (oleDeliverRequestBo.getOleDeliverRequestType().getRequestTypeCode().contains(OLEConstants.OleDeliverRequest.PAGE_HOLD)) {
760            pageHoldList.add(oleDeliverRequestBo);
761        }
762        OleDeliverRequestBo oleDeliverRequestBo1;
763        for (int i = 0; i < orderQueue.size(); i++) {
764            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallList.size() > 0) {
765                for (int x = 0; x < recallList.size(); x++) {
766                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallList.get(x));
767                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
768                    this.queuePosition = this.queuePosition + 1;
769                    finalList.add(oleDeliverRequestBo1);
770
771                }
772            }
773            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdList.size() > 0) {
774                for (int x = 0; x < holdList.size(); x++) {
775                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdList.get(x));
776                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
777                    this.queuePosition = this.queuePosition + 1;
778                    finalList.add(oleDeliverRequestBo1);
779
780                }
781            }
782            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageList.size() > 0) {
783                for (int x = 0; x < pageList.size(); x++) {
784                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageList.get(x));
785                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
786                    this.queuePosition = this.queuePosition + 1;
787                    finalList.add(oleDeliverRequestBo1);
788                }
789            }
790            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.RECALL) && recallHoldList.size() > 0) {
791                for (int x = 0; x < recallHoldList.size(); x++) {
792                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(recallHoldList.get(x));
793                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
794                    this.queuePosition = this.queuePosition + 1;
795                    finalList.add(oleDeliverRequestBo1);
796
797                }
798            }
799            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.HOLD) && holdHoldList.size() > 0) {
800                for (int x = 0; x < holdHoldList.size(); x++) {
801                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(holdHoldList.get(x));
802                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
803                    this.queuePosition = this.queuePosition + 1;
804                    finalList.add(oleDeliverRequestBo1);
805
806                }
807            }
808            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.PAGE) && pageHoldList.size() > 0) {
809                for (int x = 0; x < pageHoldList.size(); x++) {
810                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(pageHoldList.get(x));
811                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
812                    this.queuePosition = this.queuePosition + 1;
813                    finalList.add(oleDeliverRequestBo1);
814                }
815            }
816            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.COPY) && copyList.size() > 0) {
817                for (int x = 0; x < copyList.size(); x++) {
818                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(copyList.get(x));
819                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
820                    this.queuePosition = this.queuePosition + 1;
821                    finalList.add(oleDeliverRequestBo1);
822
823                }
824            }
825            if (orderQueue.get(i).equals(OLEConstants.OleDeliverRequest.INTRANSIT) && inTransitList.size() > 0) {
826                for (int x = 0; x < inTransitList.size(); x++) {
827                    oleDeliverRequestBo1 = (OleDeliverRequestBo) ObjectUtils.deepCopy(inTransitList.get(x));
828                    oleDeliverRequestBo1.setBorrowerQueuePosition(this.queuePosition + 1);
829                    this.queuePosition = this.queuePosition + 1;
830                    finalList.add(oleDeliverRequestBo1);
831
832                }
833            }
834        }
835        for (int i = 0; i < finalList.size(); i++) {
836            if (finalList.get(i).getRequestId() == null) {
837                oleDeliverRequestBo.setBorrowerQueuePosition(finalList.get(i).getBorrowerQueuePosition());
838                finalList.remove(finalList.get(i));
839            }
840        }
841        businessObjectService.save(finalList);
842        return oleDeliverRequestBo;
843    }
844
845    /**
846     * Thsi method is to check whether the item is available in doc store or not
847     *
848     * @param oleDeliverRequestBo
849     * @return boolean
850     */
851    public boolean isItemAvailbleInDocstore(OleDeliverRequestBo oleDeliverRequestBo) {
852        LOG.debug("Inside isItemAvailbleInDocstore");
853        boolean available = false;
854        Map<String, String> itemMap = new HashMap<String, String>();
855        try {
856            Map<String, String> itemUUIDMap = QueryServiceImpl.getInstance().getItemDetails(oleDeliverRequestBo.getItemId(), null);
857            String itemUUID = itemUUIDMap.get(OLEConstants.ITEM_UUID);
858            oleDeliverRequestBo.setItemUuid(itemUUID);
859        } catch (Exception e) {
860            LOG.error(e, e);
861            //To change body of catch statement use File | Settings | File Templates.
862        }
863        itemMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
864        List<OleItemSearch> itemSearchList = docstoreHelperService.getOleItemSearchList(itemMap);
865        if (itemSearchList != null && itemSearchList.size() > 0) {
866            oleDeliverRequestBo.setTitle(itemSearchList.get(0).getTitle());
867            oleDeliverRequestBo.setAuthor(itemSearchList.get(0).getAuthor());
868            oleDeliverRequestBo.setCallNumber(itemSearchList.get(0).getCallNumber());
869            oleDeliverRequestBo.setItemType(itemSearchList.get(0).getItemType());
870        }
871        try {
872            // Map docStoreDetails = loanProcessor.getItemDetailsByUUID(oleDeliverRequestBo.getItemId());
873            String itemXml = loanProcessor.getItemXML(oleDeliverRequestBo.getItemUuid());
874            Item oleItem = loanProcessor.getItemPojo(itemXml);
875
876            oleDeliverRequestBo.setCopyNumber(oleItem.getCopyNumber());
877            if (oleItem.getItemStatus() != null) {
878                oleDeliverRequestBo.setItemStatus(oleItem.getItemStatus().getCodeValue());
879            }
880            oleDeliverRequestBo.setShelvingLocation(getShelvingLocation(oleItem.getLocation()));
881            available = true;
882        } catch (Exception e) {
883            LOG.error(OLEConstants.INVAL_LOC, e);  //To change body of catch statement use File | Settings | File Templates.
884        }
885        return available;
886    }
887
888    public OleDeliverRequestBo populateItemDetailsToRequest(OleDeliverRequestBo oleDeliverRequestBo, OleItemSearch oleItemSearch) {
889        LOG.debug("Inside populateItemDetailsToRequest");
890        if (oleDeliverRequestBo != null && oleItemSearch != null) {
891            oleDeliverRequestBo.setAuthor(oleItemSearch.getAuthor());
892            oleDeliverRequestBo.setTitle(oleItemSearch.getTitle());
893            oleDeliverRequestBo.setCallNumber(oleItemSearch.getCallNumber());
894            oleDeliverRequestBo.setCopyNumber(oleItemSearch.getCopyNumber());
895            oleDeliverRequestBo.setItemType(oleItemSearch.getItemType());
896            oleDeliverRequestBo.setItemStatus(oleItemSearch.getItemStatus());
897            oleItemSearch.setShelvingLocation(oleDeliverRequestBo.getShelvingLocation());
898        }
899        return oleDeliverRequestBo;
900    }
901
902
903    public OleDeliverRequestBo generateRecallNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
904        Map<String, String> loanMap = new HashMap<String, String>();
905        loanMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
906        List<OleLoanDocument> loanDocuments = (List<OleLoanDocument>) businessObjectService.findMatching(OleLoanDocument.class, loanMap);
907        OleLoanDocument oleLoanDocument = loanDocuments.get(0);
908        Map<String, String> patronMap = new HashMap<String, String>();
909        patronMap.put(OLEConstants.OleDeliverRequest.PATRON_ID, oleLoanDocument.getPatronId());
910        List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
911        OleNoticeBo oleNoticeBo = new OleNoticeBo();
912        Item item;
913        if (patronDocumentList.size() > 0) {
914            OlePatronDocument olePatronDocument = patronDocumentList.get(0);
915            EntityTypeContactInfoBo entityTypeContactInfoBo = olePatronDocument.getEntity().getEntityTypeContactInfos().get(0);
916            oleNoticeBo.setPatronName(olePatronDocument.getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
917            oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
918            oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
919            oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
920        }
921        oleNoticeBo.setAuthor(oleDeliverRequestBo.getAuthor() != null ? oleDeliverRequestBo.getAuthor() : "");
922        oleNoticeBo.setCirculationDeskAddress("");
923        oleNoticeBo.setCirculationDeskName("");
924        oleNoticeBo.setCirculationDeskEmailAddress("");
925        oleNoticeBo.setCirculationDeskPhoneNumber("");
926        oleNoticeBo.setItemCallNumber(oleDeliverRequestBo.getCallNumber() != null ? oleDeliverRequestBo.getCallNumber() : "");
927        oleNoticeBo.setItemShelvingLocation(oleDeliverRequestBo.getShelvingLocation() != null ? oleDeliverRequestBo.getShelvingLocation() : "");
928        oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
929        oleNoticeBo.setTitle(oleDeliverRequestBo.getTitle() != null ? oleDeliverRequestBo.getTitle() : "");
930        oleNoticeBo.setOleItem(getItem(oleDeliverRequestBo.getItemUuid()));
931        oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
932        oleNoticeBo.setVolumeNumber(oleNoticeBo.getOleItem().getVolumeNumber() != null ? oleNoticeBo.getOleItem().getVolumeNumber() : "");
933        oleNoticeBo.setOriginalDueDate(oleLoanDocument.getLoanDueDate());
934        if (oleDeliverRequestBo.getRecallDueDate() != null) {
935            oleNoticeBo.setNewDueDate(oleDeliverRequestBo.getRecallDueDate());
936        } else {
937            oleNoticeBo.setNewDueDate(oleLoanDocument.getLoanDueDate());
938        }
939        oleNoticeBo.setNoticeName(OLEConstants.NOTICE_RECALL);
940        String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_BODY);
941        oleNoticeBo.setNoticeSpecificContent(noticeContent);
942        //  oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo,oleDeliverRequestBo.getOlePatron());
943        OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
944        List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
945        String noticeType = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RECALL_NOTICE_TYPE);
946        if (noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
947            String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
948            if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
949                fromAddress = OLEConstants.KUALI_MAIL;
950            }
951            if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
952                oleNoticeBos.add(oleNoticeBo);
953                List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
954                OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
955                oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
956                LOG.info("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
957/*
958                Mailer  mailer = CoreApiServiceLocator.getMailer();
959                mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
960          */
961            }
962        } else if (noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
963            oleNoticeBos.add(oleNoticeBo);
964            Map map = oleDeliverBatchService.getSMSForPatron(oleNoticeBos);
965            HashMap sms = (HashMap) map.get(OLEConstants.OleDeliverRequest.RECALL);
966            Iterator it = sms.entrySet().iterator();
967            while (it.hasNext()) {
968                Map.Entry pairs = (Map.Entry) it.next();
969                String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
970                OleSms oleSms = new OleSms();
971                oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
972            }
973
974        } else if (noticeType.equalsIgnoreCase(OLEConstants.MAIL)) {
975            oleNoticeBos.add(oleNoticeBo);
976            oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
977            LOG.info("Recall Notice Pdf generated for item Id" + oleNoticeBo.getItemId());
978        }
979        oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(oleDeliverRequestBo);
980        oleDeliverRequestBo.setRecallNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
981        return oleDeliverRequestBo;
982    }
983
984
985    public void generateOnHoldNotice() throws Exception {
986
987        List<OleDeliverRequestBo> finalDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
988        Map<String, String> onHoldNoticeMap = new HashMap<String, String>();
989        onHoldNoticeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
990        List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, onHoldNoticeMap);
991        Map<String, String> onHoldHoldNoticeMap = new HashMap<String, String>();
992        onHoldHoldNoticeMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
993        List<OleDeliverRequestBo> oleDeliverRequestBoList1 = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, onHoldHoldNoticeMap);
994        oleDeliverRequestBoList.addAll(oleDeliverRequestBoList1);
995        OleDeliverRequestBo oleDeliverRequestBo;
996        List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
997        EntityTypeContactInfoBo entityTypeContactInfoBo;
998        OleNoticeBo oleNoticeBo;
999        Item item;
1000        for (int i = 0; i < oleDeliverRequestBoList.size(); i++) {
1001            if (docstoreHelperService.isItemAvailableInDocStore(oleDeliverRequestBoList.get(i))) {
1002                item = oleDeliverRequestBoList.get(i).getOleItem();
1003                if (item != null && item.getItemStatus() != null && item.getItemStatus().getCodeValue() != null && item.getItemStatus().getCodeValue().equals(OLEConstants.ITEM_STATUS_ON_HOLD) && oleDeliverRequestBoList.get(i).getOnHoldNoticeSentDate() == null) {
1004                    entityTypeContactInfoBo = oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1005                    oleNoticeBo = new OleNoticeBo();
1006                    oleNoticeBo.setAuthor(oleDeliverRequestBoList.get(i).getAuthor());
1007                    oleNoticeBo.setCirculationDeskAddress("");
1008                    oleNoticeBo.setCirculationDeskName("");
1009                    oleNoticeBo.setCirculationDeskEmailAddress("");
1010                    oleNoticeBo.setCirculationDeskPhoneNumber("");
1011                    oleNoticeBo.setPatronName(oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getNames().get(0).getLastName());
1012                    oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1013                    oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1014                    oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1015                    oleNoticeBo.setItemCallNumber(oleDeliverRequestBoList.get(i).getCallNumber() != null ? oleDeliverRequestBoList.get(i).getCallNumber() : "");
1016                    oleNoticeBo.setItemShelvingLocation(oleDeliverRequestBoList.get(i).getShelvingLocation() != null ? oleDeliverRequestBoList.get(i).getShelvingLocation() : "");
1017                    oleNoticeBo.setItemId(oleDeliverRequestBoList.get(i).getItemId() != null ? oleDeliverRequestBoList.get(i).getItemId() : "");
1018                    oleNoticeBo.setTitle(oleDeliverRequestBoList.get(i).getTitle() != null ? oleDeliverRequestBoList.get(i).getTitle() : "");
1019                    oleNoticeBo.setOleItem(item);
1020                    oleNoticeBo.setOlePatron(oleDeliverRequestBoList.get(i).getOlePatron());
1021                    oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1022                    oleNoticeBo.setNewDueDate(new Date());
1023                    oleNoticeBo.setOriginalDueDate(new Date());
1024                    oleNoticeBo.setNoticeName(OLEConstants.NOTICE_ONHOLD);
1025                    oleNoticeBo.setCirculationDeskName(oleDeliverRequestBoList.get(i).getOlePickUpLocation().getCirculationDeskPublicName());
1026                    String circulationDeskId=oleDeliverRequestBoList.get(i).getPickUpLocationId();
1027                    int noDays=0;
1028                    Map<String,String> mapCirculationDesk=new HashMap<String,String>();
1029                    mapCirculationDesk.put("circulationDeskId",circulationDeskId);
1030                    List<OleCirculationDesk> oleCirculationDesks=(List<OleCirculationDesk>)KRADServiceLocator.getBusinessObjectService().findMatching(OleCirculationDesk.class,mapCirculationDesk);
1031                    if(oleCirculationDesks.size()>0){
1032                        OleCirculationDesk oleCirculationDesk=oleCirculationDesks.get(0);
1033                        noDays=Integer.parseInt(oleCirculationDesk.getOnHoldDays());
1034                    }
1035                    Calendar calendar=Calendar.getInstance();
1036                    calendar.add(Calendar.DATE,noDays);
1037                    Date date=calendar.getTime();
1038                    oleNoticeBo.setExpiredOnHoldDate(date);
1039                    String maxNumOfDays = oleDeliverRequestBoList.get(i).getOlePickUpLocation().getOnHoldDays() != null ? oleDeliverRequestBoList.get(i).getOlePickUpLocation().getOnHoldDays() : loanProcessor.getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1040                    Integer maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1041                    oleNoticeBo.setOnHoldDueDate(dateAdd(oleDeliverRequestBoList.get(i).getCreateDate(), maxNumberOfDaysOnHold));
1042                    String noticeContent = getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_BODY);
1043                    oleNoticeBo.setNoticeSpecificContent(noticeContent);
1044                    noticesList.add(oleNoticeBo);
1045                    OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1046                    String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1047                    HashMap<String, Object> termValues = new HashMap<String, Object>();
1048                    OleCirculationDesk oleCirculationDesk = oleDeliverRequestBoList.get(i).getOlePickUpLocation();
1049                    OlePatronDocument olePatronDocument = oleDeliverRequestBoList.get(i).getOlePatron();
1050                    String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1051                    String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1052                    termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1053                    termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1054                    termValues.put(OLEConstants.NOTICE, OLEConstants.NOTICE_ONHOLD);
1055                    LOG.info("termValues.toString()" + termValues.toString());
1056                    EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1057                    String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1058                    LOG.info("**************" + noticeType);
1059                    noticeType = noticeType != null ? noticeType : getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.ONHOLD_NOTICE_TYPE);
1060                    if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.MAIL)) {
1061                        LOG.info("noticesList.size()" + noticesList.size());
1062                        oleDeliverBatchService.getPdfNoticeForPatron(noticesList);
1063                        LOG.info("OnHold Notice Pdf generated for item Id" + oleNoticeBo.getItemId());
1064                    }
1065                    if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1066                        String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1067                        if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1068                            fromAddress = OLEConstants.KUALI_MAIL;
1069                        }
1070                        if (oleNoticeBo.getPatronEmailAddress() != null && !oleNoticeBo.getPatronEmailAddress().isEmpty()) {
1071                            List list = oleDeliverBatchService.getNoticeForPatron(noticesList);
1072                            OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1073                            oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1074                            LOG.info("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1075                       /* Mailer mailer = CoreApiServiceLocator.getMailer();
1076                        mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1077                   */
1078                        }
1079                    } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1080                        Map map = oleDeliverBatchService.getSMSForPatron(noticesList);
1081                        HashMap sms = (HashMap) map.get(OLEConstants.NOTICE_ONHOLD);
1082                        Iterator it = sms.entrySet().iterator();
1083                        while (it.hasNext()) {
1084                            Map.Entry pairs = (Map.Entry) it.next();
1085                            String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1086                            OleSms oleSms = new OleSms();
1087                            oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1088                        }
1089                    }
1090                    // To do send Notice
1091                    oleDeliverRequestBoList.get(i).setOleItem(null);
1092                    oleDeliverRequestBo = (OleDeliverRequestBo) ObjectUtils.deepCopy(oleDeliverRequestBoList.get(i));
1093                    oleDeliverRequestBo.setOnHoldNoticeSentDate(new java.sql.Date(System.currentTimeMillis()));
1094                    finalDeliverRequestBoList.add(oleDeliverRequestBo);
1095                }
1096            }
1097            businessObjectService.save(finalDeliverRequestBoList);
1098        }
1099    }
1100
1101    public void generateRequestExpirationNotice() throws Exception {
1102        List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1103        OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1104        oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findAll(OleDeliverRequestBo.class);
1105        SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1106        EntityTypeContactInfoBo entityTypeContactInfoBo;
1107        List<OleNoticeBo> noticesList = new ArrayList<OleNoticeBo>();
1108        Item item;
1109        String noticeType = null;
1110        OleNoticeBo oleNoticeBo = new OleNoticeBo();
1111        if (oleDeliverRequestBoList.size() > 0) {
1112            for (int i = 0; i < oleDeliverRequestBoList.size(); i++) {
1113                if (docstoreHelperService.isItemAvailableInDocStore(oleDeliverRequestBoList.get(i))) {
1114                    //  processItem(oleDeliverRequestBoList.get(i));
1115                    item = oleDeliverRequestBoList.get(i).getOleItem();
1116                    LOG.info("Expiration Date :" + oleDeliverRequestBoList.get(i).getRequestExpiryDate());
1117                    if (oleDeliverRequestBoList.get(i).getOlePatron().isCourtesyNotice() && (fmt.format(oleDeliverRequestBoList.get(i).getRequestExpiryDate())).compareTo(fmt.format(new Date(System.currentTimeMillis()))) <= 0) {
1118                        LOG.info("Inside Expiration Date :" + oleDeliverRequestBoList.get(i).getRequestExpiryDate());
1119                        entityTypeContactInfoBo = oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1120                        oleNoticeBo = new OleNoticeBo();
1121                        oleNoticeBo.setAuthor(oleDeliverRequestBoList.get(i).getAuthor());
1122                        oleNoticeBo.setCirculationDeskAddress("");
1123                        oleNoticeBo.setCirculationDeskName("");
1124                        oleNoticeBo.setCirculationDeskEmailAddress("");
1125                        oleNoticeBo.setCirculationDeskPhoneNumber("");
1126                        oleNoticeBo.setPatronName(oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBoList.get(i).getOlePatron().getEntity().getNames().get(0).getLastName());
1127                        oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1128                        oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1129                        oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1130                        oleNoticeBo.setItemCallNumber(oleDeliverRequestBoList.get(i).getCallNumber() != null ? oleDeliverRequestBoList.get(i).getCallNumber() : "");
1131                        oleNoticeBo.setItemShelvingLocation(oleDeliverRequestBoList.get(i).getShelvingLocation() != null ? oleDeliverRequestBoList.get(i).getShelvingLocation() : "");
1132                        oleNoticeBo.setItemId(oleDeliverRequestBoList.get(i).getItemId() != null ? oleDeliverRequestBoList.get(i).getItemId() : "");
1133                        oleNoticeBo.setTitle(oleDeliverRequestBoList.get(i).getTitle() != null ? oleDeliverRequestBoList.get(i).getTitle() : "");
1134                        oleNoticeBo.setOleItem(item);
1135                        oleNoticeBo.setOlePatron(oleDeliverRequestBoList.get(i).getOlePatron());
1136                        oleNoticeBo.setVolumeNumber(item.getVolumeNumber() != null ? item.getVolumeNumber() : "");
1137                        oleNoticeBo.setNewDueDate(new Date());
1138                        oleNoticeBo.setOriginalDueDate(new Date());
1139                        oleNoticeBo.setNoticeName(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1140                        String noticeContent = getLoanProcessor().getParameter(OLEParameterConstants.EXPIRED_BODY);
1141                        oleNoticeBo.setNoticeSpecificContent(noticeContent);
1142                        noticesList.add(oleNoticeBo);
1143                        String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1144                        HashMap<String, Object> termValues = new HashMap<String, Object>();
1145                        OleCirculationDesk oleCirculationDesk = oleDeliverRequestBoList.get(i).getOlePickUpLocation();
1146                        OlePatronDocument olePatronDocument = oleDeliverRequestBoList.get(i).getOlePatron();
1147                        String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1148                        String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1149                        termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1150                        termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1151                        termValues.put(OLEConstants.NOTICE, OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1152                        LOG.info("termValues.toString()" + termValues.toString());
1153                        EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1154                        noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1155                        LOG.info("**************" + noticeType);
1156                        noticeType = noticeType != null ? noticeType : getLoanProcessor().getParameter(OLEConstants.OleDeliverRequest.RQST_EXPR_NOTICE_TYPE);
1157                        if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1158                            // noticesList.add(oleNoticeBo);
1159                            Map map = oleDeliverBatchService.getSMSForPatron(noticesList);
1160                            HashMap sms = (HashMap) map.get(OLEConstants.OleDeliverRequest.EXPIRED_REQUEST);
1161                            Iterator it = sms.entrySet().iterator();
1162                            while (it.hasNext()) {
1163                                Map.Entry pairs = (Map.Entry) it.next();
1164
1165                                String patronPhoneNumber = oleNoticeBo.getPatronPhoneNumber();
1166                                OleSms oleSms = new OleSms();
1167                                oleSms.sendSms("", patronPhoneNumber, (String) pairs.getValue());
1168                            }
1169                        }
1170                    }
1171                }
1172                if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.MAIL)) {
1173                    oleDeliverBatchService.getPdfNoticeForPatron(noticesList);
1174                    LOG.info("Request Expiration Notice Pdf generated for item Id");
1175                } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1176                    String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1177                    if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1178                        fromAddress = OLEConstants.KUALI_MAIL;
1179                    }
1180                    //  noticesList.add(oleNoticeBo);
1181                    List list = (List) oleDeliverBatchService.getNoticeForPatron(noticesList);
1182                    OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1183                    oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1184                    LOG.info("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1185
1186                }
1187            }
1188        }
1189    }
1190
1191    private java.sql.Date dateAdd(java.sql.Date in, int daysToAdd) {
1192        if (in == null) {
1193            return null;
1194        }
1195        GregorianCalendar cal = new GregorianCalendar();
1196        cal.setTime(in);
1197        cal.add(Calendar.DAY_OF_MONTH, daysToAdd);
1198        return new java.sql.Date(cal.getTime().getTime());
1199    }
1200
1201    public void deletingExpiredRequests() {
1202        LOG.info("Inside deletingExpiredRequests");
1203        List<OleDeliverRequestBo> oleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1204        List<OleDeliverRequestBo> newOleDeliverRequestBoList = new ArrayList<OleDeliverRequestBo>();
1205        try {
1206            oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findAll(OleDeliverRequestBo.class);
1207            businessObjectService.delete(oleDeliverRequestBoList);
1208            SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OleDeliverRequest.DATE_FORMAT);
1209            for (int i = 0; i < oleDeliverRequestBoList.size(); i++) {
1210                if ((fmt.format(oleDeliverRequestBoList.get(i).getRequestExpiryDate())).compareTo(fmt.format(new Date(System.currentTimeMillis()))) > 0) {
1211                    newOleDeliverRequestBoList.add(oleDeliverRequestBoList.get(i));
1212                }
1213            }
1214            businessObjectService.save(newOleDeliverRequestBoList);
1215        } catch (Exception e) {
1216            businessObjectService.save(oleDeliverRequestBoList);
1217        }
1218    }
1219
1220    private Item getItem(String itemUUID) {
1221        LOG.debug("Inside getItem");
1222        try {
1223            // Map  docStoreDetails= loanProcessor.getItemDetails(itemBarCode);
1224            String itemXml = loanProcessor.getItemXML(itemUUID);
1225            Item oleItem = loanProcessor.getItemPojo(itemXml);
1226            return oleItem;
1227        } catch (Exception e) {
1228            LOG.error("Item not available in doc store", e);
1229        }
1230        return null;
1231    }
1232
1233
1234    private OleNoticeBo setPatronDetailsForNotice(OleNoticeBo oleNoticeBo, OlePatronDocument olePatronDocument) {
1235        LOG.debug("Inside setPatronDetailsForNotice");
1236        if (oleNoticeBo.getAuthor() != null && olePatronDocument.getOlePatronId() != null) {
1237            oleNoticeBo.setPatronName(olePatronDocument.getName().getFirstName());
1238            if (olePatronDocument.getAddresses().size() > 0) {
1239                oleNoticeBo.setPatronAddress(olePatronDocument.getAddresses().get(0).getLine1() + "/n" + olePatronDocument.getAddresses().get(0).getLine2() + "/n" + olePatronDocument.getAddresses().get(0).getCity());
1240            }
1241            oleNoticeBo.setPatronEmailAddress(olePatronDocument.getEmailAddress());
1242            oleNoticeBo.setPatronPhoneNumber(olePatronDocument.getPhoneNumber());
1243        }
1244        return oleNoticeBo;
1245    }
1246
1247
1248    private void createRequestHistoryRecord(String requestId, String OperatorId, String loanTransactionNumber) {
1249        LOG.debug("Inside createRequestHistoryRecord");
1250        Map<String, String> requestMap = new HashMap<String, String>();
1251        requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_ID, requestId);
1252        List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1253        if (oleDeliverRequestBoList.size() > 0) {
1254            OleDeliverRequestBo oleDeliverRequestBo = oleDeliverRequestBoList.get(0);
1255            OleDeliverRequestHistoryRecord oleDeliverRequestHistoryRecord = new OleDeliverRequestHistoryRecord();
1256            oleDeliverRequestHistoryRecord.setRequestId(oleDeliverRequestBo.getRequestId());
1257            oleDeliverRequestHistoryRecord.setItemId(oleDeliverRequestBo.getItemId());
1258            oleDeliverRequestHistoryRecord.setArchiveDate(new java.sql.Date(System.currentTimeMillis()));
1259            oleDeliverRequestHistoryRecord.setPickUpLocationCode(oleDeliverRequestBo.getPickUpLocationCode());
1260            oleDeliverRequestHistoryRecord.setOperatorId(OperatorId);
1261            oleDeliverRequestHistoryRecord.setDeliverRequestTypeCode(oleDeliverRequestBo.getRequestTypeCode());
1262            oleDeliverRequestHistoryRecord.setPoLineItemNumber("");
1263            oleDeliverRequestHistoryRecord.setLoanTransactionId(loanTransactionNumber);
1264            oleDeliverRequestHistoryRecord.setMachineId("");
1265            businessObjectService.save(oleDeliverRequestHistoryRecord);
1266        }
1267        businessObjectService.delete(oleDeliverRequestBoList);
1268    }
1269
1270    public OleDeliverRequestBo getOleDeliverRequestBo(String itemUUID) {
1271
1272        LOG.debug("Inside getOleDeliverRequestBo method");
1273        Map<String, String> requestMap = new HashMap<String, String>();
1274        requestMap.put(OLEConstants.ITEM_UUID, itemUUID);
1275        List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>) businessObjectService.findMatching(OleDeliverRequestBo.class, requestMap);
1276        if (oleDeliverRequestBoList.size() > 0)
1277            return oleDeliverRequestBoList.get(0);
1278        return null;
1279    }
1280
1281    private String getPatronPreferredAddress(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1282        LOG.debug("Inside the getPatronPreferredAddress method");
1283        String address = "";
1284        if (entityTypeContactInfoBo.getAddresses() != null) {
1285            for (int i = 0; i < entityTypeContactInfoBo.getAddresses().size(); i++) {
1286                if (entityTypeContactInfoBo.getAddresses().get(i).isDefaultValue()) {
1287                    if (entityTypeContactInfoBo.getAddresses().get(i).getLine1() != null)
1288                        if (!entityTypeContactInfoBo.getAddresses().get(i).getLine1().isEmpty())
1289                            address += entityTypeContactInfoBo.getAddresses().get(i).getLine1() + ",";
1290
1291                    if (entityTypeContactInfoBo.getAddresses().get(i).getLine2() != null)
1292                        if (!entityTypeContactInfoBo.getAddresses().get(i).getLine2().isEmpty())
1293                            address += entityTypeContactInfoBo.getAddresses().get(i).getLine2() + ",";
1294
1295                    if (entityTypeContactInfoBo.getAddresses().get(i).getLine3() != null)
1296                        if (!entityTypeContactInfoBo.getAddresses().get(i).getLine3().isEmpty())
1297                            address += entityTypeContactInfoBo.getAddresses().get(i).getLine3() + ",";
1298
1299                    if (entityTypeContactInfoBo.getAddresses().get(i).getCity() != null)
1300                        if (!entityTypeContactInfoBo.getAddresses().get(i).getCity().isEmpty())
1301                            address += entityTypeContactInfoBo.getAddresses().get(i).getCity() + ",";
1302
1303                    if (entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode() != null)
1304                        if (!entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode().isEmpty())
1305                            address += entityTypeContactInfoBo.getAddresses().get(i).getStateProvinceCode() + ",";
1306
1307                    if (entityTypeContactInfoBo.getAddresses().get(i).getCountryCode() != null)
1308                        if (!entityTypeContactInfoBo.getAddresses().get(i).getCountryCode().isEmpty())
1309                            address += entityTypeContactInfoBo.getAddresses().get(i).getCountryCode() + ",";
1310
1311                    if (entityTypeContactInfoBo.getAddresses().get(i).getPostalCode() != null)
1312                        if (!entityTypeContactInfoBo.getAddresses().get(i).getPostalCode().isEmpty())
1313                            address += entityTypeContactInfoBo.getAddresses().get(i).getPostalCode();
1314                }
1315            }
1316        }
1317
1318        return address;
1319    }
1320
1321    private String getPatronHomePhoneNumber(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1322        LOG.debug("Inside the getPatronHomePhoneNumber method");
1323        String phoneNumber = "";
1324        if (entityTypeContactInfoBo.getPhoneNumbers() != null) {
1325            for (int j = 0; j < entityTypeContactInfoBo.getPhoneNumbers().size(); j++) {
1326                if (entityTypeContactInfoBo.getPhoneNumbers().get(j).getPhoneTypeCode().equalsIgnoreCase("HM")) {
1327                    phoneNumber = (entityTypeContactInfoBo.getPhoneNumbers().get(j).getPhoneNumber());
1328                }
1329            }
1330        }
1331        return phoneNumber;
1332    }
1333
1334    private String getPatronHomeEmailId(EntityTypeContactInfoBo entityTypeContactInfoBo) throws Exception {
1335        LOG.debug("Inside the getPatronHomeEmailId method");
1336        String emailId = "";
1337        if (entityTypeContactInfoBo.getEmailAddresses() != null) {
1338            for (int j = 0; j < entityTypeContactInfoBo.getEmailAddresses().size(); j++) {
1339                if (entityTypeContactInfoBo.getEmailAddresses().get(j).getEmailTypeCode().equalsIgnoreCase("HM")) {
1340                    emailId = (entityTypeContactInfoBo.getEmailAddresses().get(j).getEmailAddress());
1341                }
1342            }
1343        }
1344        return emailId;
1345    }
1346
1347    private static int determineDifferenceInDays(Date currentDate, Date dueDate) {
1348        Calendar calendar1 = Calendar.getInstance();
1349        calendar1.setTime(dueDate);
1350        Calendar calendar2 = Calendar.getInstance();
1351        calendar2.setTime(currentDate);
1352        long diffInMillis = calendar2.getTimeInMillis() - calendar1.getTimeInMillis();
1353        return (int) (diffInMillis / (24 * 1000 * 60 * 60));
1354    }
1355
1356
1357    public void generateNotices() throws Exception {
1358        DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1359        List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePatronDocument.class);
1360        for (OlePatronDocument olePatronDocument : patronDocumentList) {
1361            Map<String, String> requestMap = new HashMap<String, String>();
1362            requestMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, olePatronDocument.getOlePatronId());
1363            List<OleLoanDocument> oleLoanDocumentList = (List<OleLoanDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class, requestMap);
1364            for (OleLoanDocument oleLoanDocument : oleLoanDocumentList) {
1365                try {
1366                    List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
1367                    Map docStoreDetails = QueryServiceImpl.getInstance().getItemDetails(oleLoanDocument.getItemId(), null);
1368                    String itemXml = loanProcessor.getItemXML(oleLoanDocument.getItemUuid());
1369                    Item oleItem = loanProcessor.getItemPojo(itemXml);
1370                    oleLoanDocument.setOleItem(oleItem);
1371                    oleLoanDocument.setOlePatron(olePatronDocument);
1372                    OleNoticeBo oleNoticeBo = new OleNoticeBo();
1373                    Date dueDate = oleLoanDocument.getLoanDueDate();
1374                    Date currentDate = new Date();
1375                    Integer dueDateDiffInterval = determineDifferenceInDays(dueDate, currentDate);
1376                    DateFormat formatter = new SimpleDateFormat(OLEConstants.DAT_FORM);
1377                    LOG.info("oleItem.getItemStatusEffectiveDate()" + oleItem.getItemStatusEffectiveDate());
1378                    Date itemStatusEffectiveDate = (Date) formatter.parse(oleItem.getItemStatusEffectiveDate());
1379                    Integer numberOfDaysOnHold = determineDifferenceInDays(itemStatusEffectiveDate, currentDate);
1380                    Integer dueDateSumInterval = determineDifferenceInDays(currentDate, dueDate);
1381                    Integer overdueNoticeInterval = Integer.parseInt(getIntervalForOverdueNotice());
1382                    Integer intervalWithNoticeCount = 0;
1383                    Integer loanNoOfOverdueNoticeSent = oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent()) : 0;
1384                    if (oleLoanDocument.getNumberOfOverdueNoticesSent() != null) {
1385                        intervalWithNoticeCount = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent()) + 1;
1386                    } else {
1387                        intervalWithNoticeCount = intervalWithNoticeCount + 1;
1388                    }
1389                    intervalWithNoticeCount = intervalWithNoticeCount * overdueNoticeInterval;
1390                    if (dueDateSumInterval < 0) {
1391                        dueDateSumInterval = 0;
1392                    }
1393                    if (dueDateDiffInterval < 0) {
1394                        dueDateDiffInterval = 0;
1395                    }
1396                    Integer maxNumberOfDaysOnHold = 0;
1397                    OleCirculationDesk oleCirculationDesk = null;
1398                    if (oleLoanDocument.getCirculationLocationId() != null) {
1399                        oleCirculationDesk = loanProcessor.getOleCirculationDesk(oleLoanDocument.getCirculationLocationId());
1400                        String maxNumOfDays = oleCirculationDesk.getOnHoldDays() != null ? oleCirculationDesk.getOnHoldDays() : loanProcessor.getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1401                        maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1402                    }
1403                    if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
1404                        OleInstanceItemType oleInstanceItemType = loanProcessor.getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
1405                        oleLoanDocument.setItemTypeName(oleInstanceItemType.getInstanceItemTypeCode());
1406                    }
1407                    oleLoanDocument.setInstanceUuid((String) docStoreDetails.get(OLEConstants.INSTANCE_UUID));
1408                    loanProcessor.getLocation(oleItem, oleLoanDocument);
1409                    String agendaName = OLEConstants.NOTICE_AGENDA_NM;
1410                    dataCarrierService.addData(OLEConstants.CIRC_POLICY_FOUND, null);
1411                    HashMap<String, Object> termValues = new HashMap<String, Object>();
1412                    termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1413                    termValues.put(OLEConstants.ITEM_TYPE, oleLoanDocument.getItemTypeName());
1414                    termValues.put(OLEConstants.OVERLAY_ITEM_LOCATION, oleLoanDocument.getItemLocation());
1415                    termValues.put(OLEConstants.DUE_DATE_DIFF_INTERVAL, dueDateDiffInterval);
1416                    if (oleItem.getItemStatus() != null)
1417                        termValues.put(OLEConstants.ITEM_STATUS, oleItem.getItemStatus().getCodeValue());
1418                    termValues.put(OLEConstants.NO_OF_DAYS_ON_HOLD, numberOfDaysOnHold);
1419                    termValues.put(OLEConstants.MAX_NO_OF_DAYS_ONHOLD, maxNumberOfDaysOnHold);
1420                    termValues.put(OLEConstants.OleDeliverRequest.CLAIM_RETURNED, oleLoanDocument.isClaimsReturnedIndicator() ? "true" : "false");
1421                    termValues.put(OLEConstants.OleDeliverRequest.REPLACEMENT_FEE_PATRON_BILL, oleLoanDocument.getRepaymentFeePatronBillId() != null ? "true" : "false");
1422                    termValues.put(OLEConstants.OleDeliverRequest.NUBER_OF_OVER_DUE_SENT, loanNoOfOverdueNoticeSent);
1423                    termValues.put(OLEConstants.OleDeliverRequest.DUE_DATE_SUM_INTERVAL, dueDateSumInterval);
1424                    termValues.put(OLEConstants.OleDeliverRequest.CONFIGURABLE_INTERVAL, Integer.parseInt(getIntervalForCourtesyNotice()));
1425                    termValues.put(OLEConstants.OleDeliverRequest.INTERVAL_WITH_NOTICE_COUNT, intervalWithNoticeCount);
1426                    termValues.put(OLEConstants.ITEM_SHELVING, oleLoanDocument.getItemLocation());
1427                    termValues.put(OLEConstants.ITEM_COLLECTION, oleLoanDocument.getItemCollection());
1428                    termValues.put(OLEConstants.ITEM_LIBRARY, oleLoanDocument.getItemLibrary());
1429                    termValues.put(OLEConstants.ITEM_CAMPUS, oleLoanDocument.getItemCampus());
1430                    termValues.put(OLEConstants.ITEM_INSTITUTION, oleLoanDocument.getItemInstitution());
1431                    LOG.info("termValues.toString()" + termValues.toString());
1432                    EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1433                    String notice = (String) engineResults.getAttribute(OLEConstants.NOTICE);
1434                    String itemStatus = (String) engineResults.getAttribute(OLEConstants.ITEM_STATUS);
1435                    BigDecimal replacementBill = (BigDecimal) engineResults.getAttribute(OLEConstants.REPLACEMENT_BILL);
1436                    List<String> errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
1437                    if (errorMessage != null) {
1438                        LOG.info("errorMessage" + errorMessage.toString());
1439                    }
1440                    LOG.info("notice" + notice);
1441                    agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1442                    termValues = new HashMap<String, Object>();
1443                    String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1444                    String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1445                    termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1446                    termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1447                    termValues.put(OLEConstants.NOTICE, notice);
1448                    engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1449                    String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1450                    errorMessage = (List<String>) engineResults.getAttribute(OLEConstants.ERROR_ACTION);
1451                    if (errorMessage != null) {
1452                        LOG.info("errorMessage" + errorMessage);
1453                    }
1454                    LOG.info("noticeType" + noticeType);
1455                    if (itemStatus != null) {
1456                        int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
1457                        noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
1458                        oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
1459                        oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
1460                        String billNumber = loanProcessor.generatePatronBillPayment(oleLoanDocument, OLEConstants.REPLACEMENT_FEE, replacementBill);
1461                        oleLoanDocument.setRepaymentFeePatronBillId(billNumber);
1462                        getBusinessObjectService().save(oleLoanDocument);
1463                        loanProcessor.updateItemStatus(oleItem, itemStatus);
1464                    }
1465                    OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1466                    if (notice != null) {
1467                        oleNoticeBo.setNoticeName(notice);
1468                    /*if(notice.equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)){
1469                        oleNoticeBo = getExpiredHoldNotice(oleLoanDocument);
1470                    } else */
1471                        if (notice.equalsIgnoreCase(OLEConstants.NOTICE_OVERDUE)) {
1472                            oleNoticeBo = getOverdueNotice(oleLoanDocument);
1473                            noticeType = noticeType == null ? loanProcessor.getParameter(OLEParameterConstants.OVERDUE_NOTICE_TYPE) : noticeType;
1474                        } else if (notice.equalsIgnoreCase(OLEConstants.NOTICE_COURTESY)) {
1475                            oleNoticeBo = getCourtesyNotice(oleLoanDocument);
1476                            noticeType = noticeType == null ? loanProcessor.getParameter(OLEParameterConstants.COURTESY_NOTICE_TYPE) : noticeType;
1477                        }
1478                        oleNoticeBo.setCirculationDeskName(deskLocationName);
1479                        oleNoticeBos.add(oleNoticeBo);
1480                        if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.MAIL)) {
1481                            oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
1482                        }
1483                    }
1484
1485                    olePatronDocument = oleLoanDocument.getOlePatron();
1486                    if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1487                        String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1488                        if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1489                            fromAddress = OLEConstants.KUALI_MAIL;
1490                        }
1491                        if (olePatronDocument.getEmailAddress() != null && !olePatronDocument.getEmailAddress().isEmpty()) {
1492                            List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
1493                            OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1494                            oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1495                            LOG.info("Mail send successfully to " + oleNoticeBo.getPatronEmailAddress());
1496                      /*  Mailer mailer =CoreApiServiceLocator.getMailer();
1497                        mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(olePatronDocument.getEmailAddress()), new EmailSubject("Notice Mail"), new EmailBody(list.toString()), true);
1498                      */
1499                            LOG.info("olePatronDocument.getEmailAddress()" + olePatronDocument.getEmailAddress());
1500                        }
1501                    } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1502                        //TODO : sms in progress.
1503                    }
1504                } catch (Exception e) {
1505                    LOG.error("Exception in generateNotices()" + e.getMessage(), e);
1506                }
1507            }
1508        }
1509    }
1510
1511    public void generateHoldCourtesyNotice() throws Exception {
1512
1513        List<OleDeliverRequestBo> oleDeliverRequestBos = (List<OleDeliverRequestBo>) KRADServiceLocator.getBusinessObjectService().findAll(OleDeliverRequestBo.class);
1514        for (OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBos) {
1515            List<OleNoticeBo> oleNoticeBos = new ArrayList<OleNoticeBo>();
1516            DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1517            if (docstoreHelperService.isItemAvailableInDocStore(oleDeliverRequestBo)) {
1518                Item oleItem = oleDeliverRequestBo.getOleItem();
1519                OleNoticeBo oleNoticeBo = new OleNoticeBo();
1520                Date currentDate = new Date();
1521                DateFormat formatter = new SimpleDateFormat(OLEConstants.DAT_FORM);
1522                Date itemStatusEffectiveDate = (Date) formatter.parse(oleItem.getItemStatusEffectiveDate());
1523                Integer numberOfDaysOnHold = determineDifferenceInDays(currentDate, itemStatusEffectiveDate);
1524
1525                Integer maxNumberOfDaysOnHold = 0;
1526                OleCirculationDesk oleCirculationDesk = null;
1527                if (oleDeliverRequestBo.getPickUpLocationId() != null) {
1528                    oleCirculationDesk = loanProcessor.getOleCirculationDesk(oleDeliverRequestBo.getPickUpLocationId());
1529                    String maxNumOfDays = oleCirculationDesk.getOnHoldDays() != null ? oleCirculationDesk.getOnHoldDays() : loanProcessor.getParameter(OLEConstants.MAX_NO_OF_DAYS_ON_HOLD);
1530                    maxNumberOfDaysOnHold = new Integer(maxNumOfDays);
1531                }
1532                String itemTypeName = null;
1533                if (oleItem.getItemType() != null && oleItem.getItemType().getCodeValue() != "") {
1534                    OleInstanceItemType oleInstanceItemType = loanProcessor.getItemTypeIdByItemType(oleItem.getItemType().getCodeValue());
1535                    itemTypeName = oleInstanceItemType.getInstanceItemTypeCode();
1536                }
1537                OlePatronDocument olePatronDocument = oleDeliverRequestBo.getOlePatron();
1538
1539                String agendaName = "Notice Validation";
1540                dataCarrierService.addData(OLEConstants.CIRC_POLICY_FOUND, null);
1541                HashMap<String, Object> termValues = new HashMap<String, Object>();
1542                termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1543                termValues.put(OLEConstants.ITEM_TYPE, itemTypeName);
1544                termValues.put(OLEConstants.OVERLAY_ITEM_LOCATION, oleDeliverRequestBo.getShelvingLocation());
1545                termValues.put(OLEConstants.NO_OF_DAYS_ON_HOLD, numberOfDaysOnHold);
1546                termValues.put(OLEConstants.MAX_NO_OF_DAYS_ONHOLD, maxNumberOfDaysOnHold);
1547                termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
1548                termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
1549                termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
1550                termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
1551                termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
1552                if (oleItem.getItemStatus() != null)
1553                    termValues.put(OLEConstants.ITEM_STATUS, oleItem.getItemStatus().getCodeValue());
1554                LOG.info("termValues.toString()" + termValues.toString());
1555                EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1556                String notice = (String) engineResults.getAttribute(OLEConstants.NOTICE);
1557                LOG.info("notice" + notice);
1558                agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1559                termValues = new HashMap<String, Object>();
1560                String deskLocation = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskCode() : "";
1561                String deskLocationName = oleCirculationDesk != null ? oleCirculationDesk.getCirculationDeskPublicName() : "";
1562                termValues.put(OLEConstants.BORROWER_TYPE, olePatronDocument.getOleBorrowerType().getBorrowerTypeCode());
1563                termValues.put(OLEConstants.DESK_LOCATION, deskLocation);
1564                termValues.put(OLEConstants.NOTICE, notice);
1565                LOG.info("termValues.toString()" + termValues.toString());
1566                engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1567                String noticeType = (String) engineResults.getAttribute(OLEConstants.NOTICE_TYPE);
1568                LOG.info("**************" + noticeType);
1569
1570                OleDeliverBatchServiceImpl oleDeliverBatchService = new OleDeliverBatchServiceImpl();
1571                if (notice != null) {
1572                    oleNoticeBo.setNoticeName(notice);
1573                    if (notice.equalsIgnoreCase(OLEConstants.NOTICE_HOLD_COURTESY)) {
1574                        oleNoticeBo = getExpiredHoldNotice(oleDeliverRequestBo);
1575                        oleNoticeBo.setCirculationDeskName(deskLocationName);
1576                        oleNoticeBos.add(oleNoticeBo);
1577                        noticeType = noticeType == null ? loanProcessor.getParameter("HOLDCOURTESY_NOTICE_TYPE") : noticeType;
1578                    }
1579                    if (oleNoticeBos.size() > 0 && noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.MAIL)) {
1580                        oleDeliverBatchService.getPdfNoticeForPatron(oleNoticeBos);
1581                    }
1582
1583                }
1584                olePatronDocument = oleDeliverRequestBo.getOlePatron();
1585                if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.EMAIL)) {
1586                    String fromAddress = getLoanProcessor().getParameter(OLEParameterConstants.NOTICE_FROM_MAIL);
1587                    if (fromAddress != null && (fromAddress.equals("") || fromAddress.trim().isEmpty())) {
1588                        fromAddress = OLEConstants.KUALI_MAIL;
1589                    }
1590                    if (olePatronDocument.getEmailAddress() != null && !olePatronDocument.getEmailAddress().isEmpty()) {
1591                        List list = oleDeliverBatchService.getNoticeForPatron(oleNoticeBos);
1592                        OleMailer oleMailer = GlobalResourceLoader.getService("oleMailer");
1593                        oleMailer.sendEmail(new EmailFrom(fromAddress), new EmailTo(oleNoticeBo.getPatronEmailAddress()), new EmailSubject(OLEConstants.NOTICE_MAIL), new EmailBody(list.toString()), true);
1594/*
1595                        Mailer mailer =CoreApiServiceLocator.getMailer();
1596                        mailer.sendEmail(new EmailFrom(OLEConstants.KUALI_MAIL), new EmailTo(olePatronDocument.getEmailAddress()), new EmailSubject("Notice Mail"), new EmailBody(list.toString()), true);
1597                     */
1598                        LOG.info("olePatronDocument.getEmailAddress()" + olePatronDocument.getEmailAddress());
1599                    }
1600                } else if (noticeType != null && noticeType.equalsIgnoreCase(OLEConstants.SMS)) {
1601                    //TODO : sms in progress.
1602                }
1603            }
1604        }
1605    }
1606
1607    public void deleteTemporaryHistoryRecord() throws Exception {
1608        List<OlePatronDocument> patronDocumentList = (List<OlePatronDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePatronDocument.class);
1609        for (OlePatronDocument olePatronDocument : patronDocumentList) {
1610            Map<String, String> requestMap = new HashMap<String, String>();
1611            requestMap.put(OLEConstants.OlePatron.PATRON_ID, olePatronDocument.getOlePatronId());
1612            List<OleTemporaryCirculationHistory> oleTemporaryCirculationHistoryList = (List<OleTemporaryCirculationHistory>) KRADServiceLocator.getBusinessObjectService().findMatching(OleTemporaryCirculationHistory.class, requestMap);
1613            List<OleTemporaryCirculationHistory> deleteRecords = new ArrayList<OleTemporaryCirculationHistory>();
1614            for (OleTemporaryCirculationHistory oleTemporaryCirculationHistory : oleTemporaryCirculationHistoryList) {
1615                String agendaName = OLEConstants.BATCH_PROGRAM_AGENDA;
1616                HashMap<String, Object> termValues = new HashMap<String, Object>();
1617                termValues.put(OLEConstants.OleDeliverRequest.IS_TEMPORARY_HISTORY_RECORD, "true");
1618                DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1619                dataCarrierService.addData(OLEConstants.DATE_CHECK_IN, oleTemporaryCirculationHistory.getCheckInDate());
1620                EngineResults engineResults = loanProcessor.getEngineResults(agendaName, termValues);
1621                Boolean deleteRecord = (Boolean) engineResults.getAttribute(OLEConstants.OVERLAY_OPTION_DELETE);
1622                if (deleteRecord != null && deleteRecord) {
1623                    deleteRecords.add(oleTemporaryCirculationHistory);
1624                }
1625            }
1626            getBusinessObjectService().delete(deleteRecords);
1627        }
1628    }
1629
1630    private OleNoticeBo getExpiredHoldNotice(OleDeliverRequestBo oleDeliverRequestBo) throws Exception {
1631        LOG.debug("Expired Hold Notice");
1632        Item oleItem = oleDeliverRequestBo.getOleItem();
1633        EntityTypeContactInfoBo entityTypeContactInfoBo = oleDeliverRequestBo.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1634        OleNoticeBo oleNoticeBo = new OleNoticeBo();
1635        Map docStoreDetails = QueryServiceImpl.getInstance().getItemDetails(null, oleDeliverRequestBo.getItemUuid());
1636        Map bibInformation = QueryServiceImpl.getInstance().getTitleAndAuthorfromBib((String) docStoreDetails.get(OLEConstants.BIBUUID));
1637        String shelvingLocation = oleDeliverRequestBo.getShelvingLocation();
1638        oleNoticeBo.setCirculationDeskName("");
1639        oleNoticeBo.setCirculationDeskAddress("");
1640        oleNoticeBo.setCirculationDeskEmailAddress("");
1641        oleNoticeBo.setCirculationDeskPhoneNumber("");
1642        oleNoticeBo.setCirculationDeskPhoneNumber("");
1643        oleNoticeBo.setPatronName(oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleDeliverRequestBo.getOlePatron().getEntity().getNames().get(0).getLastName());
1644        oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1645        oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1646        oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1647        oleNoticeBo.setNoticeName(OLEConstants.NOTICE_HOLD_COURTESY);
1648        oleNoticeBo.setNoticeSpecificContent(LoanUtil.getLoanUtil().getProperty(OLEConstants.OleDeliverRequest.EXP_HOLD_NOTICE_CONTENT));
1649        oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
1650        oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");
1651        oleNoticeBo.setVolumeNumber((String) docStoreDetails.get(OLEConstants.VOL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.VOL_NUM) : "");
1652        oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
1653        oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
1654        oleNoticeBo.setItemId(oleDeliverRequestBo.getItemId() != null ? oleDeliverRequestBo.getItemId() : "");
1655        oleNoticeBo.setOleItem(oleItem);
1656        oleNoticeBo.setOlePatron(oleDeliverRequestBo.getOlePatron());
1657        oleNoticeBo = setPatronDetailsForNotice(oleNoticeBo, oleDeliverRequestBo.getOlePatron());
1658        oleDeliverRequestBo.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
1659        return oleNoticeBo;
1660    }
1661
1662    private OleNoticeBo getCourtesyNotice(OleLoanDocument oleLoanDocument) throws Exception {
1663        LOG.debug("Courtesy Notice");
1664        EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1665        OleNoticeBo oleNoticeBo = new OleNoticeBo();
1666        //String itemId  = oleLoanDocument.getItemId();
1667        Map docStoreDetails = QueryServiceImpl.getInstance().getItemDetails(null, oleLoanDocument.getItemUuid());
1668        String shelvingLocation = oleLoanDocument.getItemLocation();
1669        Map bibInformation = QueryServiceImpl.getInstance().getTitleAndAuthorfromBib((String) docStoreDetails.get(OLEConstants.BIBUUID));
1670        oleNoticeBo.setCirculationDeskName("");
1671        oleNoticeBo.setCirculationDeskAddress("");
1672        oleNoticeBo.setCirculationDeskEmailAddress("");
1673        oleNoticeBo.setCirculationDeskPhoneNumber("");
1674        oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
1675        oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1676        oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1677        oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1678        oleNoticeBo.setNoticeName(OLEConstants.NOTICE_COURTESY);
1679        oleNoticeBo.setNoticeSpecificContent(LoanUtil.getLoanUtil().getProperty(OLEConstants.OleDeliverRequest.COURTESY_NOTICE_CONTENT));
1680        oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
1681        oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");
1682        oleNoticeBo.setVolumeNumber((String) docStoreDetails.get(OLEConstants.VOL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.VOL_NUM) : "");
1683        oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
1684        oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
1685        oleNoticeBo.setItemId(oleLoanDocument.getItemId());
1686        oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
1687        LOG.info("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
1688        return oleNoticeBo;
1689    }
1690
1691    private OleNoticeBo getOverdueNotice(OleLoanDocument oleLoanDocument) throws Exception {
1692        LOG.debug("Overdue Notice");
1693        EntityTypeContactInfoBo entityTypeContactInfoBo = oleLoanDocument.getOlePatron().getEntity().getEntityTypeContactInfos().get(0);
1694        OleNoticeBo oleNoticeBo = new OleNoticeBo();
1695        //   String itemId  = oleLoanDocument.getItemId();
1696        Item oleItem = oleLoanDocument.getOleItem();
1697        //  String itemUuid = oleItem.getItemIdentifier();
1698        String shelvingLocation = oleLoanDocument.getItemLocation();
1699        Map docStoreDetails = QueryServiceImpl.getInstance().getItemDetails(null, oleLoanDocument.getItemUuid());
1700        Map bibInformation = QueryServiceImpl.getInstance().getTitleAndAuthorfromBib((String) docStoreDetails.get(OLEConstants.BIBUUID));
1701        oleNoticeBo.setCirculationDeskName("");
1702        oleNoticeBo.setCirculationDeskAddress("");
1703        oleNoticeBo.setCirculationDeskEmailAddress("");
1704        oleNoticeBo.setCirculationDeskPhoneNumber("");
1705        oleNoticeBo.setPatronName(oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getFirstName() + " " + oleLoanDocument.getOlePatron().getEntity().getNames().get(0).getLastName());
1706        oleNoticeBo.setPatronAddress(getPatronPreferredAddress(entityTypeContactInfoBo) != null ? getPatronPreferredAddress(entityTypeContactInfoBo) : "");
1707        oleNoticeBo.setPatronEmailAddress(getPatronHomeEmailId(entityTypeContactInfoBo) != null ? getPatronHomeEmailId(entityTypeContactInfoBo) : "");
1708        oleNoticeBo.setPatronPhoneNumber(getPatronHomePhoneNumber(entityTypeContactInfoBo) != null ? getPatronHomePhoneNumber(entityTypeContactInfoBo) : "");
1709        oleNoticeBo.setNoticeName(OLEConstants.NOTICE_OVERDUE);
1710        oleNoticeBo.setNoticeSpecificContent(LoanUtil.getLoanUtil().getProperty(OLEConstants.OleDeliverRequest.OVERDUE_NOTICE_CONTENT));
1711        oleNoticeBo.setTitle((String) bibInformation.get(OLEConstants.TITLE) != null ? (String) bibInformation.get(OLEConstants.TITLE) : "");
1712        oleNoticeBo.setAuthor((String) bibInformation.get(OLEConstants.AUTHOR) != null ? (String) bibInformation.get(OLEConstants.AUTHOR) : "");
1713        //oleNoticeBo.setVolumeNumber((String) docStoreDetails.get(OLEConstants.VOL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.VOL_NUM) : "");
1714        String volume=(String)oleItem.getEnumeration()!=null && !oleItem.getEnumeration().equals("")?oleItem.getEnumeration():"";
1715        String issue=new String(" ");
1716        String copyNumber=(String)oleItem.getCopyNumber()!=null && !oleItem.getCopyNumber().equals("")?oleItem.getCopyNumber():"";
1717        oleNoticeBo.setVolumeIssueCopyNumber(volume+"/"+issue+"/"+copyNumber);
1718        oleNoticeBo.setItemShelvingLocation(shelvingLocation != null ? shelvingLocation : "");
1719        oleNoticeBo.setItemCallNumber((String)oleItem.getCallNumber().getNumber()!=null && !oleItem.getCallNumber().getNumber().equals("")?oleItem.getCallNumber().getNumber():"");
1720        //oleNoticeBo.setItemCallNumber((String) docStoreDetails.get(OLEConstants.CALL_NUM) != null ? (String) docStoreDetails.get(OLEConstants.CALL_NUM) : "");
1721        oleNoticeBo.setItemId(oleLoanDocument.getItemId());
1722        oleNoticeBo.setDueDate(oleLoanDocument.getLoanDueDate().toString().substring(0, 10));
1723        oleLoanDocument.getOlePatron().setEmailAddress(oleNoticeBo.getPatronEmailAddress());
1724        LOG.info("oleNoticeBo.getPatronEmailAddress()" + oleNoticeBo.getPatronEmailAddress());
1725        int noOfOverdueNoticeSent = Integer.parseInt(oleLoanDocument.getNumberOfOverdueNoticesSent() != null ? oleLoanDocument.getNumberOfOverdueNoticesSent() : "0");
1726        noOfOverdueNoticeSent = noOfOverdueNoticeSent + 1;
1727        LOG.debug("Updated Loan Record : " + oleLoanDocument);
1728        oleLoanDocument.setNumberOfOverdueNoticesSent(Integer.toString(noOfOverdueNoticeSent));
1729        oleLoanDocument.setOverDueNoticeDate(new java.sql.Date(System.currentTimeMillis()));
1730        getBusinessObjectService().save(oleLoanDocument);
1731        return oleNoticeBo;
1732    }
1733
1734    public void updateItem(Item oleItem, String itemUuid) throws Exception {
1735        ItemStatus itemStatus = new ItemStatus();
1736        itemStatus.setCodeValue(OLEConstants.OleDeliverRequest.MISSING);
1737        itemStatus.setFullValue(OLEConstants.OleDeliverRequest.MISSING);
1738        oleItem.setItemStatus(itemStatus);
1739        oleItem.setStaffOnlyFlag(true);
1740        String itemContent = new WorkItemOlemlRecordProcessor().toXML(oleItem);
1741        String itemRecordUpdateResponse =
1742                getDocstoreHelperService().updateInstanceRecord(itemUuid, OLEConstants.ITEM_DOC_TYPE, itemContent);
1743        LOG.debug(itemRecordUpdateResponse);
1744    }
1745
1746    public String getShelvingLocation(LocationLevel oleLocationLevel) {
1747        String location = null;
1748        if (oleLocationLevel != null) {
1749            if (OLEConstants.LOCATION_LEVEL_SHELVING.equalsIgnoreCase(oleLocationLevel.getLevel()))
1750                location = oleLocationLevel.getName();
1751            else
1752                location = getShelvingLocation(oleLocationLevel.getLocationLevel());
1753        }
1754        if ("".equals(location) || location == null)
1755            return null;
1756        return location;
1757    }
1758
1759
1760    public String getIntervalForCourtesyNotice() {
1761
1762        BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
1763        Map<String, String> criteriaMap = new HashMap<String, String>();
1764        criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
1765        criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
1766        criteriaMap.put(OLEConstants.NAME, OLEParameterConstants.COURTESY_NOTICE_INTER);
1767        List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
1768        return parametersList.get(0).getValue();
1769    }
1770
1771    public String getIntervalForOverdueNotice() {
1772
1773        BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
1774        Map<String, String> criteriaMap = new HashMap<String, String>();
1775        criteriaMap.put(OLEConstants.NAMESPACE_CODE, OLEConstants.DLVR_NMSPC);
1776        criteriaMap.put(OLEConstants.COMPONENT_CODE, OLEConstants.DLVR_CMPNT);
1777        criteriaMap.put(OLEConstants.NAME, OLEConstants.OVERDUE_NOTICE_INTER);
1778        List<ParameterBo> parametersList = (List<ParameterBo>) businessObjectService.findMatching(ParameterBo.class, criteriaMap);
1779        return parametersList.get(0).getValue();
1780    }
1781
1782
1783    private PatronBillPayment getPatronBillPayment(String patronId) {
1784        LOG.debug("Inside the getPatronBillPayment method");
1785        Map billMap = new HashMap();
1786        billMap.put(OLEConstants.OleDeliverRequest.LOAN_PATRON_ID, patronId);
1787        List<PatronBillPayment> patronBillPaymentList = (List<PatronBillPayment>) getBusinessObjectService().findMatching(PatronBillPayment.class, billMap);
1788        return patronBillPaymentList != null && patronBillPaymentList.size() > 0 ? patronBillPaymentList.get(0) : null;
1789    }
1790
1791    private OlePaymentStatus getPaymentStatus() {
1792        LOG.debug("Inside the getPaymentStatus method");
1793        Map statusMap = new HashMap();
1794        statusMap.put(OLEConstants.OleDeliverRequest.PAYMENT_STATUS_NAME, OLEConstants.PAYMENT_STATUS_OUTSTANDING);
1795        List<OlePaymentStatus> olePaymentStatusList = (List<OlePaymentStatus>) getBusinessObjectService().findMatching(OlePaymentStatus.class, statusMap);
1796        return olePaymentStatusList != null && olePaymentStatusList.size() > 0 ? olePaymentStatusList.get(0) : null;
1797    }
1798
1799    private String getFeeTypeId(String feeTypeName) {
1800        LOG.debug("Inside the getOverdueFeeTypeId method");
1801        Map feeMap = new HashMap();
1802        feeMap.put(OLEConstants.FEE_TYPE_NAME, feeTypeName);
1803        List<OleFeeType> oleFeeTypes = (List<OleFeeType>) getBusinessObjectService().findMatching(OleFeeType.class, feeMap);
1804        return oleFeeTypes != null && oleFeeTypes.size() > 0 ? oleFeeTypes.get(0).getFeeTypeId() : null;
1805    }
1806
1807    public String processItemType(String itemType) {
1808
1809        LOG.debug("Inside process Item Type");
1810        Map<String, String> itemMap = new HashMap<String, String>();
1811        itemMap.put(OLEConstants.OleDeliverRequest.ITEM_TYPE_CODE, itemType);
1812        List<OleInstanceItemType> oleInstanceItemTypeList = (List<OleInstanceItemType>) businessObjectService.findMatching(OleInstanceItemType.class, itemMap);
1813        if (oleInstanceItemTypeList != null && oleInstanceItemTypeList.size() > 0) {
1814            OleInstanceItemType oleInstanceItemType = oleInstanceItemTypeList.get(0);
1815            return oleInstanceItemType.getInstanceItemTypeName();
1816        }
1817        return null;
1818    }
1819
1820    public String placeRequest(String patronId, String operatorId, String itemBarcode, boolean recall) {
1821        OleDeliverRequestBo oleDeliverRequestBo = new OleDeliverRequestBo();
1822        OlePatronDocument olePatronDocument = null;
1823        Map<String, String> patronMap = new HashMap<String, String>();
1824        patronMap.put("olePatronId", patronId);
1825        List<OlePatronDocument> olePatronDocumentList = (List<OlePatronDocument>) businessObjectService.findMatching(OlePatronDocument.class, patronMap);
1826        if (olePatronDocumentList.size() > 0) {
1827            olePatronDocument = olePatronDocumentList.get(0);
1828            oleDeliverRequestBo.setOlePatron(olePatronDocument);
1829        } else {
1830            return "No patron information";
1831        }
1832        try {
1833            if (itemBarcode == null || (itemBarcode != null && itemBarcode.isEmpty())) {
1834                return "invalid barcode";
1835            }
1836            Map itemUuid = QueryServiceImpl.getInstance().getItemDetails(itemBarcode, null);
1837            String itemUUID = ((String) itemUuid.get(OLEConstants.ITEM_UUID));
1838            if (itemUUID == null || (itemUUID != null && itemUUID.isEmpty())) {
1839                return "invalid barcode";
1840            } else {
1841                oleDeliverRequestBo.setRequestCreator("Operator");
1842                oleDeliverRequestBo.setOperatorCreateId(operatorId);
1843                oleDeliverRequestBo.setBorrowerId(patronId);
1844                oleDeliverRequestBo.setItemId(itemBarcode);
1845                oleDeliverRequestBo.setItemUuid(itemUUID);
1846                if (!processOperator(oleDeliverRequestBo)) {
1847                    return OLEConstants.INVALID_OPERATOR;
1848                }
1849                if (recall) {
1850                    oleDeliverRequestBo.setRequestTypeId("1");
1851
1852                    List<OleDeliverRequestType> oleDeliverRequestTypeList = (List<OleDeliverRequestType>) businessObjectService.findAll(OleDeliverRequestType.class);
1853                    for (OleDeliverRequestType oleDeliverRequestType : oleDeliverRequestTypeList) {
1854                        if (oleDeliverRequestType.getRequestTypeId().equals(oleDeliverRequestBo.getRequestTypeId())) {
1855                            oleDeliverRequestBo.setRequestTypeCode(oleDeliverRequestType.getRequestTypeCode());
1856                            oleDeliverRequestBo.setOleDeliverRequestType(oleDeliverRequestType);
1857                        }
1858                    }
1859                    docstoreHelperService.isItemAvailableInDocStore(oleDeliverRequestBo);
1860
1861                    boolean deliver = this.validateDeliveryPrivilege(oleDeliverRequestBo);
1862                    if (!deliver)
1863                        oleDeliverRequestBo.setRequestTypeId("2");
1864                } else {
1865                    oleDeliverRequestBo.setRequestTypeId("3");
1866                    boolean deliver = this.validateDeliveryPrivilege(oleDeliverRequestBo);
1867                    if (!deliver)
1868                        oleDeliverRequestBo.setRequestTypeId("4");
1869                }
1870              /*  if(recall)
1871                      if(deliver)
1872                    oleDeliverRequestBo.setRequestTypeId("1");
1873                        else
1874                           oleDeliverRequestBo.setRequestTypeId("2");
1875                else
1876                    if(deliver)
1877                    oleDeliverRequestBo.setRequestTypeId("3");
1878                         else
1879                            oleDeliverRequestBo.setRequestTypeId("4");*/
1880                boolean patronExpired = this.isPatronRecordExpired(oleDeliverRequestBo);
1881                if (patronExpired)
1882                    return "Patron Record Expired";
1883                boolean requestRaised = this.isRequestAlreadyRaisedByPatron(oleDeliverRequestBo);
1884                if (requestRaised)
1885                    return "Request Already Raised For This Item By The Patron ";
1886                boolean itemEligible = this.isItemEligible(oleDeliverRequestBo);
1887                if (!itemEligible)
1888                    return "Item is not eligible for circulation";
1889                boolean alreadyLoaned = this.isAlreadyLoaned(oleDeliverRequestBo);
1890                if (alreadyLoaned)
1891                    return "Item is currently in loan with the requested borrower";
1892
1893                boolean valid = false;
1894                EngineResults engineResult = this.executeEngineResults(oleDeliverRequestBo);
1895                if (engineResult != null) {
1896                    List<ResultEvent> allResults = engineResult.getAllResults();
1897                    if (allResults.size() > 0) {
1898                        for (Iterator<ResultEvent> resultEventIterator = allResults.iterator(); resultEventIterator.hasNext(); ) {
1899                            ResultEvent resultEvent = resultEventIterator.next();
1900                            if (resultEvent.getType().equals(RULE_EVALUATED))
1901                                valid |= resultEvent.getResult();
1902                        }
1903                        if ((oleDeliverRequestBo.getMessage() != null && !oleDeliverRequestBo.getMessage().isEmpty()))
1904                            return oleDeliverRequestBo.getMessage();
1905                    }
1906                }
1907                OleDeliverRequestBo oleDeliverRequestBo1 = oleDeliverRequestBo;
1908                if (recall) {
1909                    oleDeliverRequestBo1 = this.updateLoanDocument(oleDeliverRequestBo);
1910                }
1911                oleDeliverRequestBo.setOleItem(null);
1912                this.reOrderQueuePosition(oleDeliverRequestBo1);
1913                getBusinessObjectService().save(oleDeliverRequestBo1);
1914                Map<String,String> requestMap = new HashMap<String,String>();
1915                requestMap.put("borrowerId",patronId);
1916                requestMap.put("itemId",itemBarcode);
1917                List<OleDeliverRequestBo> oleDeliverRequestBoList = (List<OleDeliverRequestBo>)businessObjectService.findMatching(OleDeliverRequestBo.class,requestMap);
1918                String requestId="";
1919                if(oleDeliverRequestBoList.size()>0){
1920                    requestId = ":Request Id :"+oleDeliverRequestBoList.get(0).getRequestId();
1921                }
1922                return "Request Raised Succesfully"+requestId;
1923            }
1924
1925        } catch (Exception e) {
1926            LOG.error(e, e);
1927            return "Request failed";
1928        }
1929    }
1930
1931    public EngineResults executeEngineResults(OleDeliverRequestBo oleDeliverRequestBo) {
1932        List<OleDeliverRequestBo> recallList = new ArrayList<OleDeliverRequestBo>();
1933        List<OleDeliverRequestBo> holdList = new ArrayList<OleDeliverRequestBo>();
1934        List<OleDeliverRequestBo> pageList = new ArrayList<OleDeliverRequestBo>();
1935        List<OleDeliverRequestBo> requestsByBorrower = new ArrayList<OleDeliverRequestBo>();
1936        Engine engine = KrmsApiServiceLocator.getEngine();
1937        EngineResults engineResult = null;
1938        HashMap<String, Object> agendaValue = new HashMap<String, Object>();
1939        agendaValue.put(OLEConstants.NAME_NM, OLEConstants.REQUEST_AGENDA_NM);
1940        List<AgendaBo> agendaBos = (List<AgendaBo>) KRADServiceLocator.getBusinessObjectService().findMatching(AgendaBo.class, agendaValue);
1941        if (agendaBos != null && agendaBos.size() > 0) {
1942            AgendaBo agendaBo = agendaBos.get(0);
1943            HashMap<String, String> map = new HashMap<String, String>();
1944            map.put(OLEConstants.AGENDA_NAME, agendaBo.getName());
1945            List<MatchBo> matchBos = (List<MatchBo>) KRADServiceLocator.getBusinessObjectService().findMatching(MatchBo.class, map);
1946
1947            SelectionCriteria selectionCriteria =
1948                    SelectionCriteria.createCriteria(null, getSelectionContext(agendaBo.getContext().getName()),
1949                            getAgendaContext(OLEConstants.REQUEST_AGENDA_NM));
1950
1951            ExecutionOptions executionOptions = new ExecutionOptions();
1952            executionOptions.setFlag(ExecutionFlag.LOG_EXECUTION, true);
1953
1954            Facts.Builder factBuilder = Facts.Builder.create();
1955
1956            String borrowerType = "";
1957            if (oleDeliverRequestBo.getOlePatron() != null && oleDeliverRequestBo.getOlePatron().getOleBorrowerType() != null) {
1958                borrowerType = oleDeliverRequestBo.getOlePatron().getOleBorrowerType().getBorrowerTypeCode();
1959            }
1960            String itemType = oleDeliverRequestBo.getItemType();
1961
1962            String requestTypeId = oleDeliverRequestBo.getRequestTypeId();
1963
1964            String requestType = oleDeliverRequestBo.getRequestTypeCode();
1965
1966            String location = oleDeliverRequestBo.getShelvingLocation();
1967            LoanProcessor loanProcessor = getLoanProcessor();
1968            OleLoanDocument oleLoanDocument = loanProcessor.getOleLoanDocumentUsingItemUUID(oleDeliverRequestBo.getItemUuid());
1969            DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
1970            dataCarrierService.addData(OLEConstants.LOANED_DATE, oleLoanDocument != null ? oleLoanDocument.getCreateDate() : null);
1971            dataCarrierService.addData(OLEConstants.CIRC_POLICY_FOUND, null);
1972            String borrowerId = oleDeliverRequestBo.getBorrowerId();
1973            Map<String, String> requestMap = new HashMap<String, String>();
1974            requestMap.put(OLEConstants.ITEM_UUID, oleDeliverRequestBo.getItemUuid());
1975            if (requestTypeId != null && (requestTypeId.equals("1") || requestTypeId.equals("2"))) {
1976                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "1");
1977                recallList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
1978                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "2");
1979                recallList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
1980            } else if (requestTypeId != null && (requestTypeId.equals("3") || requestTypeId.equals("4"))) {
1981                //  holdList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
1982                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "3");
1983                holdList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
1984                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "4");
1985                holdList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
1986            } else if (requestTypeId != null && (requestTypeId.equals("5") || requestTypeId.equals("6"))) {
1987                // pageList = (List<OleDeliverRequestBo>)getBusinessObjectService().findMatching(OleDeliverRequestBo.class,requestMap);
1988                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "5");
1989                pageList = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap);
1990                requestMap.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, "6");
1991                pageList.addAll((List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestMap));
1992            }
1993            Map<String, String> requestByBorrower = new HashMap<String, String>();
1994            requestByBorrower.put(OLEConstants.OleDeliverRequest.BORROWER_ID, borrowerId);
1995            requestsByBorrower = (List<OleDeliverRequestBo>) getBusinessObjectService().findMatching(OleDeliverRequestBo.class, requestByBorrower);
1996            HashMap<String, Object> termValues = new HashMap<String, Object>();
1997            termValues.put(OLEConstants.BORROWER_TYPE, borrowerType);
1998            termValues.put(OLEConstants.ITEM_TYPE, itemType);
1999            termValues.put(OLEConstants.LOCATION, location);
2000            termValues.put(OLEConstants.ITEM_SHELVING, oleDeliverRequestBo.getShelvingLocation());
2001            termValues.put(OLEConstants.ITEM_COLLECTION, oleDeliverRequestBo.getItemCollection());
2002            termValues.put(OLEConstants.ITEM_LIBRARY, oleDeliverRequestBo.getItemLibrary());
2003            termValues.put(OLEConstants.ITEM_CAMPUS, oleDeliverRequestBo.getItemCampus());
2004            termValues.put(OLEConstants.ITEM_INSTITUTION, oleDeliverRequestBo.getItemInstitution());
2005            termValues.put(OLEConstants.MAX_NO_OF_RECALL_REQUEST, new Integer(recallList.size()) + 1);
2006            termValues.put(OLEConstants.MAX_NO_OF_HOLD_REQUEST, new Integer(holdList.size()) + 1);
2007            termValues.put(OLEConstants.MAX_NO_OF_PAGE_REQUEST, new Integer(pageList.size()) + 1);
2008            // termValues.put("maxNumberOfRequestByBorrower",requestsByBorrower.size());
2009            termValues.put(OLEConstants.OleDeliverRequest.REQUEST_TYPE_ID, requestTypeId);
2010            termValues.put(OLEConstants.REQUEST_TYPE, requestType);
2011
2012
2013            for (Iterator<MatchBo> matchBoIterator = matchBos.iterator(); matchBoIterator.hasNext(); ) {
2014                MatchBo matchBo = matchBoIterator.next();
2015                factBuilder.addFact(matchBo.getTermName(), termValues.get((matchBo.getTermName())));
2016            }
2017            LOG.info("termValues.toString()" + termValues.toString());
2018            engineResult = engine.execute(selectionCriteria, factBuilder.build(), executionOptions);
2019            List<String> errorMessage = (List<String>) engineResult.getAttribute(OLEConstants.ERROR_ACTION);
2020            java.sql.Date d = (java.sql.Date) engineResult.getAttribute(OLEConstants.REQ_EXPIRATION_DATE);
2021            Timestamp recallDueDate = (Timestamp) engineResult.getAttribute(OLEConstants.RECALL_DUE_DATE);
2022            String notice = (String) engineResult.getAttribute(OLEConstants.NOTICE);
2023            oleDeliverRequestBo.setNoticeType(notice);
2024            if (recallDueDate != null && oleLoanDocument.getLoanDueDate().compareTo(recallDueDate) > 0) {
2025                oleLoanDocument.setLoanDueDate(recallDueDate);
2026                oleDeliverRequestBo.setRecallDueDate(recallDueDate);
2027                getBusinessObjectService().save(oleLoanDocument);
2028            }
2029            oleDeliverRequestBo.setRequestExpiryDate(d);
2030            StringBuffer failures = new StringBuffer();
2031            if (errorMessage != null && errorMessage.size() > 0) {
2032                int i = 1;
2033                for (String errMsg : errorMessage) {
2034                    failures.append(i++ + ". " + errMsg + OLEConstants.BREAK);
2035                }
2036            }
2037            if (!failures.toString().isEmpty()) {
2038                oleDeliverRequestBo.setMessage(failures.toString());
2039            }
2040            dataCarrierService.addData(OLEConstants.ERROR_ACTION, null);
2041        }
2042        return engineResult;
2043    }
2044
2045    /**
2046     * This method returns SelectionContext using contextName.
2047     *
2048     * @param contextName
2049     * @return Map
2050     */
2051    protected Map<String, String> getSelectionContext(String contextName) {
2052        Map<String, String> selector = new HashMap<String, String>();
2053        selector.put(NAMESPACE_CODE_SELECTOR, OLEConstants.OLE_NAMESPACE);
2054        selector.put(NAME_SELECTOR, contextName);
2055        return selector;
2056    }
2057
2058    /**
2059     * This method returns AgendaContext using agendaName..
2060     *
2061     * @param agendaName
2062     * @return Map
2063     */
2064    protected Map<String, String> getAgendaContext(String agendaName) {
2065        Map<String, String> selector = new HashMap<String, String>();
2066        selector.put(NAME_SELECTOR, agendaName);
2067        return selector;
2068    }
2069
2070
2071}
2072
2073
2074
2075
2076
2077