View Javadoc
1   package org.kuali.ole.deliver.controller.checkout;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.apache.log4j.Logger;
5   import org.kie.api.runtime.rule.Agenda;
6   import org.kie.api.runtime.rule.AgendaGroup;
7   import org.kie.internal.runtime.StatefulKnowledgeSession;
8   import org.kuali.ole.OLEConstants;
9   import org.kuali.ole.deliver.bo.OLEDeliverNotice;
10  import org.kuali.ole.deliver.bo.OleItemSearch;
11  import org.kuali.ole.deliver.bo.OleLoanDocument;
12  import org.kuali.ole.deliver.bo.OlePatronNotes;
13  import org.kuali.ole.deliver.calendar.service.DateUtil;
14  import org.kuali.ole.deliver.drools.CustomAgendaFilter;
15  import org.kuali.ole.deliver.drools.DroolsConstants;
16  import org.kuali.ole.deliver.drools.DroolsEngine;
17  import org.kuali.ole.deliver.form.OleLoanForm;
18  import org.kuali.ole.deliver.service.CircDeskLocationResolver;
19  import org.kuali.ole.deliver.service.ParameterValueResolver;
20  import org.kuali.ole.deliver.util.ErrorMessage;
21  import org.kuali.ole.deliver.util.NoticeInfo;
22  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
23  import org.kuali.ole.docstore.common.document.Item;
24  import org.kuali.ole.docstore.common.document.ItemOleml;
25  import org.kuali.ole.docstore.common.document.content.enums.DocType;
26  import org.kuali.ole.docstore.common.document.content.instance.ItemStatus;
27  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
28  import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.ItemRecord;
29  import org.kuali.ole.sys.context.SpringContext;
30  import org.kuali.ole.util.DocstoreUtil;
31  import org.kuali.ole.utility.OleStopWatch;
32  import org.kuali.rice.kim.api.role.Role;
33  import org.kuali.rice.kim.impl.role.RoleServiceImpl;
34  import org.kuali.rice.krad.service.BusinessObjectService;
35  import org.kuali.rice.krad.service.KRADServiceLocator;
36  import org.kuali.rice.krad.util.GlobalVariables;
37  
38  import java.math.BigDecimal;
39  import java.sql.Timestamp;
40  import java.text.ParseException;
41  import java.text.SimpleDateFormat;
42  import java.util.*;
43  
44  /**
45   * Created by pvsubrah on 6/4/15.
46   */
47  public class CircUtilController {
48      private static final Logger LOG = Logger.getLogger(CircUtilController.class);
49      private BusinessObjectService businessObjectService;
50      private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
51      private DocstoreClientLocator docstoreClientLocator;
52  
53      public void fireRules(List<Object> facts, String[] expectedRules, String agendaGroup) {
54          StatefulKnowledgeSession session = DroolsEngine.getInstance().getSession();
55          Agenda agenda = session.getAgenda();
56          AgendaGroup group = agenda.getAgendaGroup(agendaGroup);
57          group.setFocus();
58          for (Iterator<Object> iterator = facts.iterator(); iterator.hasNext(); ) {
59              Object fact = iterator.next();
60              session.insert(fact);
61          }
62  
63          if (null!= expectedRules && expectedRules.length > 0) {
64              session.fireAllRules(new CustomAgendaFilter(expectedRules));
65          } else {
66              session.fireAllRules();
67          }
68          session.dispose();
69      }
70  
71      public List<OLEDeliverNotice> processNotices(NoticeInfo noticeInfo, OleLoanDocument currentLoanDocument){
72          List<OLEDeliverNotice> deliverNotices = new ArrayList<>();
73  
74          Map<String, Map<String, Object>> noticeInfoForTypeMap = noticeInfo.getNoticeInfoForTypeMap();
75  
76          if (null != noticeInfoForTypeMap) {
77              for (Iterator<String> iterator = noticeInfoForTypeMap.keySet().iterator(); iterator.hasNext(); ) {
78                  String noticeType = iterator.next();
79                  if (noticeType.equalsIgnoreCase(OLEConstants.COURTESY_NOTICE)) {
80                      processCourtseyNotices(noticeInfo, deliverNotices, currentLoanDocument);
81                  } else if (noticeType.equalsIgnoreCase(OLEConstants.OVERDUE_NOTICE)) {
82                      Integer numOverDueNoticeToBeSent = Integer.parseInt((String) noticeInfo.getNoticeInfoForTypeMap().get
83                              (OLEConstants.OVERDUE_NOTICE).get(DroolsConstants.NUMBER_OF_OVERDUE_NOTICES_TO_BE_SENT));
84                      int count = 0;
85                      for (count = 0; count < numOverDueNoticeToBeSent; count++) {
86                          processOverdueNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
87                      }
88                      processLostNotices(noticeInfo, deliverNotices, count, currentLoanDocument);
89                  }
90              }
91          }
92  
93          return deliverNotices;
94      }
95  
96      private void processLostNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, int count, OleLoanDocument currentLoanDocument) {
97          OLEDeliverNotice lostNotice = new OLEDeliverNotice();
98          lostNotice.setNoticeType(OLEConstants.NOTICE_LOST);
99          lostNotice.setNoticeSendType(DroolsConstants.EMAIL);
100         lostNotice.setPatronId(currentLoanDocument.getPatronId());
101         lostNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(Integer.parseInt((String) noticeInfo
102                 .getNoticeInfoForTypeMap().get(OLEConstants.OVERDUE_NOTICE).get(DroolsConstants
103                         .INTERVAL_TO_GENERATE_NOTICE_FOR_OVERDUE)), currentLoanDocument.getLoanDueDate(), count + 1));
104         deliverNotices.add(lostNotice);
105         lostNotice.setReplacementFeeAmount(BigDecimal.valueOf(Double.parseDouble((String) noticeInfo
106                 .getNoticeInfoForTypeMap().get(OLEConstants.OVERDUE_NOTICE).get(DroolsConstants
107                         .REPLACEMENT_BILL_AMT))));
108     }
109 
110     private void processOverdueNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, int count, OleLoanDocument currentLoanDocument) {
111         OLEDeliverNotice overdueNotice = new OLEDeliverNotice();
112         overdueNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(Integer.parseInt((String) noticeInfo
113                         .getNoticeInfoForTypeMap().get(OLEConstants.OVERDUE_NOTICE).get(DroolsConstants.INTERVAL_TO_GENERATE_NOTICE_FOR_OVERDUE)),
114                 currentLoanDocument.getLoanDueDate(), count + 1));
115         overdueNotice.setNoticeSendType(DroolsConstants.EMAIL);
116         overdueNotice.setNoticeType(OLEConstants.OVERDUE_NOTICE);
117         overdueNotice.setPatronId(currentLoanDocument.getPatronId());
118         deliverNotices.add(overdueNotice);
119     }
120 
121     private void processCourtseyNotices(NoticeInfo noticeInfo, List<OLEDeliverNotice> deliverNotices, OleLoanDocument currentLoanDocument) {
122         OLEDeliverNotice courtseyNotice = new OLEDeliverNotice();
123         String loanId = currentLoanDocument.getLoanId();
124         courtseyNotice.setNoticeType(OLEConstants.COURTESY_NOTICE);
125         courtseyNotice.setNoticeSendType(DroolsConstants.EMAIL);
126         courtseyNotice.setNoticeToBeSendDate(calculateNoticeToBeSentDate(-Integer.parseInt((String) noticeInfo
127                         .getNoticeInfoForTypeMap().get(OLEConstants.COURTESY_NOTICE).get(DroolsConstants.INTERVAL_TO_GENERATE_NOTICE_FOR_COURTSEY)),
128                 currentLoanDocument.getLoanDueDate(), 1));
129         courtseyNotice.setLoanId(loanId);
130         courtseyNotice.setPatronId(currentLoanDocument.getPatronId());
131         deliverNotices.add(courtseyNotice);
132     }
133 
134     private Timestamp calculateNoticeToBeSentDate(Integer interval, Timestamp dueDate, Integer count) {
135         Timestamp noticeToBeSentDate;
136 
137         noticeToBeSentDate = interval != null && dueDate != null ?
138                 DateUtil.addDays(dueDate, interval * count) : null;
139         return noticeToBeSentDate;
140     }
141 
142     public ItemRecord getItemRecordByBarcode(String itemBarcode){
143         ItemRecord itemRecord = null;
144         HashMap<String, String> criteriaMap = new HashMap<>();
145         criteriaMap.put("barCode", itemBarcode);
146         List<ItemRecord> itemRecords = (List<ItemRecord>) getBusinessObjectService().findMatching(ItemRecord.class,
147                 criteriaMap);
148         if (null != itemRecords && !itemRecords.isEmpty()) {
149             itemRecord = itemRecords.get(0);
150         }
151 
152         return itemRecord;
153     }
154 
155     public String convertDateToString(Date date ,String format){
156         LOG.info("Date Format : " + format + "Date : " + date);
157         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
158         String dateValue ="";
159         try{
160             dateValue = simpleDateFormat.format(date);
161         }catch(Exception e){
162             LOG.error(e,e);
163         }
164         LOG.info("Formatted Date : " + dateValue);
165         return dateValue;
166     }
167 
168     public String convertToString(Timestamp date) {
169         SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
170         SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
171         Date itemDate = null;
172         try {
173             itemDate = format2.parse(date.toString());
174         } catch (ParseException e) {
175             LOG.error("format string to Date " + e);
176         }
177         return format1.format(itemDate).toString();
178     }
179 
180     public String getLoginUserId() {
181         return GlobalVariables.getUserSession().getPrincipalId();
182     }
183 
184 
185     public BusinessObjectService getBusinessObjectService() {
186         if (null == businessObjectService) {
187             businessObjectService = KRADServiceLocator.getBusinessObjectService();
188         }
189         return businessObjectService;
190     }
191 
192     public CircDeskLocationResolver getCircDeskLocationResolver() {
193         return new CircDeskLocationResolver();
194     }
195 
196     public ItemOlemlRecordProcessor getItemOlemlRecordProcessor() {
197         if(itemOlemlRecordProcessor == null){
198             itemOlemlRecordProcessor = SpringContext.getBean(ItemOlemlRecordProcessor.class);
199         }
200         return itemOlemlRecordProcessor;
201     }
202 
203     public DocstoreClientLocator getDocstoreClientLocator() {
204         if (docstoreClientLocator == null) {
205             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
206         }
207         return docstoreClientLocator;
208     }
209 
210 
211     public void rollBackSavedLoanRecord(String barcode) {
212         Map<String, String> criteria = new HashMap<String, String>();
213         criteria.put("itemId", barcode);
214         List<OleLoanDocument> oleLoanDocument = (List<OleLoanDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleLoanDocument.class, criteria);
215         if (oleLoanDocument.size() > 0) {
216             KRADServiceLocator.getBusinessObjectService().delete(oleLoanDocument.get(0));
217         }
218     }
219 
220     public OleLoanDocument updateLoanDocumentWithItemInformation(ItemRecord itemRecord, OleLoanDocument oleLoanDocument) {
221 
222         OleItemSearch oleItemSearch = new DocstoreUtil().getOleItemSearchList(itemRecord.getItemId());
223         oleLoanDocument.setTitle(oleItemSearch.getTitle());
224         oleLoanDocument.setAuthor(oleItemSearch.getAuthor());
225         oleLoanDocument.setLocation(oleItemSearch.getShelvingLocation());
226         oleLoanDocument.setItemCallNumber(oleItemSearch.getCallNumber());
227         oleLoanDocument.setItemCopyNumber(oleItemSearch.getCopyNumber());
228         oleLoanDocument.setChronology(oleItemSearch.getChronology());
229         oleLoanDocument.setEnumeration(oleItemSearch.getEnumeration());
230         oleLoanDocument.setItemStatus(oleItemSearch.getItemStatus());
231         oleLoanDocument.setItemUuid(oleItemSearch.getItemUUID());
232         oleLoanDocument.setInstanceUuid(oleItemSearch.getInstanceUUID());
233         oleLoanDocument.setBibUuid(oleItemSearch.getBibUUID());
234         return oleLoanDocument;
235     }
236 
237 
238 
239     public Boolean updateItemInfoInSolr(Map map, String itemUUID) {
240         org.kuali.ole.docstore.common.document.content.instance.Item oleItem = getExistingItemFromSolr(itemUUID);
241         if (oleItem != null) {
242             String patronId = null == map.get("patronId") ? null :  (String) map.get("patronId");
243             String proxyPatronId = null == map.get("proxyPatronId") ? null : (String) map.get("proxyPatronId");
244             Date itemCheckoutDateTime = null == map.get("itemCheckoutDateTime") ? null : (Date) map.get("itemCheckoutDateTime");
245             Timestamp loanDueDate = null == map.get("loanDueDate") ? null : (Timestamp) map.get("loanDueDate");
246             String numRenewals = null == map.get("numRenewals") ? null :  (String) map.get("numRenewals");
247             String itemStatus = null == map.get("itemStatus") ? null :  (String) map.get("itemStatus");
248 
249             oleItem.setCurrentBorrower(patronId);
250             oleItem.setProxyBorrower(proxyPatronId);
251             if (null != itemCheckoutDateTime) {
252                 oleItem.setCheckOutDateTime(convertDateToString(itemCheckoutDateTime, "MM/dd/yyyy HH:mm:ss"));
253             } else {
254                 oleItem.setCheckOutDateTime(null);
255             }
256 
257             if (loanDueDate != null) {
258                 oleItem.setDueDateTime(convertToString(loanDueDate));
259             } else {
260                 oleItem.setDueDateTime("");
261             }
262 
263             oleItem.setNumberOfRenew(null == numRenewals ? 0 : Integer.parseInt(numRenewals));
264 
265             try {
266                 updateItem(oleItem, itemStatus);
267             } catch (Exception e) {
268                 return false;
269             }
270         }
271         return true;
272     }
273 
274 
275 
276     private org.kuali.ole.docstore.common.document.content.instance.Item getExistingItemFromSolr(String itemUUID) {
277         ItemOlemlRecordProcessor itemOlemlRecordProcessor = new ItemOlemlRecordProcessor();
278         try {
279             Item item = getDocstoreClientLocator().getDocstoreClient().retrieveItem(itemUUID);
280             return itemOlemlRecordProcessor.fromXML(item.getContent());
281         } catch (Exception e) {
282             e.printStackTrace();
283         }
284         return null;
285     }
286 
287 
288 
289     public void updateItem(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatus) throws Exception {
290         try {
291             String itemUuid = oleItem.getItemIdentifier();
292             String itemXmlContent = buildItemContent(oleItem, itemStatus);
293             Item item = new ItemOleml();
294             item.setId(itemUuid);
295             item.setContent(itemXmlContent);
296             item.setCategory(OLEConstants.WORK_CATEGORY);
297             item.setType(DocType.ITEM.getCode());
298             item.setFormat(OLEConstants.OLEML_FORMAT);
299             item.setStaffOnly(oleItem.isStaffOnlyFlag());
300             getDocstoreClientLocator().getDocstoreClient().updateItem(item);
301         } catch (Exception e) {
302             LOG.error(OLEConstants.ITM_STS_TO_DOC_FAIL + e, e);
303             throw new Exception(OLEConstants.ITM_STS_TO_DOC_FAIL);
304         }
305     }
306 
307 
308 
309     public String buildItemContent(org.kuali.ole.docstore.common.document.content.instance.Item oleItem, String itemStatusValue) throws Exception {
310         ItemStatus itemStatus = new ItemStatus();
311         itemStatus.setCodeValue(itemStatusValue);
312         itemStatus.setFullValue(itemStatusValue);
313         oleItem.setItemStatus(itemStatus);
314         oleItem.setItemStatusEffectiveDate(String.valueOf(new SimpleDateFormat(OLEConstants.DAT_FORMAT_EFFECTIVE).format(new Date())));
315         String itemContent = getItemOlemlRecordProcessor().toXML(oleItem);
316         return itemContent;
317     }
318 
319 }