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.common.client.DocstoreClientLocator;
20  import org.kuali.ole.docstore.common.document.*;
21  import org.kuali.ole.DocumentUniqueIDPrefix;
22  import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
23  import org.kuali.ole.docstore.common.document.content.instance.xstream.InstanceOlemlRecordProcessor;
24  import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
25  import org.kuali.ole.integration.purap.CapitalAssetSystem;
26  import org.kuali.ole.module.purap.PurapConstants;
27  import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
28  import org.kuali.ole.module.purap.businessobject.*;
29  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
30  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
31  import org.kuali.ole.module.purap.document.RequisitionDocument;
32  import org.kuali.ole.module.purap.document.service.OlePurapService;
33  import org.kuali.ole.select.OleSelectConstant;
34  import org.kuali.ole.select.OleSelectNotificationConstant;
35  import org.kuali.ole.select.businessobject.*;
36  import org.kuali.ole.select.document.OlePurchaseOrderDocument;
37  import org.kuali.ole.select.document.OleRequisitionDocument;
38  import org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService;
39  import org.kuali.ole.select.document.service.OleRequestorService;
40  import org.kuali.ole.select.document.service.OleSelectDocumentService;
41  import org.kuali.ole.select.service.BibInfoWrapperService;
42  import org.kuali.ole.select.service.FileProcessingService;
43  import org.kuali.ole.select.service.OleUrlResolver;
44  import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
45  import org.kuali.ole.sys.OLEConstants;
46  import org.kuali.ole.sys.context.SpringContext;
47  import org.kuali.rice.core.api.config.property.ConfigurationService;
48  import org.kuali.rice.core.api.datetime.DateTimeService;
49  import org.kuali.rice.core.api.util.type.KualiDecimal;
50  import org.kuali.rice.core.api.util.type.KualiInteger;
51  import org.kuali.rice.kew.api.WorkflowDocument;
52  import org.kuali.rice.kew.api.exception.WorkflowException;
53  import org.kuali.rice.kim.api.identity.Person;
54  import org.kuali.rice.kim.api.identity.PersonService;
55  import org.kuali.rice.krad.UserSession;
56  import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent;
57  import org.kuali.rice.krad.service.KRADServiceLocator;
58  import org.kuali.rice.krad.util.GlobalVariables;
59  import java.math.BigDecimal;
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 ItemOlemlRecordProcessor itemOlemlRecordProcessor;
69      private HoldingOlemlRecordProcessor holdingOlemlRecordProcessor;
70      private InstanceOlemlRecordProcessor instanceOlemlRecordProcessor;
71      private transient OleUrlResolver oleUrlResolver;
72      private static transient OlePatronRecordHandler olePatronRecordHandler;
73      private static transient OlePatronDocumentList olePatronDocumentList;
74      private static transient OleSelectDocumentService oleSelectDocumentService;
75      private static transient OlePurapService olePurapService;
76      private DocstoreClientLocator docstoreClientLocator;
77      protected ConfigurationService kualiConfigurationService;
78  
79      public DocstoreClientLocator getDocstoreClientLocator() {
80          if (docstoreClientLocator == null) {
81              docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
82          }
83          return docstoreClientLocator;
84      }
85      public static OleSelectDocumentService getOleSelectDocumentService() {
86          if (oleSelectDocumentService == null) {
87              oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
88          }
89          return oleSelectDocumentService;
90      }
91  
92      public static void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
93          OlePurchaseOrderDocumentHelperServiceImpl.oleSelectDocumentService = oleSelectDocumentService;
94      }
95  
96      public static OlePatronDocumentList getOlePatronDocumentList() {
97          if (olePatronDocumentList == null) {
98              olePatronDocumentList = SpringContext.getBean(OlePatronDocumentList.class);
99          }
100         return olePatronDocumentList;
101     }
102 
103     public static void setOlePatronDocumentList(OlePatronDocumentList olePatronDocumentList) {
104         OlePurchaseOrderDocumentHelperServiceImpl.olePatronDocumentList = olePatronDocumentList;
105     }
106 
107 
108     public OlePatronRecordHandler getOlePatronRecordHandler() {
109         if (null == olePatronRecordHandler) {
110             olePatronRecordHandler = new OlePatronRecordHandler();
111         }
112         return olePatronRecordHandler;
113     }
114 
115     public void setOlePatronRecordHandler(OlePatronRecordHandler olePatronRecordHandler) {
116         this.olePatronRecordHandler = olePatronRecordHandler;
117     }
118 
119     public static OlePurapService getOlePurapService() {
120         if (olePurapService == null) {
121             olePurapService = SpringContext.getBean(OlePurapService.class);
122         }
123         return olePurapService;
124     }
125 
126     public static void setOlePurapService(OlePurapService olePurapService) {
127         OlePurchaseOrderDocumentHelperServiceImpl.olePurapService = olePurapService;
128     }
129 
130 
131     /**
132      * This method is overridden to populate newly added ole fields from requisition into Purchase Order Document.
133      *
134      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#populatePurchaseOrderFromRequisition(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.ole.module.purap.document.RequisitionDocument)
135      */
136     @Override
137     public void populatePurchaseOrderFromRequisition(PurchaseOrderDocument purchaseOrderDoc, RequisitionDocument requisitionDoc) {
138         LOG.debug("Inside populatePurchaseOrderFromRequisition of OlePurchaseOrderDocumentHelperServiceImpl");
139         OlePurchaseOrderDocument purchaseOrderDocument = (OlePurchaseOrderDocument) purchaseOrderDoc;
140         OleRequisitionDocument requisitionDocument = (OleRequisitionDocument) requisitionDoc;
141         purchaseOrderDocument.setPurchaseOrderCreateTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
142         purchaseOrderDocument.getDocumentHeader().setOrganizationDocumentNumber(requisitionDocument.getDocumentHeader().getOrganizationDocumentNumber());
143         purchaseOrderDocument.getDocumentHeader().setDocumentDescription(requisitionDocument.getDocumentHeader().getDocumentDescription());
144         purchaseOrderDocument.getDocumentHeader().setExplanation(requisitionDocument.getDocumentHeader().getExplanation());
145         purchaseOrderDocument.setBillingName(requisitionDocument.getBillingName());
146         purchaseOrderDocument.setBillingLine1Address(requisitionDocument.getBillingLine1Address());
147         purchaseOrderDocument.setBillingLine2Address(requisitionDocument.getBillingLine2Address());
148         purchaseOrderDocument.setBillingCityName(requisitionDocument.getBillingCityName());
149         purchaseOrderDocument.setBillingStateCode(requisitionDocument.getBillingStateCode());
150         purchaseOrderDocument.setBillingPostalCode(requisitionDocument.getBillingPostalCode());
151         purchaseOrderDocument.setBillingCountryCode(requisitionDocument.getBillingCountryCode());
152         purchaseOrderDocument.setBillingPhoneNumber(requisitionDocument.getBillingPhoneNumber());
153 
154         purchaseOrderDocument.setReceivingName(requisitionDocument.getReceivingName());
155         purchaseOrderDocument.setReceivingCityName(requisitionDocument.getReceivingCityName());
156         purchaseOrderDocument.setReceivingLine1Address(requisitionDocument.getReceivingLine1Address());
157         purchaseOrderDocument.setReceivingLine2Address(requisitionDocument.getReceivingLine2Address());
158         purchaseOrderDocument.setReceivingStateCode(requisitionDocument.getReceivingStateCode());
159         purchaseOrderDocument.setReceivingPostalCode(requisitionDocument.getReceivingPostalCode());
160         purchaseOrderDocument.setReceivingCountryCode(requisitionDocument.getReceivingCountryCode());
161         purchaseOrderDocument.setAddressToVendorIndicator(requisitionDocument.getAddressToVendorIndicator());
162 
163         purchaseOrderDocument.setDeliveryBuildingCode(requisitionDocument.getDeliveryBuildingCode());
164         purchaseOrderDocument.setDeliveryBuildingRoomNumber(requisitionDocument.getDeliveryBuildingRoomNumber());
165         purchaseOrderDocument.setDeliveryBuildingName(requisitionDocument.getDeliveryBuildingName());
166         purchaseOrderDocument.setDeliveryCampusCode(requisitionDocument.getDeliveryCampusCode());
167         purchaseOrderDocument.setDeliveryCityName(requisitionDocument.getDeliveryCityName());
168         purchaseOrderDocument.setDeliveryCountryCode(requisitionDocument.getDeliveryCountryCode());
169         purchaseOrderDocument.setDeliveryInstructionText(requisitionDocument.getDeliveryInstructionText());
170         purchaseOrderDocument.setDeliveryBuildingLine1Address(requisitionDocument.getDeliveryBuildingLine1Address());
171         purchaseOrderDocument.setDeliveryBuildingLine2Address(requisitionDocument.getDeliveryBuildingLine2Address());
172         purchaseOrderDocument.setDeliveryPostalCode(requisitionDocument.getDeliveryPostalCode());
173         purchaseOrderDocument.setDeliveryRequiredDate(requisitionDocument.getDeliveryRequiredDate());
174         purchaseOrderDocument.setDeliveryRequiredDateReasonCode(requisitionDocument.getDeliveryRequiredDateReasonCode());
175         purchaseOrderDocument.setDeliveryStateCode(requisitionDocument.getDeliveryStateCode());
176         purchaseOrderDocument.setDeliveryToEmailAddress(requisitionDocument.getDeliveryToEmailAddress());
177         purchaseOrderDocument.setDeliveryToName(requisitionDocument.getDeliveryToName());
178         purchaseOrderDocument.setDeliveryToPhoneNumber(requisitionDocument.getDeliveryToPhoneNumber());
179         purchaseOrderDocument.setDeliveryBuildingOtherIndicator(requisitionDocument.isDeliveryBuildingOtherIndicator());
180         purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
181         purchaseOrderDocument.setPurchaseOrderBeginDate(requisitionDocument.getPurchaseOrderBeginDate());
182         purchaseOrderDocument.setPurchaseOrderCostSourceCode(requisitionDocument.getPurchaseOrderCostSourceCode());
183         purchaseOrderDocument.setPostingYear(requisitionDocument.getPostingYear());
184         purchaseOrderDocument.setPurchaseOrderEndDate(requisitionDocument.getPurchaseOrderEndDate());
185         purchaseOrderDocument.setChartOfAccountsCode(requisitionDocument.getChartOfAccountsCode());
186         purchaseOrderDocument.setDocumentFundingSourceCode(requisitionDocument.getDocumentFundingSourceCode());
187         purchaseOrderDocument.setInstitutionContactEmailAddress(requisitionDocument.getInstitutionContactEmailAddress());
188         purchaseOrderDocument.setInstitutionContactName(requisitionDocument.getInstitutionContactName());
189         purchaseOrderDocument.setInstitutionContactPhoneNumber(requisitionDocument.getInstitutionContactPhoneNumber());
190         purchaseOrderDocument.setNonInstitutionFundAccountNumber(requisitionDocument.getNonInstitutionFundAccountNumber());
191         purchaseOrderDocument.setNonInstitutionFundChartOfAccountsCode(requisitionDocument.getNonInstitutionFundChartOfAccountsCode());
192         purchaseOrderDocument.setNonInstitutionFundOrgChartOfAccountsCode(requisitionDocument.getNonInstitutionFundOrgChartOfAccountsCode());
193         purchaseOrderDocument.setNonInstitutionFundOrganizationCode(requisitionDocument.getNonInstitutionFundOrganizationCode());
194         purchaseOrderDocument.setOrganizationCode(requisitionDocument.getOrganizationCode());
195         purchaseOrderDocument.setRecurringPaymentTypeCode(requisitionDocument.getRecurringPaymentTypeCode());
196         purchaseOrderDocument.setRequestorPersonEmailAddress(requisitionDocument.getRequestorPersonEmailAddress());
197         purchaseOrderDocument.setRequestorPersonName(requisitionDocument.getRequestorPersonName());
198         purchaseOrderDocument.setRequestorPersonPhoneNumber(requisitionDocument.getRequestorPersonPhoneNumber());
199         purchaseOrderDocument.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
200         purchaseOrderDocument.setPurchaseOrderTotalLimit(requisitionDocument.getPurchaseOrderTotalLimit());
201         purchaseOrderDocument.setPurchaseOrderTransmissionMethodCode(requisitionDocument.getPurchaseOrderTransmissionMethodCode());
202         purchaseOrderDocument.setUseTaxIndicator(requisitionDocument.isUseTaxIndicator());
203         purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
204         purchaseOrderDocument.setVendorCityName(requisitionDocument.getVendorCityName());
205         purchaseOrderDocument.setVendorContractGeneratedIdentifier(requisitionDocument.getVendorContractGeneratedIdentifier());
206         purchaseOrderDocument.setVendorCountryCode(requisitionDocument.getVendorCountryCode());
207         purchaseOrderDocument.setVendorCustomerNumber(requisitionDocument.getVendorCustomerNumber());
208         purchaseOrderDocument.setVendorAttentionName(requisitionDocument.getVendorAttentionName());
209         purchaseOrderDocument.setVendorDetailAssignedIdentifier(requisitionDocument.getVendorDetailAssignedIdentifier());
210         purchaseOrderDocument.setVendorFaxNumber(requisitionDocument.getVendorFaxNumber());
211         purchaseOrderDocument.setVendorHeaderGeneratedIdentifier(requisitionDocument.getVendorHeaderGeneratedIdentifier());
212         purchaseOrderDocument.setVendorLine1Address(requisitionDocument.getVendorLine1Address());
213         purchaseOrderDocument.setVendorLine2Address(requisitionDocument.getVendorLine2Address());
214         purchaseOrderDocument.setVendorAddressInternationalProvinceName(requisitionDocument.getVendorAddressInternationalProvinceName());
215         purchaseOrderDocument.setVendorName(requisitionDocument.getVendorName());
216         purchaseOrderDocument.setVendorNoteText(requisitionDocument.getVendorNoteText());
217         purchaseOrderDocument.setVendorPhoneNumber(requisitionDocument.getVendorPhoneNumber());
218         purchaseOrderDocument.setVendorPostalCode(requisitionDocument.getVendorPostalCode());
219         purchaseOrderDocument.setVendorStateCode(requisitionDocument.getVendorStateCode());
220         purchaseOrderDocument.setVendorRestrictedIndicator(requisitionDocument.getVendorRestrictedIndicator());
221         purchaseOrderDocument.setVendorPoNumber(requisitionDocument.getVendorPoNumber());
222         purchaseOrderDocument.setExternalOrganizationB2bSupplierIdentifier(requisitionDocument.getExternalOrganizationB2bSupplierIdentifier());
223         purchaseOrderDocument.setRequisitionSourceCode(requisitionDocument.getRequisitionSourceCode());
224         purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
225         purchaseOrderDocument.setReceivingDocumentRequiredIndicator(requisitionDocument.isReceivingDocumentRequiredIndicator());
226         purchaseOrderDocument.setPaymentRequestPositiveApprovalIndicator(requisitionDocument.isPaymentRequestPositiveApprovalIndicator());
227         /*purchaseOrderDocument.setLicensingRequirementIndicator(requisitionDocument.isLicensingRequirementIndicator());*/
228        /* purchaseOrderDocument.setLicensingRequirementCode(requisitionDocument.getLicensingRequirementCode());*/
229 
230         purchaseOrderDocument.setStatusCode(PurapConstants.PurchaseOrderStatuses.APPDOC_IN_PROCESS);
231 
232         // Copy items from requisition (which will copy the item's accounts and capital assets)
233         List<OlePurchaseOrderItem> items = new ArrayList();
234         for (PurApItem reqItem : ((PurchasingAccountsPayableDocument) requisitionDocument).getItems()) {
235             RequisitionCapitalAssetItem reqCamsItem = (RequisitionCapitalAssetItem) requisitionDocument.getPurchasingCapitalAssetItemByItemIdentifier(reqItem.getItemIdentifier().intValue());
236             items.add(new OlePurchaseOrderItem((OleRequisitionItem) reqItem, purchaseOrderDocument, reqCamsItem));
237         }
238         purchaseOrderDocument.setItems(items);
239 
240         // Copy capital asset information that is directly off the document.
241         purchaseOrderDocument.setCapitalAssetSystemTypeCode(requisitionDocument.getCapitalAssetSystemTypeCode());
242         purchaseOrderDocument.setCapitalAssetSystemStateCode(requisitionDocument.getCapitalAssetSystemStateCode());
243         for (CapitalAssetSystem capitalAssetSystem : requisitionDocument.getPurchasingCapitalAssetSystems()) {
244             purchaseOrderDocument.getPurchasingCapitalAssetSystems().add(new PurchaseOrderCapitalAssetSystem(capitalAssetSystem));
245         }
246 
247         purchaseOrderDocument.fixItemReferences();
248     }
249 
250     /**
251      * This method is overriden to populate bib info in  Purchase Order Document
252      *
253      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#prepareForSave(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.rice.krad.rule.event.KualiDocumentEvent)
254      */
255     @Override
256     public void prepareForSave(PurchaseOrderDocument purchaseOrderDocument, KualiDocumentEvent event) {
257         LOG.debug("Inside prepareForSave of OlePurchaseOrderDocumentHelperServiceImpl");
258         WorkflowDocument workFlowDocument = purchaseOrderDocument.getDocumentHeader().getWorkflowDocument();
259         try {
260             List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
261             Iterator iterator = items.iterator();
262             while (iterator.hasNext()) {
263                 Object object = iterator.next();
264                 if (object instanceof OlePurchaseOrderItem) {
265                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
266                     if ((!StringUtils.isEmpty(singleItem.getInternalRequestorId()) || !StringUtils.isEmpty(singleItem
267                             .getRequestorId())) && singleItem.getRequestorTypeId() == null) {
268                         KualiInteger staffRequestorTypeId = getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_STAFF);
269                         singleItem.setRequestorTypeId(staffRequestorTypeId.intValue());
270                     }
271                 }
272             }
273         } catch (Exception e) {
274             LOG.error("Exception in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
275             throw new RuntimeException(e);
276         }
277         if (event instanceof org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent &&
278                 purchaseOrderDocument.getRequisitionIdentifier() == null) {
279             try {
280                 UserSession userSession = GlobalVariables.getUserSession();
281                 //TODO: need to configure a user/role
282                 //GlobalVariables.setUserSession(new UserSession("ole-khuntley"));
283                 String user = null;
284                 if (GlobalVariables.getUserSession() == null) {
285                     kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
286                     user = kualiConfigurationService.getPropertyValueAsString(OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR);
287                     GlobalVariables.setUserSession(new UserSession(user));
288                 }
289                 RequisitionDocument rdoc = SpringContext.getBean(org.kuali.ole.module.purap.document.service.RequisitionService.class)
290                         .generateRequisitionFromPurchaseOrder(purchaseOrderDocument);
291                 if (LOG.isDebugEnabled()) {
292                     LOG.debug("Requisition Document Status Code---->" + rdoc.getApplicationDocumentStatus());
293                 }
294                 rdoc.setRequisitionSourceCode("STAN");
295                 List adhocRouteRecipientList = new ArrayList();
296                 adhocRouteRecipientList.addAll(purchaseOrderDocument.getAdHocRoutePersons());
297                 adhocRouteRecipientList.addAll(purchaseOrderDocument.getAdHocRouteWorkgroups());
298                 SpringContext.getBean(org.kuali.rice.krad.service.DocumentService.class).blanketApproveDocument(rdoc, "Automatic Approval From PO", adhocRouteRecipientList);
299                 GlobalVariables.setUserSession(userSession);
300                 purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(rdoc.getPurapDocumentIdentifier());
301                 purchaseOrderDocument.setRequisitionIdentifier(rdoc.getPurapDocumentIdentifier());
302             } catch (WorkflowException e) {
303                 LOG.error("Exception in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
304                 throw new RuntimeException("Error in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
305             }
306 
307             purchaseOrderDocument.setStatusCode(PurchaseOrderStatuses.APPDOC_IN_PROCESS);
308         }
309     }
310 
311     private KualiInteger getRequestorTypeId(String requestorType) {
312         KualiInteger requestorTypeId = null;
313         Map<String, Object> criteria = new HashMap<String, Object>();
314         criteria.put(OleSelectConstant.REQUESTOR_TYPE, requestorType);
315         org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
316         Collection<OleRequestorType> requestorTypeList = businessObjectService.findMatching(OleRequestorType.class, criteria);
317         requestorTypeId = new KualiInteger(requestorTypeList.iterator().next().getRequestorTypeId());
318         return requestorTypeId;
319     }
320 
321     protected void setRequestorNameOnItem(OlePurchasingItem singleItem) {
322         String requestorFirstName = singleItem.getRequestorFirstName();
323         if ((singleItem.getRequestorId() != null) || (singleItem.getInternalRequestorId() != null)) {
324             int requestorTypeId = singleItem.getRequestorTypeId();
325             Map requestorTypeIdMap = new HashMap();
326             requestorTypeIdMap.put("requestorTypeId", requestorTypeId);
327             org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
328             List<OleRequestorType> oleRequestorTypeList = (List) businessObjectService.findMatching(OleRequestorType.class, requestorTypeIdMap);
329             for (int i = 0; i < oleRequestorTypeList.size(); i++) {
330                 if (oleRequestorTypeList.get(i).getRequestorType().equalsIgnoreCase(OleSelectConstant.REQUESTOR_TYPE_STAFF)) {
331                     Person personImpl = SpringContext.getBean(PersonService.class).getPerson(singleItem.getInternalRequestorId());
332                     if (singleItem.getRequestorId() == null && singleItem.getInternalRequestorId() != null) {
333                         if (personImpl != null) {
334                             singleItem.setRequestorFirstName(personImpl.getName());
335                         }
336                     }
337                 }
338                 /*
339                  * else { Map requestorIdMap = new HashMap(); requestorIdMap.put("requestorId", singleItem.getRequestorId());
340                  * List<OleRequestor> oleRequestorList = (List) businessObjectService.findMatching(OleRequestor.class,
341                  * requestorIdMap); singleItem.setRequestorFirstName(oleRequestorList.get(0).getRequestorFirstName()); }
342                  */
343             }
344         }
345     }
346 
347 
348     /**
349      * This method is overriden to populate bib info in  Purchase Order Document
350      *
351      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#processAfterRetrieve(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
352      */
353     @Override
354     public void processAfterRetrieve(PurchaseOrderDocument purchaseOrderDocument) {
355 
356         // super.processAfterRetrieve();
357         LOG.debug("Inside processAfterRetrieve of OlePurchaseOrderDocumentHelperServiceImpl");
358         try {
359             PurchaseOrderType purchaseOrderTypeDoc = getOlePurapService().getPurchaseOrderType(purchaseOrderDocument.getPurchaseOrderTypeId());
360             if(purchaseOrderTypeDoc != null){
361                 purchaseOrderDocument.setOrderType(purchaseOrderTypeDoc);
362             }
363             List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
364             Iterator iterator = items.iterator();
365             while (iterator.hasNext()) {
366                 Object object = iterator.next();
367                 if (object instanceof OlePurchaseOrderItem) {
368                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
369                     setItemDetailWhileProcessAfterRetrive(singleItem);
370                 }
371             }
372         } catch (Exception e) {
373             LOG.error("Exception in OlePurchaseOrderDocument:processAfterRetrieve for OlePurchaseOrderItem " + e.getMessage());
374             throw new RuntimeException(e);
375         }
376 
377     }
378 
379     /**
380      * This method is used to set the item detail while processafterretrive method is executed
381      * @param olePurchaseOrderItem
382      */
383     private void setItemDetailWhileProcessAfterRetrive(OlePurchaseOrderItem olePurchaseOrderItem)throws Exception{
384         if(olePurchaseOrderItem.getRequestorId()!=null){
385             olePurchaseOrderItem.setRequestorFirstName(getOlePurapService().getPatronName(olePurchaseOrderItem.getRequestorId()));
386         }
387         // Added for jira OLE-2811 ends
388         setRequestorNameOnItem(olePurchaseOrderItem);
389         HashMap<String, String> dataMap = new HashMap<String, String>();
390         if(olePurchaseOrderItem.getItemUnitPrice()!=null){
391             olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
392         }
393         if (olePurchaseOrderItem.getItemTitleId() != null) {
394             Bib bib = new BibMarc();
395             if (olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != "") {
396                 bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(olePurchaseOrderItem.getItemTitleId());
397             }
398             olePurchaseOrderItem.setBibUUID(bib.getId());
399             dataMap.put(OleSelectConstant.TITLE_ID, olePurchaseOrderItem.getItemTitleId());
400             dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
401             olePurchaseOrderItem.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(olePurchaseOrderItem.getItemTitleId()));
402             olePurchaseOrderItem.setItemDescription(getOlePurapService().getItemDescription(bib));
403         }
404         BibTree bibTree = new BibTree();
405         if(olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != ""){
406             bibTree = getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(olePurchaseOrderItem.getItemTitleId());
407         }
408         if (null != olePurchaseOrderItem.getItemTitleId()) {
409             if (olePurchaseOrderItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
410                     || olePurchaseOrderItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
411                 List<OleCopies> copies = setCopiesToLineItem(olePurchaseOrderItem, bibTree);
412                 olePurchaseOrderItem.setItemTypeDescription(bibTree.getHoldingsTrees().get(bibTree.getHoldingsTrees().size() - 1)
413                         .getItems().get(0).getItemType());
414                 olePurchaseOrderItem.setCopies(copies);
415             }
416         }
417         if (olePurchaseOrderItem.getItemQuantity() != null && olePurchaseOrderItem.getItemNoOfParts() != null && !olePurchaseOrderItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
418                 && !olePurchaseOrderItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))&&olePurchaseOrderItem.getCopyList().size()>0) {
419             olePurchaseOrderItem.setSingleCopyNumber(olePurchaseOrderItem.getCopyList().get(0).getCopyNumber());
420         }
421     }
422 
423     public List<OleCopies> setCopiesToLineItem(OlePurchaseOrderItem singleItem, BibTree bibTree) {
424         List<HoldingsTree> instanceDocuments = bibTree.getHoldingsTrees();
425         List<OleCopies> copies = new ArrayList<OleCopies>();
426         for (HoldingsTree holdingsTree : instanceDocuments) {
427             List<Item> itemDocuments = holdingsTree.getItems();
428             StringBuffer enumeration = new StringBuffer();
429             for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
430                 if (itemDocs + 1 == itemDocuments.size()) {
431                     enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
432                 } else {
433                     enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ";");
434                 }
435 
436             }
437             int startingCopy = 0;
438             if (singleItem.getItemNoOfParts().intValue() != 0 && null != enumeration) {
439                 String enumerationSplit = enumeration.substring(1, 2);
440                 boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
441                 if (isint) {
442                     startingCopy = Integer.parseInt(enumerationSplit);
443                 }
444             }
445             if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
446                     || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
447                 int noOfCopies = holdingsTree.getItems().size()
448                         / singleItem.getItemNoOfParts().intValue();
449                 OleRequisitionCopies copy = new OleRequisitionCopies();
450                 copy.setParts(singleItem.getItemNoOfParts());
451                 copy.setLocationCopies(holdingsTree.getHoldings().getLocationName());
452                 copy.setItemCopies(new KualiDecimal(noOfCopies));
453                 copy.setPartEnumeration(enumeration.toString());
454                 copy.setStartingCopyNumber(new KualiInteger(startingCopy));
455                 copies.add(copy);
456             }
457         }
458         return copies;
459     }
460 
461     public boolean checkIsEnumerationSplitIsIntegerOrNot(String enumerationSplit) {
462         try {
463             int startingCopy = Integer.parseInt(enumerationSplit);
464         } catch (NumberFormatException e) {
465             return false;
466         }
467         return true;
468     }
469 
470     /**
471      * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
472      * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
473      *
474      * @param instanceIdsList
475      * @return List<WorkBibDocument>
476      */
477 //    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
478 //        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
479 //        for (String instanceId : instanceIdsList) {
480 //            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
481 //            instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
482 //            instanceIdMapList.add(instanceIdMap);
483 //        }
484 //
485 //        QueryService queryService = QueryServiceImpl.getInstance();
486 //        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
487 //        try {
488 //            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
489 //        } catch (Exception ex) {
490 //            // TODO Auto-generated catch block
491 //            ex.printStackTrace();
492 //        }
493 //        return workBibDocuments;
494 //    }
495 
496     // Added for Jira OLE-1900 Ends
497 
498     @Override
499     public void setBibInfoBean(BibInfoBean bibInfoBean, OlePurchaseOrderItem singleItem) {
500         bibInfoBean.setTitle(singleItem.getItemTitle());
501         bibInfoBean.setAuthor(singleItem.getItemAuthor());
502         bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
503     }
504 
505     @Override
506     public void setBibInfoBean(BibInfoBean bibInfoBean, OleRequisitionItem singleItem) {
507         bibInfoBean.setTitle(singleItem.getBibInfoBean().getTitle());
508         bibInfoBean.setAuthor(singleItem.getBibInfoBean().getAuthor());
509         bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
510     }
511 
512     /**
513      * This method returns if Purchase Order Document created is in Final Status
514      *
515      * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#getIsFinalReqs(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
516      */
517     @Override
518     public boolean getIsFinalReqs(PurchaseOrderDocument purchaseOrderDocument) {
519         LOG.debug("Inside getIsFinalReqs of OlePurchaseOrderDocumentHelperServiceImpl");
520         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isFinal()) {
521             return true;
522         }
523         return false;
524     }
525 
526 
527     @Override
528     public boolean getIsSplitPO(PurchaseOrderDocument purchaseOrderDocument) {
529         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
530         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_SPLIT) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
531             return true;
532         }
533         return false;
534     }
535 
536     @Override
537     public boolean getIsReOpenPO(PurchaseOrderDocument purchaseOrderDocument) {
538         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
539         if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_REOPEN) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
540             return true;
541         }
542         return false;
543     }
544 
545     /**
546      * This method is used to get the bibedtior creat url from propertie file
547      *
548      * @return Bibeditor creat url string
549      */
550     @Override
551     public String getBibeditorCreateURL() {
552         String bibeditorCreateURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
553         return bibeditorCreateURL;
554     }
555 
556     @Override
557     public String getBibSearchURL() {
558         String bibSearchURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
559         return bibSearchURL;
560     }
561 
562     /**
563      * This method is used to get the bibedtior edit url from propertie file
564      *
565      * @return Bibeditor edit url string
566      */
567     @Override
568     public String getBibeditorEditURL() {
569         String bibeditorEditURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
570         return bibeditorEditURL;
571     }
572 
573     /**
574      * This method is used to get the dublinedtior edit url from propertie file
575      *
576      * @return Dublineditor edit url string
577      */
578     public String getDublinEditorEditURL() {
579         String dublinEditorEditURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DUBLINEDITOR_URL_KEY);
580         return dublinEditorEditURL;
581     }
582     /**
583      * This method is used to get the bibedtior view url from propertie file
584      *
585      * @return Bibeditor view url string
586      */
587     @Override
588     public String getBibeditorViewURL() {
589         String bibeditorViewURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
590         return bibeditorViewURL;
591     }
592     /**
593      * This method is used to get the dublinedtior view url from propertie file
594      *
595      * @return dublineditor view url string
596      */
597     public String getDublinEditorViewURL() {
598         String dublinEditorViewURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSTORE_VIEW_URL_KEY);
599         return dublinEditorViewURL;
600     }
601     /**
602      * This method is used to get the Instanceeditor url from propertie file
603      *
604      * @return Instanceeditor url string
605      */
606     @Override
607     public String getInstanceEditorURL() {
608         String instanceEditorURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
609                 OLEConstants.INSTANCEEDITOR_URL_KEY);
610         return instanceEditorURL;
611     }
612 
613     /**
614      * This method is used to get the directory path where the marc xml files need to be created
615      *
616      * @return Directory path string
617      */
618     @Override
619     public String getMarcXMLFileDirLocation() throws Exception {
620         FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
621         String externaleDirectory = fileProcessingService.getMarcXMLFileDirLocation();
622         return externaleDirectory;
623     }
624 
625 
626     @Override
627     public List getItemsActiveOnly(PurchaseOrderDocument purchaseOrderDocument) {
628         List returnList = new ArrayList();
629         for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
630             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
631             if (item.isItemActiveIndicator()) {
632                 returnList.add(item);
633             }
634         }
635         return returnList;
636     }
637 
638     /**
639      * Gets the active items in this Purchase Order, and sets up the alternate amount for GL entry creation.
640      *
641      * @return the list of all active items in this Purchase Order.
642      */
643     @Override
644     public List getItemsActiveOnlySetupAlternateAmount(PurchaseOrderDocument purchaseOrderDocument) {
645         List returnList = new ArrayList();
646         for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
647             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
648             if (item.isItemActiveIndicator()) {
649                 for (Object element : item.getSourceAccountingLines()) {
650                     PurchaseOrderAccount account = (PurchaseOrderAccount) element;
651                     account.setAlternateAmountForGLEntryCreation(account.getItemAccountOutstandingEncumbranceAmount());
652                 }
653                 returnList.add(item);
654             }
655         }
656         return returnList;
657     }
658 
659     @Override
660     public boolean getAdditionalChargesExist(PurchaseOrderDocument purchaseOrderDocument) {
661         List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
662         for (OlePurchaseOrderItem item : items) {
663             if ((item != null) &&
664                     (item.getItemType() != null) &&
665                     (item.getItemType().isAdditionalChargeIndicator()) &&
666                     (item.getExtendedPrice() != null) &&
667                     (!KualiDecimal.ZERO.equals(item.getExtendedPrice()))) {
668                 return true;
669             }
670         }
671         return false;
672     }
673 }