View Javadoc

1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.document.service.impl;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.ole.docstore.discovery.service.QueryService;
20  import org.kuali.ole.docstore.discovery.service.QueryServiceImpl;
21  import org.kuali.ole.docstore.model.bo.WorkBibDocument;
22  import org.kuali.ole.docstore.model.bo.WorkInstanceDocument;
23  import org.kuali.ole.docstore.model.bo.WorkItemDocument;
24  import org.kuali.ole.docstore.model.enums.DocType;
25  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkHoldingOlemlRecordProcessor;
26  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkInstanceOlemlRecordProcessor;
27  import org.kuali.ole.docstore.model.xstream.work.instance.oleml.WorkItemOlemlRecordProcessor;
28  import org.kuali.ole.integration.purap.CapitalAssetSystem;
29  import org.kuali.ole.module.purap.PurapConstants;
30  import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
31  import org.kuali.ole.module.purap.businessobject.*;
32  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
33  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
34  import org.kuali.ole.module.purap.document.RequisitionDocument;
35  import org.kuali.ole.select.OleSelectConstant;
36  import org.kuali.ole.select.businessobject.*;
37  import org.kuali.ole.select.document.OlePurchaseOrderDocument;
38  import org.kuali.ole.select.document.OleRequisitionDocument;
39  import org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService;
40  import org.kuali.ole.select.document.service.OleRequestorService;
41  import org.kuali.ole.select.document.service.OleSelectDocumentService;
42  import org.kuali.ole.select.service.BibInfoWrapperService;
43  import org.kuali.ole.select.service.FileProcessingService;
44  import org.kuali.ole.select.service.OleUrlResolver;
45  import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
46  import org.kuali.ole.sys.OLEConstants;
47  import org.kuali.ole.sys.context.SpringContext;
48  import org.kuali.rice.core.api.config.property.ConfigurationService;
49  import org.kuali.rice.core.api.datetime.DateTimeService;
50  import org.kuali.rice.core.api.util.type.KualiDecimal;
51  import org.kuali.rice.core.api.util.type.KualiInteger;
52  import org.kuali.rice.kew.api.WorkflowDocument;
53  import org.kuali.rice.kew.api.exception.WorkflowException;
54  import org.kuali.rice.kim.api.identity.Person;
55  import org.kuali.rice.kim.api.identity.PersonService;
56  import org.kuali.rice.krad.UserSession;
57  import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent;
58  import org.kuali.rice.krad.util.GlobalVariables;
59  
60  import java.util.*;
61  
62  public class OlePurchaseOrderDocumentHelperServiceImpl implements OlePurchaseOrderDocumentHelperService {
63  
64      protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderDocumentHelperServiceImpl.class);
65      private final String UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkIn&stringContent=";
66      private final String CHECKOUT_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkOut&uuid=";
67      private final String CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING = "docAction=ingestContent&stringContent=";
68      private WorkItemOlemlRecordProcessor workItemOlemlRecordProcessor;
69      private WorkHoldingOlemlRecordProcessor workHoldingOlemlRecordProcessor;
70      private WorkInstanceOlemlRecordProcessor workInstanceOlemlRecordProcessor;
71      private transient OleUrlResolver oleUrlResolver;
72      private static transient OlePatronRecordHandler olePatronRecordHandler;
73      private static transient OlePatronDocumentList olePatronDocumentList;
74      private static transient OleSelectDocumentService oleSelectDocumentService;
75  
76  
77      public static OleSelectDocumentService getOleSelectDocumentService() {
78          if (oleSelectDocumentService == null) {
79              oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
80          }
81          return oleSelectDocumentService;
82      }
83  
84      public static void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
85          OlePurchaseOrderDocumentHelperServiceImpl.oleSelectDocumentService = oleSelectDocumentService;
86      }
87  
88      public static OlePatronDocumentList getOlePatronDocumentList() {
89          if (olePatronDocumentList == null) {
90              olePatronDocumentList = SpringContext.getBean(OlePatronDocumentList.class);
91          }
92          return olePatronDocumentList;
93      }
94  
95      public static void setOlePatronDocumentList(OlePatronDocumentList olePatronDocumentList) {
96          OlePurchaseOrderDocumentHelperServiceImpl.olePatronDocumentList = olePatronDocumentList;
97      }
98  
99  
100     public OlePatronRecordHandler getOlePatronRecordHandler() {
101         if (null == olePatronRecordHandler) {
102             olePatronRecordHandler = new OlePatronRecordHandler();
103         }
104         return olePatronRecordHandler;
105     }
106 
107     public void setOlePatronRecordHandler(OlePatronRecordHandler olePatronRecordHandler) {
108         this.olePatronRecordHandler = olePatronRecordHandler;
109     }
110 
111 
112     /**
113      * This method is overridden to populate newly added ole fields from requisition into Purchase Order Document.
114      *
115      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#populatePurchaseOrderFromRequisition(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.ole.module.purap.document.RequisitionDocument)
116      */
117     @Override
118     public void populatePurchaseOrderFromRequisition(PurchaseOrderDocument purchaseOrderDoc, RequisitionDocument requisitionDoc) {
119         LOG.debug("Inside populatePurchaseOrderFromRequisition of OlePurchaseOrderDocumentHelperServiceImpl");
120         OlePurchaseOrderDocument purchaseOrderDocument = (OlePurchaseOrderDocument) purchaseOrderDoc;
121         OleRequisitionDocument requisitionDocument = (OleRequisitionDocument) requisitionDoc;
122         purchaseOrderDocument.setPurchaseOrderCreateTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
123         purchaseOrderDocument.getDocumentHeader().setOrganizationDocumentNumber(requisitionDocument.getDocumentHeader().getOrganizationDocumentNumber());
124         purchaseOrderDocument.getDocumentHeader().setDocumentDescription(requisitionDocument.getDocumentHeader().getDocumentDescription());
125         purchaseOrderDocument.getDocumentHeader().setExplanation(requisitionDocument.getDocumentHeader().getExplanation());
126         purchaseOrderDocument.setBillingName(requisitionDocument.getBillingName());
127         purchaseOrderDocument.setBillingLine1Address(requisitionDocument.getBillingLine1Address());
128         purchaseOrderDocument.setBillingLine2Address(requisitionDocument.getBillingLine2Address());
129         purchaseOrderDocument.setBillingCityName(requisitionDocument.getBillingCityName());
130         purchaseOrderDocument.setBillingStateCode(requisitionDocument.getBillingStateCode());
131         purchaseOrderDocument.setBillingPostalCode(requisitionDocument.getBillingPostalCode());
132         purchaseOrderDocument.setBillingCountryCode(requisitionDocument.getBillingCountryCode());
133         purchaseOrderDocument.setBillingPhoneNumber(requisitionDocument.getBillingPhoneNumber());
134 
135         purchaseOrderDocument.setReceivingName(requisitionDocument.getReceivingName());
136         purchaseOrderDocument.setReceivingCityName(requisitionDocument.getReceivingCityName());
137         purchaseOrderDocument.setReceivingLine1Address(requisitionDocument.getReceivingLine1Address());
138         purchaseOrderDocument.setReceivingLine2Address(requisitionDocument.getReceivingLine2Address());
139         purchaseOrderDocument.setReceivingStateCode(requisitionDocument.getReceivingStateCode());
140         purchaseOrderDocument.setReceivingPostalCode(requisitionDocument.getReceivingPostalCode());
141         purchaseOrderDocument.setReceivingCountryCode(requisitionDocument.getReceivingCountryCode());
142         purchaseOrderDocument.setAddressToVendorIndicator(requisitionDocument.getAddressToVendorIndicator());
143 
144         purchaseOrderDocument.setDeliveryBuildingCode(requisitionDocument.getDeliveryBuildingCode());
145         purchaseOrderDocument.setDeliveryBuildingRoomNumber(requisitionDocument.getDeliveryBuildingRoomNumber());
146         purchaseOrderDocument.setDeliveryBuildingName(requisitionDocument.getDeliveryBuildingName());
147         purchaseOrderDocument.setDeliveryCampusCode(requisitionDocument.getDeliveryCampusCode());
148         purchaseOrderDocument.setDeliveryCityName(requisitionDocument.getDeliveryCityName());
149         purchaseOrderDocument.setDeliveryCountryCode(requisitionDocument.getDeliveryCountryCode());
150         purchaseOrderDocument.setDeliveryInstructionText(requisitionDocument.getDeliveryInstructionText());
151         purchaseOrderDocument.setDeliveryBuildingLine1Address(requisitionDocument.getDeliveryBuildingLine1Address());
152         purchaseOrderDocument.setDeliveryBuildingLine2Address(requisitionDocument.getDeliveryBuildingLine2Address());
153         purchaseOrderDocument.setDeliveryPostalCode(requisitionDocument.getDeliveryPostalCode());
154         purchaseOrderDocument.setDeliveryRequiredDate(requisitionDocument.getDeliveryRequiredDate());
155         purchaseOrderDocument.setDeliveryRequiredDateReasonCode(requisitionDocument.getDeliveryRequiredDateReasonCode());
156         purchaseOrderDocument.setDeliveryStateCode(requisitionDocument.getDeliveryStateCode());
157         purchaseOrderDocument.setDeliveryToEmailAddress(requisitionDocument.getDeliveryToEmailAddress());
158         purchaseOrderDocument.setDeliveryToName(requisitionDocument.getDeliveryToName());
159         purchaseOrderDocument.setDeliveryToPhoneNumber(requisitionDocument.getDeliveryToPhoneNumber());
160         purchaseOrderDocument.setDeliveryBuildingOtherIndicator(requisitionDocument.isDeliveryBuildingOtherIndicator());
161         purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
162         purchaseOrderDocument.setPurchaseOrderBeginDate(requisitionDocument.getPurchaseOrderBeginDate());
163         purchaseOrderDocument.setPurchaseOrderCostSourceCode(requisitionDocument.getPurchaseOrderCostSourceCode());
164         purchaseOrderDocument.setPostingYear(requisitionDocument.getPostingYear());
165         purchaseOrderDocument.setPurchaseOrderEndDate(requisitionDocument.getPurchaseOrderEndDate());
166         purchaseOrderDocument.setChartOfAccountsCode(requisitionDocument.getChartOfAccountsCode());
167         purchaseOrderDocument.setDocumentFundingSourceCode(requisitionDocument.getDocumentFundingSourceCode());
168         purchaseOrderDocument.setInstitutionContactEmailAddress(requisitionDocument.getInstitutionContactEmailAddress());
169         purchaseOrderDocument.setInstitutionContactName(requisitionDocument.getInstitutionContactName());
170         purchaseOrderDocument.setInstitutionContactPhoneNumber(requisitionDocument.getInstitutionContactPhoneNumber());
171         purchaseOrderDocument.setNonInstitutionFundAccountNumber(requisitionDocument.getNonInstitutionFundAccountNumber());
172         purchaseOrderDocument.setNonInstitutionFundChartOfAccountsCode(requisitionDocument.getNonInstitutionFundChartOfAccountsCode());
173         purchaseOrderDocument.setNonInstitutionFundOrgChartOfAccountsCode(requisitionDocument.getNonInstitutionFundOrgChartOfAccountsCode());
174         purchaseOrderDocument.setNonInstitutionFundOrganizationCode(requisitionDocument.getNonInstitutionFundOrganizationCode());
175         purchaseOrderDocument.setOrganizationCode(requisitionDocument.getOrganizationCode());
176         purchaseOrderDocument.setRecurringPaymentTypeCode(requisitionDocument.getRecurringPaymentTypeCode());
177         purchaseOrderDocument.setRequestorPersonEmailAddress(requisitionDocument.getRequestorPersonEmailAddress());
178         purchaseOrderDocument.setRequestorPersonName(requisitionDocument.getRequestorPersonName());
179         purchaseOrderDocument.setRequestorPersonPhoneNumber(requisitionDocument.getRequestorPersonPhoneNumber());
180         purchaseOrderDocument.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
181         purchaseOrderDocument.setPurchaseOrderTotalLimit(requisitionDocument.getPurchaseOrderTotalLimit());
182         purchaseOrderDocument.setPurchaseOrderTransmissionMethodCode(requisitionDocument.getPurchaseOrderTransmissionMethodCode());
183         purchaseOrderDocument.setUseTaxIndicator(requisitionDocument.isUseTaxIndicator());
184         purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
185         purchaseOrderDocument.setVendorCityName(requisitionDocument.getVendorCityName());
186         purchaseOrderDocument.setVendorContractGeneratedIdentifier(requisitionDocument.getVendorContractGeneratedIdentifier());
187         purchaseOrderDocument.setVendorCountryCode(requisitionDocument.getVendorCountryCode());
188         purchaseOrderDocument.setVendorCustomerNumber(requisitionDocument.getVendorCustomerNumber());
189         purchaseOrderDocument.setVendorAttentionName(requisitionDocument.getVendorAttentionName());
190         purchaseOrderDocument.setVendorDetailAssignedIdentifier(requisitionDocument.getVendorDetailAssignedIdentifier());
191         purchaseOrderDocument.setVendorFaxNumber(requisitionDocument.getVendorFaxNumber());
192         purchaseOrderDocument.setVendorHeaderGeneratedIdentifier(requisitionDocument.getVendorHeaderGeneratedIdentifier());
193         purchaseOrderDocument.setVendorLine1Address(requisitionDocument.getVendorLine1Address());
194         purchaseOrderDocument.setVendorLine2Address(requisitionDocument.getVendorLine2Address());
195         purchaseOrderDocument.setVendorAddressInternationalProvinceName(requisitionDocument.getVendorAddressInternationalProvinceName());
196         purchaseOrderDocument.setVendorName(requisitionDocument.getVendorName());
197         purchaseOrderDocument.setVendorNoteText(requisitionDocument.getVendorNoteText());
198         purchaseOrderDocument.setVendorPhoneNumber(requisitionDocument.getVendorPhoneNumber());
199         purchaseOrderDocument.setVendorPostalCode(requisitionDocument.getVendorPostalCode());
200         purchaseOrderDocument.setVendorStateCode(requisitionDocument.getVendorStateCode());
201         purchaseOrderDocument.setVendorRestrictedIndicator(requisitionDocument.getVendorRestrictedIndicator());
202         purchaseOrderDocument.setVendorPoNumber(requisitionDocument.getVendorPoNumber());
203         purchaseOrderDocument.setExternalOrganizationB2bSupplierIdentifier(requisitionDocument.getExternalOrganizationB2bSupplierIdentifier());
204         purchaseOrderDocument.setRequisitionSourceCode(requisitionDocument.getRequisitionSourceCode());
205         purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
206         purchaseOrderDocument.setReceivingDocumentRequiredIndicator(requisitionDocument.isReceivingDocumentRequiredIndicator());
207         purchaseOrderDocument.setPaymentRequestPositiveApprovalIndicator(requisitionDocument.isPaymentRequestPositiveApprovalIndicator());
208         /*purchaseOrderDocument.setLicensingRequirementIndicator(requisitionDocument.isLicensingRequirementIndicator());*/
209        /* purchaseOrderDocument.setLicensingRequirementCode(requisitionDocument.getLicensingRequirementCode());*/
210 
211         purchaseOrderDocument.setStatusCode(PurapConstants.PurchaseOrderStatuses.APPDOC_IN_PROCESS);
212 
213         // Copy items from requisition (which will copy the item's accounts and capital assets)
214         List<OlePurchaseOrderItem> items = new ArrayList();
215         for (PurApItem reqItem : ((PurchasingAccountsPayableDocument) requisitionDocument).getItems()) {
216             RequisitionCapitalAssetItem reqCamsItem = (RequisitionCapitalAssetItem) requisitionDocument.getPurchasingCapitalAssetItemByItemIdentifier(reqItem.getItemIdentifier().intValue());
217             items.add(new OlePurchaseOrderItem((OleRequisitionItem) reqItem, purchaseOrderDocument, reqCamsItem));
218         }
219         purchaseOrderDocument.setItems(items);
220 
221         // Copy capital asset information that is directly off the document.
222         purchaseOrderDocument.setCapitalAssetSystemTypeCode(requisitionDocument.getCapitalAssetSystemTypeCode());
223         purchaseOrderDocument.setCapitalAssetSystemStateCode(requisitionDocument.getCapitalAssetSystemStateCode());
224         for (CapitalAssetSystem capitalAssetSystem : requisitionDocument.getPurchasingCapitalAssetSystems()) {
225             purchaseOrderDocument.getPurchasingCapitalAssetSystems().add(new PurchaseOrderCapitalAssetSystem(capitalAssetSystem));
226         }
227 
228         purchaseOrderDocument.fixItemReferences();
229     }
230 
231     /**
232      * This method is overriden to populate bib info in  Purchase Order Document
233      *
234      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#prepareForSave(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.rice.krad.rule.event.KualiDocumentEvent)
235      */
236     @Override
237     public void prepareForSave(PurchaseOrderDocument purchaseOrderDocument, KualiDocumentEvent event) {
238         LOG.debug("Inside prepareForSave of OlePurchaseOrderDocumentHelperServiceImpl");
239         WorkflowDocument workFlowDocument = purchaseOrderDocument.getDocumentHeader().getWorkflowDocument();
240         String documentType = workFlowDocument.getDocumentTypeName();
241 
242         try {
243             FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
244             BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
245             String titleId = null;
246             int itemCount = 0;
247             List<OlePurchaseOrderItem> items = new ArrayList<OlePurchaseOrderItem>();
248             items = purchaseOrderDocument.getItems();
249             List<String> itemTitleIdsList = new ArrayList<String>();
250             for (OlePurchaseOrderItem itemTitleId : items) {
251                 if (null != itemTitleId.getItemTitleId()) {
252                     itemTitleIdsList.add(itemTitleId.getItemTitleId());
253                 }
254             }
255             // List<WorkBibDocument> workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
256             Iterator iterator = items.iterator();
257             HashMap dataMap = new HashMap();
258             while (iterator.hasNext()) {
259                 Object object = iterator.next();
260                 if (object instanceof OlePurchaseOrderItem) {
261                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
262                     // Added for jira OLE-2811 starts
263                     List<OLERequestorPatronDocument> olePatronDocumentList = new ArrayList<OLERequestorPatronDocument>();
264                     HashMap<String, List<OLERequestorPatronDocument>> patronListMap = new HashMap<String, List<OLERequestorPatronDocument>>();
265 
266                     if (getOlePatronDocumentList().getPatronListMap() != null) {
267                         if (!getOlePatronDocumentList().getPatronListMap().containsKey(singleItem.getDocumentNumber())) {
268                             olePatronDocumentList = getOleSelectDocumentService().getPatronDocumentListFromWebService();
269                             patronListMap.put(singleItem.getDocumentNumber(), olePatronDocumentList);
270                             getOlePatronDocumentList().setPatronListMap(patronListMap);
271                         } else {
272                             olePatronDocumentList = getOlePatronDocumentList().getPatronListMap().get(
273                                     singleItem.getDocumentNumber());
274                         }
275                     } else {
276                         olePatronDocumentList = getOleSelectDocumentService().getPatronDocumentListFromWebService();
277                         patronListMap.put(singleItem.getDocumentNumber(), olePatronDocumentList);
278                         getOlePatronDocumentList().setPatronListMap(patronListMap);
279                     }
280                     String patronFirstName = getOleSelectDocumentService().getPatronName(olePatronDocumentList,
281                             singleItem.getRequestorId());
282                     if (patronFirstName != null) {
283                         singleItem.setRequestorFirstName(patronFirstName);
284                     }
285                     // Added for jira OLE-2811 ends
286 
287 
288                     if ((!StringUtils.isEmpty(singleItem.getInternalRequestorId()) || !StringUtils.isEmpty(singleItem
289                             .getRequestorId())) && singleItem.getRequestorTypeId() == null) {
290                         KualiInteger staffRequestorTypeId = getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_STAFF);
291                         singleItem.setRequestorTypeId(staffRequestorTypeId.intValue());
292                     }
293 
294                 }
295             }
296         } catch (Exception e) {
297             LOG.error("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
298             throw new RuntimeException(e);
299         }
300         if (event instanceof org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent &&
301                 purchaseOrderDocument.getRequisitionIdentifier() == null) {
302             try {
303                 UserSession uss = GlobalVariables.getUserSession();
304                 //TODO: need to configure a user/role
305                 GlobalVariables.setUserSession(new UserSession("ole-khuntley"));
306                 RequisitionDocument rdoc = SpringContext.getBean(org.kuali.ole.module.purap.document.service.RequisitionService.class)
307                         .generateRequisitionFromPurchaseOrder(purchaseOrderDocument);
308                 if (LOG.isDebugEnabled()) {
309                     LOG.debug("Requisition Document Status Code---->" + rdoc.getApplicationDocumentStatus());
310                 }
311                 rdoc.setRequisitionSourceCode("STAN");
312                 List ss = new ArrayList();
313                 ss.addAll(purchaseOrderDocument.getAdHocRoutePersons());
314                 ss.addAll(purchaseOrderDocument.getAdHocRouteWorkgroups());
315 
316                 SpringContext.getBean(org.kuali.rice.krad.service.DocumentService.class).blanketApproveDocument(rdoc, "Automatic Approval From PO", ss);
317                 GlobalVariables.setUserSession(uss);
318                 purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(rdoc.getPurapDocumentIdentifier());
319                 purchaseOrderDocument.setRequisitionIdentifier(rdoc.getPurapDocumentIdentifier());
320             } catch (WorkflowException e) {
321                 LOG.error("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
322                 throw new RuntimeException("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
323             }
324 
325             purchaseOrderDocument.setStatusCode(PurchaseOrderStatuses.APPDOC_IN_PROCESS);
326         }
327     }
328 
329     private KualiInteger getRequestorTypeId(String requestorType) {
330         KualiInteger requestorTypeId = null;
331         Map<String, Object> criteria = new HashMap<String, Object>();
332         criteria.put(OleSelectConstant.REQUESTOR_TYPE, requestorType);
333         org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
334         Collection<OleRequestorType> requestorTypeList = businessObjectService.findMatching(OleRequestorType.class, criteria);
335         requestorTypeId = new KualiInteger(requestorTypeList.iterator().next().getRequestorTypeId());
336         return requestorTypeId;
337     }
338 
339     protected void setRequestorNameOnItem(OlePurchasingItem singleItem) {
340         String requestorFirstName = singleItem.getRequestorFirstName();
341         if ((singleItem.getRequestorId() != null) || (singleItem.getInternalRequestorId() != null)) {
342             int requestorTypeId = singleItem.getRequestorTypeId();
343             Map requestorTypeIdMap = new HashMap();
344             requestorTypeIdMap.put("requestorTypeId", requestorTypeId);
345             org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
346             List<OleRequestorType> oleRequestorTypeList = (List) businessObjectService.findMatching(OleRequestorType.class, requestorTypeIdMap);
347             for (int i = 0; i < oleRequestorTypeList.size(); i++) {
348                 if (oleRequestorTypeList.get(i).getRequestorType().equalsIgnoreCase(OleSelectConstant.REQUESTOR_TYPE_STAFF)) {
349                     Person personImpl = SpringContext.getBean(PersonService.class).getPerson(singleItem.getInternalRequestorId());
350                     if (singleItem.getRequestorId() == null && singleItem.getInternalRequestorId() != null) {
351                         if (personImpl != null) {
352                             singleItem.setRequestorFirstName(personImpl.getName());
353                         }
354                     }
355                 }
356                 /*
357                  * else { Map requestorIdMap = new HashMap(); requestorIdMap.put("requestorId", singleItem.getRequestorId());
358                  * List<OleRequestor> oleRequestorList = (List) businessObjectService.findMatching(OleRequestor.class,
359                  * requestorIdMap); singleItem.setRequestorFirstName(oleRequestorList.get(0).getRequestorFirstName()); }
360                  */
361             }
362         }
363     }
364 
365 
366     /**
367      * This method is overriden to populate bib info in  Purchase Order Document
368      *
369      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#processAfterRetrieve(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
370      */
371     @Override
372     public void processAfterRetrieve(PurchaseOrderDocument purchaseOrderDocument) {
373 
374         // super.processAfterRetrieve();
375         LOG.debug("Inside processAfterRetrieve of OlePurchaseOrderDocumentHelperServiceImpl");
376         // Added for jira OLE-2811 starts
377         List<OLERequestorPatronDocument> olePatronDocumentList = new ArrayList<OLERequestorPatronDocument>();
378         HashMap<String, List<OLERequestorPatronDocument>> patronListMap = new HashMap<String, List<OLERequestorPatronDocument>>();
379 
380         if (getOlePatronDocumentList().getPatronListMap() != null) {
381             if (!getOlePatronDocumentList().getPatronListMap().containsKey(purchaseOrderDocument.getDocumentNumber())) {
382                 olePatronDocumentList = getOleSelectDocumentService().getPatronDocumentListFromWebService();
383                 patronListMap.put(purchaseOrderDocument.getDocumentNumber(), olePatronDocumentList);
384                 getOlePatronDocumentList().setPatronListMap(patronListMap);
385             } else {
386                 olePatronDocumentList = getOlePatronDocumentList().getPatronListMap().get(
387                         purchaseOrderDocument.getDocumentNumber());
388             }
389         } else {
390             olePatronDocumentList = getOleSelectDocumentService().getPatronDocumentListFromWebService();
391             patronListMap.put(purchaseOrderDocument.getDocumentNumber(), olePatronDocumentList);
392             getOlePatronDocumentList().setPatronListMap(patronListMap);
393         }
394         // Added for jira OLE-2811 ends
395 
396         try {
397 
398             Map purchaseOrderTypeIdMap = new HashMap();
399             purchaseOrderTypeIdMap.put("purchaseOrderTypeId", purchaseOrderDocument.getPurchaseOrderTypeId());
400             org.kuali.rice.krad.service.BusinessObjectService businessObject = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
401             List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List) businessObject.findMatching(PurchaseOrderType.class, purchaseOrderTypeIdMap);
402             if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
403                 PurchaseOrderType purchaseOrderTypeDoc = purchaseOrderTypeDocumentList.get(0);
404                 purchaseOrderDocument.setOrderType(purchaseOrderTypeDoc);
405             }
406 
407             BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
408             OleRequestorService oleRequestorService = SpringContext.getBean(OleRequestorService.class);
409             List<OleRequisitionItem> items = new ArrayList<OleRequisitionItem>();
410             items = purchaseOrderDocument.getItems();
411             Iterator iterator = items.iterator();
412             while (iterator.hasNext()) {
413                 Object object = iterator.next();
414                 if (object instanceof OleRequisitionItem) {
415                     OleRequisitionItem singleItem = (OleRequisitionItem) object;
416                     // Added for jira OLE-2811 starts
417                     String patronFirstName = getOleSelectDocumentService().getPatronName(olePatronDocumentList,
418                             singleItem.getRequestorId());
419                     if (patronFirstName != null) {
420                         singleItem.setRequestorFirstName(patronFirstName);
421                     }
422                     // Added for jira OLE-2811 ends
423 
424                     setRequestorNameOnItem(singleItem);
425 
426                     if (singleItem.getItemTitleId() != null) {
427                         BibInfoBean xmlBibInfoBean = new BibInfoBean();
428                         HashMap<String, String> dataMap = new HashMap<String, String>();
429                         dataMap.put(OleSelectConstant.TITLE_ID, singleItem.getItemTitleId());
430                         dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
431                         xmlBibInfoBean = docStore.getBibInfo(dataMap);
432                         singleItem.setBibInfoBean(xmlBibInfoBean);
433                         /*
434                          * if (singleItem.getRequestorId() != null) { OleRequestor oleRequestor =
435                          * oleRequestorService.getRequestorDetails(singleItem.getRequestorId().toString());
436                          * singleItem.setRequestorFirstName(oleRequestor.getRequestorName()); }
437                          */
438                     }
439 
440                 }
441             }
442 
443         } catch (Exception e) {
444             LOG.error("Error in OlePurchaseOrderDocument:processAfterRetrieve for OleRequisitionItem " + e.getMessage());
445             throw new RuntimeException(e);
446         }
447         try {
448             BibInfoWrapperService docStore = SpringContext.getBean(BibInfoWrapperServiceImpl.class);
449             FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
450             String titleId = null;
451             int itemCount = 0;
452             boolean isBibFileExist = false;
453             boolean isBibEdit = false;
454             List<OlePurchaseOrderItem> items = new ArrayList<OlePurchaseOrderItem>();
455             items = purchaseOrderDocument.getItems();
456             Iterator iterator = items.iterator();
457             while (iterator.hasNext()) {
458                 Object object = iterator.next();
459                 if (object instanceof OlePurchaseOrderItem) {
460                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
461                     List<String> itemTitleIdsList = new ArrayList<String>();
462                     List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
463                     if (null != singleItem.getItemTitleId()) {
464                         itemTitleIdsList.add(singleItem.getItemTitleId());
465                         workBibDocuments = getWorkBibDocuments(itemTitleIdsList);
466                     }
467                     // Added for jira OLE-2811 starts
468 
469                     String patronFirstName = getOleSelectDocumentService().getPatronName(olePatronDocumentList,
470                             singleItem.getRequestorId());
471                     if (patronFirstName != null) {
472                         singleItem.setRequestorFirstName(patronFirstName);
473                     }
474                     // Added for jira OLE-2811 ends
475 
476                     setRequestorNameOnItem(singleItem);
477 
478                     BibInfoBean xmlBibInfoBean = new BibInfoBean();
479                     HashMap<String, String> dataMap = new HashMap<String, String>();
480 
481                     if (singleItem.getItemTypeCode().equals(OleSelectConstant.ITEM_TYPE_CODE_ITEM)) {
482                         String fileName = purchaseOrderDocument.getDocumentNumber() + "_" + itemCount;
483                         dataMap.put(OleSelectConstant.FILEPATH, getMarcXMLFileDirLocation());
484                         dataMap.put(OleSelectConstant.FILENAME, fileName);
485                         if (fileProcessingService.isCreateFileExist(dataMap)) {
486                             isBibFileExist = true;
487                         }
488                         if (isBibFileExist) {
489                             if (xmlBibInfoBean.getDocStoreOperation() == null) {
490                                 xmlBibInfoBean.setDocStoreOperation(OleSelectConstant.DOCSTORE_OPERATION_STAFF);
491                             }
492                             titleId = docStore.getTitleIdByMarcXMLFileProcessing(xmlBibInfoBean, dataMap);
493                             if (titleId != null) {
494                                 singleItem.setItemTitleId(titleId);
495                             }
496                         }
497                         itemCount++;
498                     }
499 
500                     if (singleItem.getItemTitleId() != null) {
501                         HashMap<String, String> queryMap = new HashMap<String, String>();
502                         queryMap.put(OleSelectConstant.DocStoreDetails.ITEMLINKS_KEY, singleItem.getItemTitleId());
503                         List<DocInfoBean> docStoreResult = docStore.searchBibInfo(queryMap);
504                         Iterator bibIdIterator = docStoreResult.iterator();
505                         if (bibIdIterator.hasNext()) {
506                             DocInfoBean docInfoBean = (DocInfoBean) bibIdIterator.next();
507                             singleItem.setBibUUID(docInfoBean.getUniqueId());
508                         }
509                         String itemDescription;
510                         dataMap.put(OleSelectConstant.TITLE_ID, singleItem.getItemTitleId());
511                         dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
512                         xmlBibInfoBean = docStore.getBibInfo(dataMap);
513                         singleItem.setBibInfoBean(xmlBibInfoBean);
514                         itemDescription = (singleItem.getBibInfoBean().getTitle() != null ? singleItem.getBibInfoBean().getTitle() : "") + (singleItem.getBibInfoBean().getAuthor() != null ? "," + singleItem.getBibInfoBean().getAuthor() : "") + (singleItem.getBibInfoBean().getPublisher() != null ? "," + singleItem.getBibInfoBean().getPublisher() : "") + (singleItem.getBibInfoBean().getIsbn() != null ? "," + singleItem.getBibInfoBean().getIsbn() : "");
515                         singleItem.setItemDescription(itemDescription);
516 
517                     }
518                     // Added for Jira OLE-1900 Starts
519 
520                     if (null != singleItem.getItemTitleId() && workBibDocuments.size() > 0) {
521                         if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
522                                 || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
523                             for (WorkBibDocument workBibDocument : workBibDocuments) {
524                                 List<OleCopies> copies = setCopiesToLineItem(singleItem, workBibDocument);
525                                 singleItem.setItemTypeDescription(workBibDocument.getInstanceDocument()
526                                         .getItemDocumentList().get(0).getItemType());
527                                 singleItem.setCopies(copies);
528                             }
529                         }
530                     }
531 
532                     // Added for Jira OLE-1900 Ends
533                 }
534             }
535         } catch (Exception e) {
536             LOG.error("Error in OlePurchaseOrderDocument:processAfterRetrieve for OlePurchaseOrderItem " + e.getMessage());
537             throw new RuntimeException(e);
538         }
539 
540     }
541 
542     // Added for Jira OLE-1900 Starts
543 
544     /**
545      * This method will set copies into list of copies for LineItem.
546      *
547      * @param singleItem
548      * @param workBibDocument
549      * @return
550      */
551     public List<OleCopies> setCopiesToLineItem(OlePurchaseOrderItem singleItem, WorkBibDocument workBibDocument) {
552         List<WorkInstanceDocument> instanceDocuments = workBibDocument.getWorkInstanceDocumentList();
553         List<OleCopies> copies = new ArrayList<OleCopies>();
554         for (WorkInstanceDocument workInstanceDocument : instanceDocuments) {
555             List<WorkItemDocument> itemDocuments = workInstanceDocument.getItemDocumentList();
556             StringBuffer enumeration = new StringBuffer();
557             for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
558                 if (itemDocs + 1 == itemDocuments.size()) {
559                     enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
560                 } else {
561                     enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ";");
562                 }
563 
564             }
565             int startingCopy = 0;
566             if (singleItem.getItemNoOfParts().intValue() != 0 && null != enumeration) {
567                 String enumerationSplit = enumeration.substring(1, 2);
568                 boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
569                 if (isint) {
570                     startingCopy = Integer.parseInt(enumerationSplit);
571                 }
572             }
573             if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
574                     || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
575                 int noOfCopies = workInstanceDocument.getItemDocumentList().size()
576                         / singleItem.getItemNoOfParts().intValue();
577                 OleRequisitionCopies copy = new OleRequisitionCopies();
578                 copy.setParts(singleItem.getItemNoOfParts());
579                 copy.setLocationCopies(workInstanceDocument.getHoldingsDocument().getLocationName());
580                 copy.setItemCopies(new KualiDecimal(noOfCopies));
581                 copy.setPartEnumeration(enumeration.toString());
582                 copy.setStartingCopyNumber(new KualiInteger(startingCopy));
583                 copies.add(copy);
584             }
585         }
586         return copies;
587     }
588 
589     public boolean checkIsEnumerationSplitIsIntegerOrNot(String enumerationSplit) {
590         try {
591             int startingCopy = Integer.parseInt(enumerationSplit);
592         } catch (NumberFormatException e) {
593             return false;
594         }
595         return true;
596     }
597 
598     /**
599      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
600      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
601      *
602      * @param instanceIdsList
603      * @return List<WorkBibDocument>
604      */
605     private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
606         List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
607         for (String instanceId : instanceIdsList) {
608             LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
609             instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
610             instanceIdMapList.add(instanceIdMap);
611         }
612 
613         QueryService queryService = QueryServiceImpl.getInstance();
614         List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
615         try {
616             workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
617         } catch (Exception ex) {
618             // TODO Auto-generated catch block
619             ex.printStackTrace();
620         }
621         return workBibDocuments;
622     }
623 
624     // Added for Jira OLE-1900 Ends
625 
626     @Override
627     public void setBibInfoBean(BibInfoBean bibInfoBean, OlePurchaseOrderItem singleItem) {
628         bibInfoBean.setTitle(singleItem.getItemTitle());
629         bibInfoBean.setAuthor(singleItem.getItemAuthor());
630         bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
631     }
632 
633     @Override
634     public void setBibInfoBean(BibInfoBean bibInfoBean, OleRequisitionItem singleItem) {
635         bibInfoBean.setTitle(singleItem.getBibInfoBean().getTitle());
636         bibInfoBean.setAuthor(singleItem.getBibInfoBean().getAuthor());
637         bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
638     }
639 
640     /**
641      * This method returns if Purchase Order Document created is in Final Status
642      *
643      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#getIsFinalReqs(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
644      */
645     @Override
646     public boolean getIsFinalReqs(PurchaseOrderDocument purchaseOrderDocument) {
647         LOG.debug("Inside getIsFinalReqs of OlePurchaseOrderDocumentHelperServiceImpl");
648         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isFinal()) {
649             return true;
650         }
651         return false;
652     }
653 
654 
655     @Override
656     public boolean getIsSplitPO(PurchaseOrderDocument purchaseOrderDocument) {
657         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
658         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_SPLIT) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
659             return true;
660         }
661         return false;
662     }
663 
664     @Override
665     public boolean getIsReOpenPO(PurchaseOrderDocument purchaseOrderDocument) {
666         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
667         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_REOPEN) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
668             return true;
669         }
670         return false;
671     }
672 
673     /**
674      * This method is used to get the bibedtior creat url from propertie file
675      *
676      * @return Bibeditor creat url string
677      */
678     @Override
679     public String getBibeditorCreateURL() {
680         String bibeditorCreateURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
681         return bibeditorCreateURL;
682     }
683 
684     @Override
685     public String getBibSearchURL() {
686         String bibSearchURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
687         return bibSearchURL;
688     }
689 
690     /**
691      * This method is used to get the bibedtior edit url from propertie file
692      *
693      * @return Bibeditor edit url string
694      */
695     @Override
696     public String getBibeditorEditURL() {
697         String bibeditorEditURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
698         return bibeditorEditURL;
699     }
700 
701     /**
702      * This method is used to get the bibedtior view url from propertie file
703      *
704      * @return Bibeditor view url string
705      */
706     @Override
707     public String getBibeditorViewURL() {
708         String bibeditorViewURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
709         return bibeditorViewURL;
710     }
711 
712     /**
713      * This method is used to get the Instanceeditor url from propertie file
714      *
715      * @return Instanceeditor url string
716      */
717     @Override
718     public String getInstanceEditorURL() {
719         String instanceEditorURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
720                 OLEConstants.INSTANCEEDITOR_URL_KEY);
721         return instanceEditorURL;
722     }
723 
724     /**
725      * This method is used to get the directory path where the marc xml files need to be created
726      *
727      * @return Directory path string
728      */
729     @Override
730     public String getMarcXMLFileDirLocation() throws Exception {
731         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
732         String externaleDirectory = fileProcessingService.getMarcXMLFileDirLocation();
733         return externaleDirectory;
734     }
735 
736 
737     @Override
738     public List getItemsActiveOnly(PurchaseOrderDocument purchaseOrderDocument) {
739         List returnList = new ArrayList();
740         for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
741             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
742             if (item.isItemActiveIndicator()) {
743                 returnList.add(item);
744             }
745         }
746         return returnList;
747     }
748 
749     /**
750      * Gets the active items in this Purchase Order, and sets up the alternate amount for GL entry creation.
751      *
752      * @return the list of all active items in this Purchase Order.
753      */
754     @Override
755     public List getItemsActiveOnlySetupAlternateAmount(PurchaseOrderDocument purchaseOrderDocument) {
756         List returnList = new ArrayList();
757         for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
758             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
759             if (item.isItemActiveIndicator()) {
760                 for (Object element : item.getSourceAccountingLines()) {
761                     PurchaseOrderAccount account = (PurchaseOrderAccount) element;
762                     account.setAlternateAmountForGLEntryCreation(account.getItemAccountOutstandingEncumbranceAmount());
763                 }
764                 returnList.add(item);
765             }
766         }
767         return returnList;
768     }
769 
770     @Override
771     public boolean getAdditionalChargesExist(PurchaseOrderDocument purchaseOrderDocument) {
772         List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
773         for (OlePurchaseOrderItem item : items) {
774             if ((item != null) &&
775                     (item.getItemType() != null) &&
776                     (item.getItemType().isAdditionalChargeIndicator()) &&
777                     (item.getExtendedPrice() != null) &&
778                     (!KualiDecimal.ZERO.equals(item.getExtendedPrice()))) {
779                 return true;
780             }
781         }
782         return false;
783     }
784 }