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;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.ole.DocumentUniqueIDPrefix;
20  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
21  import org.kuali.ole.docstore.common.document.Bib;
22  import org.kuali.ole.gl.service.SufficientFundsService;
23  import org.kuali.ole.integration.purap.CapitalAssetSystem;
24  import org.kuali.ole.module.purap.PurapConstants;
25  import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
26  import org.kuali.ole.module.purap.PurapConstants.RequisitionSources;
27  import org.kuali.ole.module.purap.PurapParameterConstants;
28  import org.kuali.ole.module.purap.PurapWorkflowConstants;
29  import org.kuali.ole.module.purap.businessobject.*;
30  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
31  import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
32  import org.kuali.ole.module.purap.document.RequisitionDocument;
33  import org.kuali.ole.module.purap.document.service.OlePurapService;
34  import org.kuali.ole.module.purap.document.service.RequisitionService;
35  import org.kuali.ole.module.purap.service.PurapAccountingService;
36  import org.kuali.ole.select.OleSelectConstant;
37  import org.kuali.ole.select.businessobject.*;
38  import org.kuali.ole.select.document.service.OleCopyHelperService;
39  import org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService;
40  import org.kuali.ole.select.service.BibInfoService;
41  import org.kuali.ole.select.service.BibInfoWrapperService;
42  import org.kuali.ole.select.service.FileProcessingService;
43  import org.kuali.ole.select.service.impl.BibInfoServiceImpl;
44  import org.kuali.ole.sys.OLEConstants;
45  import org.kuali.ole.sys.businessobject.GeneralLedgerPendingEntry;
46  import org.kuali.ole.sys.businessobject.SourceAccountingLine;
47  import org.kuali.ole.sys.businessobject.SufficientFundsItem;
48  import org.kuali.ole.sys.context.SpringContext;
49  import org.kuali.ole.sys.service.GeneralLedgerPendingEntryService;
50  import org.kuali.ole.sys.service.UniversityDateService;
51  import org.kuali.ole.vnd.businessobject.VendorAlias;
52  import org.kuali.rice.core.api.config.property.ConfigurationService;
53  import org.kuali.rice.core.api.datetime.DateTimeService;
54  import org.kuali.rice.core.api.util.type.KualiDecimal;
55  import org.kuali.rice.core.api.util.type.KualiInteger;
56  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
57  import org.kuali.rice.kew.api.KewApiConstants;
58  import org.kuali.rice.kew.api.KewApiServiceLocator;
59  import org.kuali.rice.kew.api.doctype.DocumentType;
60  import org.kuali.rice.kew.api.exception.WorkflowException;
61  import org.kuali.rice.kew.framework.postprocessor.DocumentRouteLevelChange;
62  import org.kuali.rice.krad.UserSession;
63  import org.kuali.rice.krad.bo.Note;
64  import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent;
65  import org.kuali.rice.krad.service.BusinessObjectService;
66  import org.kuali.rice.krad.service.DocumentService;
67  import org.kuali.rice.krad.util.GlobalVariables;
68  import org.kuali.rice.krad.util.KRADConstants;
69  import java.math.BigDecimal;
70  import java.util.*;
71  
72  public class OlePurchaseOrderDocument extends PurchaseOrderDocument {
73      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderDocument.class);
74      /*    public void populatePurchaseOrderFromRequisition(RequisitionDocument requisitionDocument) {
75              super.populatePurchaseOrderFromRequisition(requisitionDocument);
76          }*/
77      private String vendorPoNumber;
78  
79      private static transient ConfigurationService kualiConfigurationService;
80      private static transient BibInfoWrapperService bibInfoWrapperService;
81      private static transient DateTimeService dateTimeService;
82      private static transient FileProcessingService fileProcessingService;
83      private static transient BusinessObjectService businessObjectService;
84      private static transient ParameterService parameterService;
85      private static transient RequisitionService RequisitionService;
86      private static transient OlePurchaseOrderDocumentHelperService olePurchaseOrderDocumentHelperService;
87      private static transient DocumentService documentService;
88      protected List<SourceAccountingLine> accountsForRouting = new ArrayList<SourceAccountingLine>();
89      private static transient BibInfoService bibInfoService;
90      private static transient OlePatronRecordHandler olePatronRecordHandler;
91      private static transient OlePurapService olePurapService;
92      private static transient OleCopyHelperService oleCopyHelperService;
93      protected List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = new ArrayList<OlePurchaseOrderLineForInvoice>();
94      protected List<OlePurchaseOrderTotal> purchaseOrderTotalList = new ArrayList<OlePurchaseOrderTotal>();
95      private Date poEndDate;
96      private boolean closePO;
97      private String poNotes;
98      private String poItemLink;
99      private DocstoreClientLocator docstoreClientLocator;
100     protected static DocumentService getDocumentService() {
101         if (documentService == null) {
102             documentService = SpringContext.getBean(DocumentService.class);
103         }
104         return documentService;
105     }
106 
107     public DocstoreClientLocator getDocstoreClientLocator() {
108         if (null == docstoreClientLocator) {
109             return  SpringContext.getBean(DocstoreClientLocator.class);
110         }
111         return docstoreClientLocator;
112     }
113 
114     public static OlePurapService getOlePurapService() {
115         if (olePurapService == null) {
116             olePurapService = SpringContext.getBean(OlePurapService.class);
117         }
118         return olePurapService;
119     }
120 
121     public static OlePurchaseOrderDocumentHelperService getOlePurchaseOrderDocumentHelperService() {
122         if (olePurchaseOrderDocumentHelperService == null) {
123             olePurchaseOrderDocumentHelperService = SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class);
124         }
125         return olePurchaseOrderDocumentHelperService;
126     }
127 
128     public static void setOlePurchaseOrderDocumentHelperService(OlePurchaseOrderDocumentHelperService olePurchaseOrderDocumentHelperService) {
129         OlePurchaseOrderDocument.olePurchaseOrderDocumentHelperService = olePurchaseOrderDocumentHelperService;
130     }
131 
132     @Override
133     public ParameterService getParameterService() {
134         if (parameterService == null) {
135             parameterService = SpringContext.getBean(ParameterService.class);
136         }
137         return parameterService;
138     }
139 
140     public void setParameterService(ParameterService parameterService) {
141         this.parameterService = parameterService;
142     }
143 
144     public static RequisitionService getRequisitionService() {
145         if (RequisitionService == null) {
146             RequisitionService = SpringContext.getBean(RequisitionService.class);
147         }
148         return RequisitionService;
149     }
150 
151     public static void setRequisitionService(RequisitionService RequisitionService) {
152         OlePurchaseOrderDocument.RequisitionService = RequisitionService;
153     }
154 
155     public static ConfigurationService getConfigurationService() {
156         if (kualiConfigurationService == null) {
157             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
158         }
159         return kualiConfigurationService;
160     }
161 
162     public static void setConfigurationService(ConfigurationService kualiConfigurationService) {
163         OlePurchaseOrderDocument.kualiConfigurationService = kualiConfigurationService;
164     }
165 
166     public static BibInfoWrapperService getBibInfoWrapperService() {
167         if (bibInfoWrapperService == null) {
168             bibInfoWrapperService = SpringContext.getBean(BibInfoWrapperService.class);
169         }
170         return bibInfoWrapperService;
171     }
172 
173     public static void setBibInfoWrapperService(BibInfoWrapperService bibInfoWrapperService) {
174         OlePurchaseOrderDocument.bibInfoWrapperService = bibInfoWrapperService;
175     }
176 
177     public static FileProcessingService getFileProcessingService() {
178         if (fileProcessingService == null) {
179             fileProcessingService = SpringContext.getBean(FileProcessingService.class);
180         }
181         return fileProcessingService;
182     }
183 
184     public static void setFileProcessingService(FileProcessingService fileProcessingService) {
185         OlePurchaseOrderDocument.fileProcessingService = fileProcessingService;
186     }
187 
188     public static DateTimeService getDateTimeService() {
189         if (dateTimeService == null) {
190             dateTimeService = SpringContext.getBean(DateTimeService.class);
191         }
192         return dateTimeService;
193     }
194 
195     public static void setDateTimeService(DateTimeService dateTimeService) {
196         OlePurchaseOrderDocument.dateTimeService = dateTimeService;
197     }
198 
199     @Override
200     public BusinessObjectService getBusinessObjectService() {
201         if (businessObjectService == null) {
202             businessObjectService = SpringContext.getBean(BusinessObjectService.class);
203         }
204         return businessObjectService;
205     }
206 
207     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
208         this.businessObjectService = businessObjectService;
209     }
210 
211     public static BibInfoService getBibInfoService() {
212         if (bibInfoService == null) {
213             bibInfoService = SpringContext.getBean(BibInfoServiceImpl.class);
214         }
215         return bibInfoService;
216     }
217 
218     public OlePatronRecordHandler getOlePatronRecordHandler() {
219         if (null == olePatronRecordHandler) {
220             olePatronRecordHandler = new OlePatronRecordHandler();
221         }
222         return olePatronRecordHandler;
223     }
224 
225     public void setOlePatronRecordHandler(OlePatronRecordHandler olePatronRecordHandler) {
226         this.olePatronRecordHandler = olePatronRecordHandler;
227     }
228 
229     public static OleCopyHelperService getOleCopyHelperService() {
230         if(oleCopyHelperService  == null){
231             oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
232         }
233         return oleCopyHelperService;
234     }
235 
236     public static void setOleCopyHelperService(OleCopyHelperService oleCopyHelperService) {
237         OlePurchaseOrderDocument.oleCopyHelperService = oleCopyHelperService;
238     }
239 
240     @Override
241     public List<OlePurchaseOrderItem> getItemsActiveOnly() {
242         List<OlePurchaseOrderItem> returnList = new ArrayList<OlePurchaseOrderItem>();
243         for (Iterator iter = getItems().iterator(); iter.hasNext(); ) {
244             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
245             if (item.isItemActiveIndicator()) {
246                 returnList.add(item);
247             }
248         }
249         return returnList;
250     }
251 
252     /**
253      * Gets the active items in this Purchase Order, and sets up the alternate amount for GL entry creation.
254      *
255      * @return the list of all active items in this Purchase Order.
256      */
257     public List changeItemsActiveOnlySetupAlternateAmount() {
258         List returnList = new ArrayList();
259         for (Iterator iter = getItems().iterator(); iter.hasNext(); ) {
260             OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
261             if (item.isItemActiveIndicator()) {
262                 for (Object element : item.getSourceAccountingLines()) {
263                     PurchaseOrderAccount account = (PurchaseOrderAccount) element;
264                     account.setAlternateAmountForGLEntryCreation(account.getItemAccountOutstandingEncumbranceAmount());
265                 }
266                 returnList.add(item);
267             }
268         }
269         return returnList;
270     }
271 
272     @Override
273     public boolean getAdditionalChargesExist() {
274         List<OlePurchaseOrderItem> items = this.getItems();
275         for (OlePurchaseOrderItem item : items) {
276             if ((item != null) &&
277                     (item.getItemType() != null) &&
278                     (item.getItemType().isAdditionalChargeIndicator()) &&
279                     (item.getExtendedPrice() != null) &&
280                     (!KualiDecimal.ZERO.equals(item.getExtendedPrice()))) {
281                 return true;
282             }
283         }
284         return false;
285     }
286 
287     @Override
288     public void populatePurchaseOrderFromRequisition(RequisitionDocument requisitionDoc) {
289         OleRequisitionDocument requisitionDocument = (OleRequisitionDocument) requisitionDoc;
290         this.setPurchaseOrderCreateTimestamp(getDateTimeService().getCurrentTimestamp());
291         this.getDocumentHeader().setOrganizationDocumentNumber(requisitionDocument.getDocumentHeader().getOrganizationDocumentNumber());
292         this.getDocumentHeader().setDocumentDescription(requisitionDocument.getDocumentHeader().getDocumentDescription());
293         this.getDocumentHeader().setExplanation(requisitionDocument.getDocumentHeader().getExplanation());
294         this.setBillingName(requisitionDocument.getBillingName());
295         this.setBillingLine1Address(requisitionDocument.getBillingLine1Address());
296         this.setBillingLine2Address(requisitionDocument.getBillingLine2Address());
297         this.setBillingCityName(requisitionDocument.getBillingCityName());
298         this.setBillingStateCode(requisitionDocument.getBillingStateCode());
299         this.setBillingPostalCode(requisitionDocument.getBillingPostalCode());
300         this.setBillingCountryCode(requisitionDocument.getBillingCountryCode());
301         this.setBillingPhoneNumber(requisitionDocument.getBillingPhoneNumber());
302         this.setVendorAliasName(requisitionDocument.getVendorAliasName());
303         this.setReceivingName(requisitionDocument.getReceivingName());
304         this.setReceivingCityName(requisitionDocument.getReceivingCityName());
305         this.setReceivingLine1Address(requisitionDocument.getReceivingLine1Address());
306         this.setReceivingLine2Address(requisitionDocument.getReceivingLine2Address());
307         this.setReceivingStateCode(requisitionDocument.getReceivingStateCode());
308         this.setReceivingPostalCode(requisitionDocument.getReceivingPostalCode());
309         this.setReceivingCountryCode(requisitionDocument.getReceivingCountryCode());
310         this.setAddressToVendorIndicator(requisitionDocument.getAddressToVendorIndicator());
311         this.setVendorPoNumber(requisitionDocument.getVendorPoNumber());
312         this.setDeliveryBuildingCode(requisitionDocument.getDeliveryBuildingCode());
313         this.setDeliveryBuildingRoomNumber(requisitionDocument.getDeliveryBuildingRoomNumber());
314         this.setDeliveryBuildingName(requisitionDocument.getDeliveryBuildingName());
315         this.setDeliveryCampusCode(requisitionDocument.getDeliveryCampusCode());
316         this.setDeliveryCityName(requisitionDocument.getDeliveryCityName());
317         this.setDeliveryCountryCode(requisitionDocument.getDeliveryCountryCode());
318         this.setDeliveryInstructionText(requisitionDocument.getDeliveryInstructionText());
319         this.setDeliveryBuildingLine1Address(requisitionDocument.getDeliveryBuildingLine1Address());
320         this.setDeliveryBuildingLine2Address(requisitionDocument.getDeliveryBuildingLine2Address());
321         this.setDeliveryPostalCode(requisitionDocument.getDeliveryPostalCode());
322         this.setDeliveryRequiredDate(requisitionDocument.getDeliveryRequiredDate());
323         this.setDeliveryRequiredDateReasonCode(requisitionDocument.getDeliveryRequiredDateReasonCode());
324         this.setDeliveryStateCode(requisitionDocument.getDeliveryStateCode());
325         this.setDeliveryToEmailAddress(requisitionDocument.getDeliveryToEmailAddress());
326         this.setDeliveryToName(requisitionDocument.getDeliveryToName());
327         this.setDeliveryToPhoneNumber(requisitionDocument.getDeliveryToPhoneNumber());
328         this.setDeliveryBuildingOtherIndicator(requisitionDocument.isDeliveryBuildingOtherIndicator());
329         //this.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
330         this.setPurchaseOrderBeginDate(requisitionDocument.getPurchaseOrderBeginDate());
331         this.setPurchaseOrderCostSourceCode(requisitionDocument.getPurchaseOrderCostSourceCode());
332         this.setPostingYear(requisitionDocument.getPostingYear());
333         this.setPurchaseOrderEndDate(requisitionDocument.getPurchaseOrderEndDate());
334         this.setChartOfAccountsCode(requisitionDocument.getChartOfAccountsCode());
335         this.setDocumentFundingSourceCode(requisitionDocument.getDocumentFundingSourceCode());
336         this.setInstitutionContactEmailAddress(requisitionDocument.getInstitutionContactEmailAddress());
337         this.setInstitutionContactName(requisitionDocument.getInstitutionContactName());
338         this.setInstitutionContactPhoneNumber(requisitionDocument.getInstitutionContactPhoneNumber());
339         this.setNonInstitutionFundAccountNumber(requisitionDocument.getNonInstitutionFundAccountNumber());
340         this.setNonInstitutionFundChartOfAccountsCode(requisitionDocument.getNonInstitutionFundChartOfAccountsCode());
341         this.setNonInstitutionFundOrgChartOfAccountsCode(requisitionDocument.getNonInstitutionFundOrgChartOfAccountsCode());
342         this.setNonInstitutionFundOrganizationCode(requisitionDocument.getNonInstitutionFundOrganizationCode());
343         this.setOrganizationCode(requisitionDocument.getOrganizationCode());
344         this.setRecurringPaymentTypeCode(requisitionDocument.getRecurringPaymentTypeCode());
345         this.setRequestorPersonEmailAddress(requisitionDocument.getRequestorPersonEmailAddress());
346         this.setRequestorPersonName(requisitionDocument.getRequestorPersonName());
347         this.setRequestorPersonPhoneNumber(requisitionDocument.getRequestorPersonPhoneNumber());
348         this.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
349         this.setPurchaseOrderTotalLimit(requisitionDocument.getPurchaseOrderTotalLimit());
350         this.setPurchaseOrderTransmissionMethodCode(requisitionDocument.getPurchaseOrderTransmissionMethodCode());
351         this.setUseTaxIndicator(requisitionDocument.isUseTaxIndicator());
352         this.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
353         this.setVendorCityName(requisitionDocument.getVendorCityName());
354         this.setVendorContractGeneratedIdentifier(requisitionDocument.getVendorContractGeneratedIdentifier());
355         this.setVendorCountryCode(requisitionDocument.getVendorCountryCode());
356         this.setVendorCustomerNumber(requisitionDocument.getVendorCustomerNumber());
357         this.setVendorAttentionName(requisitionDocument.getVendorAttentionName());
358         this.setVendorDetailAssignedIdentifier(requisitionDocument.getVendorDetailAssignedIdentifier());
359         this.setVendorFaxNumber(requisitionDocument.getVendorFaxNumber());
360         this.setVendorHeaderGeneratedIdentifier(requisitionDocument.getVendorHeaderGeneratedIdentifier());
361         this.setVendorLine1Address(requisitionDocument.getVendorLine1Address());
362         this.setVendorLine2Address(requisitionDocument.getVendorLine2Address());
363         this.setVendorAddressInternationalProvinceName(requisitionDocument.getVendorAddressInternationalProvinceName());
364         this.setVendorName(requisitionDocument.getVendorName());
365         this.setVendorNoteText(requisitionDocument.getVendorNoteText());
366         this.setVendorPhoneNumber(requisitionDocument.getVendorPhoneNumber());
367         this.setVendorPostalCode(requisitionDocument.getVendorPostalCode());
368         this.setVendorStateCode(requisitionDocument.getVendorStateCode());
369         this.setVendorRestrictedIndicator(requisitionDocument.getVendorRestrictedIndicator());
370 
371         this.setExternalOrganizationB2bSupplierIdentifier(requisitionDocument.getExternalOrganizationB2bSupplierIdentifier());
372         this.setRequisitionSourceCode(requisitionDocument.getRequisitionSourceCode());
373         this.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
374         this.setReceivingDocumentRequiredIndicator(requisitionDocument.isReceivingDocumentRequiredIndicator());
375         this.setPaymentRequestPositiveApprovalIndicator(requisitionDocument.isPaymentRequestPositiveApprovalIndicator());
376 
377         this.setStatusCode(PurapConstants.PurchaseOrderStatuses.APPDOC_IN_PROCESS);
378 
379         // Copy items from requisition (which will copy the item's accounts and capital assets)
380         List<OlePurchaseOrderItem> items = new ArrayList();
381         for (PurApItem reqItem : ((PurchasingAccountsPayableDocument) requisitionDocument).getItems()) {
382             RequisitionCapitalAssetItem reqCamsItem = (RequisitionCapitalAssetItem) requisitionDocument.getPurchasingCapitalAssetItemByItemIdentifier(reqItem.getItemIdentifier().intValue());
383             //items.add(new OlePurchaseOrderItem((OleRequisitionItem)reqItem, this, reqCamsItem));
384             items.add(new OlePurchaseOrderItem((OleRequisitionItem) reqItem, this, reqCamsItem));
385         }
386         this.setItems(items);
387 
388         // Copy capital asset information that is directly off the document.
389         this.setCapitalAssetSystemTypeCode(requisitionDocument.getCapitalAssetSystemTypeCode());
390         this.setCapitalAssetSystemStateCode(requisitionDocument.getCapitalAssetSystemStateCode());
391         for (CapitalAssetSystem capitalAssetSystem : requisitionDocument.getPurchasingCapitalAssetSystems()) {
392             this.getPurchasingCapitalAssetSystems().add(new PurchaseOrderCapitalAssetSystem(capitalAssetSystem));
393         }
394 
395         this.fixItemReferences();
396     }
397 
398     @Override
399     public void prepareForSave(KualiDocumentEvent event) {
400         try {
401             List<OlePurchaseOrderItem> items = this.getItems();
402             for (OlePurchaseOrderItem singleItem : items) {
403                 if (singleItem instanceof OlePurchaseOrderItem) {
404                     if(!this.getRequisitionSourceCode().equalsIgnoreCase(
405                             OleSelectConstant.REQUISITON_SRC_TYPE_DIRECTINPUT)){
406                         singleItem.setVendorItemPoNumber(this.getVendorPoNumber());
407                     }
408                     if (singleItem.getBibInfoBean() != null) {
409                         if (!StringUtils.isEmpty(singleItem.getInternalRequestorId()) && singleItem.getBibInfoBean().getRequestorType() == null) {
410                             singleItem.setRequestorTypeId(getOlePurapService().getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_STAFF));
411                         }
412                     }
413                 }
414             }
415             if (event instanceof org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent && this.getRequisitionIdentifier() == null) {
416                 routePO();
417             }
418         } catch (Exception e) {
419             LOG.error("Exception in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
420             throw new RuntimeException("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
421         }
422         super.prepareForSave(event);
423     }
424 
425     /**
426      *
427      */
428     private void routePO(){
429         String currentUser = GlobalVariables.getUserSession().getPrincipalName();
430         try {
431             UserSession userSession = GlobalVariables.getUserSession();
432             // TODO: need to configure a user/role
433             GlobalVariables.setUserSession(new UserSession(OLEConstants.SYSTEM_USER));
434             RequisitionDocument requisitionDocument = getRequisitionService().generateRequisitionFromPurchaseOrder(this);
435             // rdoc.setAccountsPayablePurchasingDocumentLinkIdentifier(this.getDocumentNumber());
436             if (LOG.isDebugEnabled()) {
437                 LOG.debug("Requisition Document Status Code---->" + requisitionDocument.getApplicationDocumentStatus());
438             }
439             requisitionDocument.setRequisitionSourceCode(OLEConstants.REQ_SRC_CD);
440             List adHocRouteRecipientList = new ArrayList();
441             adHocRouteRecipientList.addAll(this.getAdHocRoutePersons());
442             adHocRouteRecipientList.addAll(this.getAdHocRouteWorkgroups());
443 
444             getDocumentService().blanketApproveDocument(requisitionDocument, "Automatic Approval From PO", adHocRouteRecipientList);
445             GlobalVariables.setUserSession(userSession);
446             this.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getPurapDocumentIdentifier());
447             this.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
448         } catch (WorkflowException e) {
449             LOG.error("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
450             throw new RuntimeException("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
451         } finally {
452             GlobalVariables.setUserSession(new UserSession(currentUser));
453         }
454         this.setStatusCode(PurchaseOrderStatuses.APPDOC_IN_PROCESS);
455     }
456     @Override
457     public void processAfterRetrieve() {
458         try {
459             PurchaseOrderType purchaseOrderTypeDoc = getOlePurapService().getPurchaseOrderType(this.getPurchaseOrderTypeId());
460             if(purchaseOrderTypeDoc != null){
461                 this.setOrderType(purchaseOrderTypeDoc);
462             }
463             if (this.getVendorAliasName() == null) {
464                 populateVendorAliasName();
465             }
466             List<OlePurchaseOrderItem> items = this.getItems();
467             Iterator iterator = items.iterator();
468             while (iterator.hasNext()) {
469                 try{
470                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) iterator.next();
471                     // Added for jira OLE-2811 starts
472                     //Modified for jiar OLE-6032
473                     setItemDetailWhileProcessAfterRetrive(singleItem);
474                 }catch(Exception e){
475                     LOG.error("Exception in OlePurchaseOrderDocument:processAfterRetrieve --Exception while processing receiving purchasing record--->"+e);
476                     e.printStackTrace();
477                 }
478             }//End of Iteration of Purchase order while loop
479         } catch (Exception e) {
480             LOG.error("Error in OlePurchaseOrderDocument:processAfterRetrieve for OlePurchaseOrderItem " + e.getMessage());
481             throw new RuntimeException(e);
482         }
483     }
484 
485     /**
486      * This method is used to set the item detail while processafterretrive method is executed
487      * @param olePurchaseOrderItem
488      */
489     private void setItemDetailWhileProcessAfterRetrive(OlePurchaseOrderItem olePurchaseOrderItem)throws Exception{
490         if(olePurchaseOrderItem.getRequestorId()!=null){
491             olePurchaseOrderItem.setRequestorFirstName(getOlePurapService().getPatronName(olePurchaseOrderItem.getRequestorId()));
492         }
493         if(olePurchaseOrderItem.getItemUnitPrice()!=null){
494             olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
495         }
496         if (olePurchaseOrderItem.getItemTitleId() != null) {
497             olePurchaseOrderItem.setBibInfoBean(new BibInfoBean());
498             if (olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != "") {
499                 Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(olePurchaseOrderItem.getItemTitleId());
500                 olePurchaseOrderItem.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(olePurchaseOrderItem.getItemTitleId()));
501                 if (bib != null) {
502                     olePurchaseOrderItem.setItemDescription(getOlePurapService().getItemDescription(bib));
503                     //setItemDescription(olePurchaseOrderItem,bib);
504                     olePurchaseOrderItem.setBibUUID(bib.getId());
505                 }
506             }
507         }
508         if (olePurchaseOrderItem.getItemType() != null && olePurchaseOrderItem.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
509             populateCopiesSection(olePurchaseOrderItem);
510         }
511         if(olePurchaseOrderItem.getClaimDate()==null){
512             getOlePurapService().setClaimDateForPO(olePurchaseOrderItem,this.vendorDetail);
513         }
514         if(olePurchaseOrderItem.getCopyList().size() > 0) {
515             getOlePurapService().setInvoiceDocumentsForPO(olePurchaseOrderItem);
516         }
517     }
518 
519     /**
520      * This method is used to set the item description on item for the given Bib
521      * @param olePurchaseOrderItem
522      * @param newBib
523      */
524 /*    private void setItemDescription(OlePurchaseOrderItem olePurchaseOrderItem, Bib newBib){
525         LOG.debug("### Inside setItemDescription() of OleRequisitionDocument ###");
526         String itemDescription = ((newBib.getTitle() != null && !newBib.getTitle().isEmpty()) ? newBib.getTitle() + "," : "") + ((newBib.getAuthor() != null && !newBib.getAuthor().isEmpty()) ? newBib.getAuthor() + "," : "") + ((newBib.getPublisher() != null && !newBib.getPublisher().isEmpty()) ? newBib.getPublisher() + "," : "") + ((newBib.getIsbn() != null && !newBib.getIsbn().isEmpty()) ? newBib.getIsbn() + "," : "");
527         itemDescription = itemDescription.substring(0, itemDescription.lastIndexOf(","));
528         if(LOG.isDebugEnabled()){
529             LOG.debug("Item Description---------->"+itemDescription);
530         }
531         StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
532         itemDescription = stringEscapeUtils.unescapeHtml(itemDescription);
533         olePurchaseOrderItem.setItemDescription(itemDescription);
534     }*/
535 
536     /**
537      * This method is used to populated the copies section details
538      * @param singleItem
539      */
540     private void populateCopiesSection(OlePurchaseOrderItem singleItem) {
541         LOG.debug("### Inside populateCopiesSection of OlePurchaseOrderDocument ###");
542         if (singleItem.getCopies().size() > 0) {
543             List<OleCopy> copyList = getOleCopyHelperService().setCopyValuesForList(singleItem.getCopies(), singleItem.getItemTitleId(), null);
544             if (copyList.size() >= singleItem.getCopyList().size()) {
545                 int copyCount = 0;
546                 for (OleCopy oleCopy : singleItem.getCopyList()) {
547                     OleCopy copy = copyList.get(copyCount);
548                     oleCopy.setLocation(copy.getLocation());
549                     oleCopy.setEnumeration(copy.getEnumeration());
550                     oleCopy.setCopyNumber(copy.getCopyNumber());
551                     oleCopy.setPartNumber(copy.getPartNumber());
552                     copyCount++;
553                 }
554                 for(int i = copyCount ; i<copyList.size() ; i++){
555                     singleItem.getCopyList().add(copyList.get(copyCount));
556                     copyCount++;
557                 }
558             }
559         }
560         else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && !singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
561                 && !singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))&&singleItem.getCopyList().size()>0) {
562             singleItem.setSingleCopyNumber(singleItem.getCopyList().get(0).getCopyNumber());
563         }
564         else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
565                     || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1)))) {
566             singleItem.setCopies(getOleCopyHelperService().setCopiesToLineItem(singleItem.getCopyList(), singleItem.getItemNoOfParts(), singleItem.getItemTitleId()));
567         }
568         if(singleItem.getCopyList().size() > 0) {
569             getOlePurapService().setInvoiceDocumentsForPO(singleItem);
570         }
571     }
572 
573     /**
574      * Sets default values for APO.
575      */
576     @Override
577     public void setDefaultValuesForAPO() {
578         this.setPurchaseOrderAutomaticIndicator(Boolean.TRUE);
579         if (!RequisitionSources.B2B.equals(this.getRequisitionSourceCode())) {
580             String paramName = PurapParameterConstants.DEFAULT_B2B_VENDOR_CHOICE;
581             String paramValue = getParameterService().getParameterValueAsString(PurchaseOrderDocument.class, paramName);
582             this.setPurchaseOrderVendorChoiceCode(paramValue);
583         }
584     }
585 
586     @Override
587     public Class getItemClass() {
588         // TODO Auto-generated method stub
589         return OlePurchaseOrderItem.class;
590     }
591 
592 
593     public boolean getIsFinalReqs() {
594 
595         if (this.getDocumentHeader().getWorkflowDocument().isFinal()) {
596             return true;
597         }
598         return false;
599     }
600     /**
601      * This method is used to get the dublinedtior edit url from propertie file
602      *
603      * @return Dublineditor edit url string
604      */
605     public String getDublinEditorEditURL() {
606         return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorEditURL();
607     }
608 
609     /**
610      * This method is used to get the dublinedtior view url from propertie file
611      *
612      * @return dublineditor view url string
613      */
614     public String getDublinEditorViewURL() {
615         return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorViewURL();
616     }
617     /**
618 
619      /**
620      * This method is used to get the bibedtior creat url from propertie file
621      *
622      * @return Bibeditor creat url string
623      */
624     public String getBibeditorCreateURL() {
625         String bibeditorCreateURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
626         return bibeditorCreateURL;
627     }
628 
629     public String getBibSearchURL() {
630         String bibSearchURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
631         return bibSearchURL;
632     }
633 
634     /**
635      * This method is used to get the bibedtior edit url from propertie file
636      *
637      * @return Bibeditor edit url string
638      */
639     public String getBibeditorEditURL() {
640         String bibeditorEditURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
641         return bibeditorEditURL;
642     }
643 
644     /**
645      * This method is used to get the Instanceeditor url from propertie file
646      *
647      * @return Instanceeditor url string
648      */
649     public String getInstanceEditorURL() {
650         String instanceEditorURL = getConfigurationService().getPropertyValueAsString(
651                 OLEConstants.INSTANCEEDITOR_URL_KEY);
652         return instanceEditorURL;
653     }
654 
655     /**
656      * This method is used to get the bibedtior view url from propertie file
657      *
658      * @return Bibeditor view url string
659      */
660     public String getBibeditorViewURL() {
661         String bibeditorViewURL = getConfigurationService().getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
662         return bibeditorViewURL;
663     }
664 
665     /**
666      * This method is used to get the directory path where the marc xml files need to be created
667      *
668      * @return Directory path string
669      */
670     public String getMarcXMLFileDirLocation() throws Exception {
671         String externaleDirectory = getFileProcessingService().getMarcXMLFileDirLocation();
672         return externaleDirectory;
673     }
674 
675     public boolean getIsSplitPO() {
676         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocument");
677         return getOlePurchaseOrderDocumentHelperService().getIsSplitPO(this);
678     }
679 
680     public boolean getIsReOpenPO() {
681         LOG.debug("Inside getIsReOpenPO of OlePurchaseOrderDocument");
682         return getOlePurchaseOrderDocumentHelperService().getIsReOpenPO(this);
683     }
684 
685 
686     public String getVendorPoNumber() {
687         return vendorPoNumber;
688     }
689 
690     public void setVendorPoNumber(String vendorPoNumber) {
691         this.vendorPoNumber = vendorPoNumber;
692     }
693 
694 
695     /**
696      * This method is used to check the status of the document for displaying view and edit buttons in line item
697      *
698      * @return boolean
699      */
700     public boolean getIsSaved() {
701         if (this.getDocumentHeader().getWorkflowDocument().isSaved() || this.getDocumentHeader().getWorkflowDocument().isInitiated()) {
702             return true;
703         }
704         return false;
705     }
706 
707     /**
708      * Method overridden for JIRA OLE-2359 Fund Check
709      * Makes sure that accounts for routing has been generated, so that other information can be retrieved from that
710      */
711     @Override
712     protected void populateAccountsForRouting() {
713         List<SufficientFundsItem> fundsItems = new ArrayList<SufficientFundsItem>();
714         String documentId = this.getDocumentNumber();
715         try {
716             //  String nodeName = SpringContext.getBean(WorkflowDocumentService.class).getCurrentRouteLevelName(getFinancialSystemDocumentHeader().getWorkflowDocument());
717             String nodeName = getFinancialSystemDocumentHeader().getWorkflowDocument().getCurrentNodeNames().iterator()
718                     .next();
719             if (nodeName != null
720                     && (nodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || nodeName
721                     .equalsIgnoreCase(PurapWorkflowConstants.BUDGET_REVIEW_REQUIRED))) {
722                 if (SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().compareTo(getPostingYear()) >= 0) {
723                     List<GeneralLedgerPendingEntry> pendingEntries = getPendingLedgerEntriesForSufficientFundsChecking();
724                     for (GeneralLedgerPendingEntry glpe : pendingEntries) {
725                         glpe.getChartOfAccountsCode();
726                     }
727                     SpringContext.getBean(GeneralLedgerPendingEntryService.class).delete(getDocumentNumber());
728                     fundsItems = SpringContext.getBean(SufficientFundsService.class).checkSufficientFunds(pendingEntries);
729                     SpringContext.getBean(GeneralLedgerPendingEntryService.class).generateGeneralLedgerPendingEntries(this);
730                     SpringContext.getBean(BusinessObjectService.class).save(getGeneralLedgerPendingEntries());
731                 }
732                 SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(this);
733                 accountsForRouting = (SpringContext.getBean(PurapAccountingService.class).generateSummary(getItems()));
734                 List<String> fundsItemList = new ArrayList<String>();
735                 for (SufficientFundsItem fundsItem : fundsItems) {
736                     fundsItemList.add(fundsItem.getAccount().getChartOfAccountsCode());
737                 }
738                 for (Iterator accountsForRoutingIter = accountsForRouting.iterator(); accountsForRoutingIter.hasNext(); ) {
739                     if (!(fundsItemList.contains(((SourceAccountingLine) accountsForRoutingIter.next()).getChartOfAccountsCode()))) {
740                         accountsForRoutingIter.remove();
741                     }
742                 }
743                 setAccountsForRouting(accountsForRouting);
744                 // need to refresh to get the references for the searchable attributes (ie status) and for invoking route levels (ie account
745                 // objects) -hjs
746                 refreshNonUpdateableReferences();
747                 for (SourceAccountingLine sourceLine : getAccountsForRouting()) {
748                     sourceLine.refreshNonUpdateableReferences();
749                 }
750             } else {
751                 super.populateAccountsForRouting();
752             }
753         } catch (Exception e) {
754             logAndThrowRuntimeException("Error in populateAccountsForRouting while submitting document with id " + getDocumentNumber(), e);
755         }
756     }
757 
758 
759     @Override
760     public void doRouteLevelChange(DocumentRouteLevelChange levelChangeEvent) {
761         super.doRouteLevelChange(levelChangeEvent);
762         try {
763             String newNodeName = levelChangeEvent.getNewNodeName();
764             String documentId = this.getDocumentNumber();
765             LOG.info("********** Purchase order document Id: " + documentId + " ***********************");
766             if (!OLEConstants.PO_NOTE_MAP.containsKey(documentId)
767                     && newNodeName != null
768                     && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
769                     .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
770                 if (LOG.isDebugEnabled()){
771                     LOG.debug("********** Attachement List:  " + this.getNotes() + "***********************");
772                 }
773                 addPurchaseOrderNote(levelChangeEvent);
774                 if (LOG.isDebugEnabled()){
775                     LOG.debug("********** After Adding Attachement List:  " + this.getNotes() + "***********************");
776                 }
777                 OLEConstants.PO_NOTE_MAP.put(documentId, true);// boolean variable is not used, but in future if required for any
778                 // manipulation this can be used.
779             }
780         } catch (Exception e) {
781             String errorMsg = "Workflow Error found checking actions requests on document with id "
782                     + getDocumentNumber() + ". *** WILL NOT UPDATE PURAP STATUS ***";
783             LOG.error(errorMsg, e);
784         }
785     }
786 
787     public void addPurchaseOrderNote(DocumentRouteLevelChange levelChangeEvent) {
788 
789         String newNodeName = levelChangeEvent.getNewNodeName();
790         if (newNodeName != null
791                 && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
792                 .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
793             String note = "";
794             if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE)){
795                 note = OLEConstants.SufficientFundCheck.PO_NOTE;
796             }
797             if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET)){
798                 note = OLEConstants.SufficientFundCheck.FYI_NOTE;
799             }
800             DocumentService documentService = SpringContext.getBean(DocumentService.class);
801             Note apoNote = documentService.createNoteFromDocument(this, note);
802             this.addNote(apoNote);
803             documentService.saveDocumentNotes(this);
804         }
805 
806     }
807 
808     private void populateVendorAliasName() {
809         Map vendorDetailMap = new HashMap();
810         vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, this.getVendorHeaderGeneratedIdentifier());
811         vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, this.getVendorDetailAssignedIdentifier());
812         List<VendorAlias> vendorDetailList = (List) getBusinessObjectService().findMatching(VendorAlias.class, vendorDetailMap);
813         if (vendorDetailList != null && vendorDetailList.size() > 0) {
814             this.setVendorAliasName(vendorDetailList.get(0).getVendorAliasName());
815         }
816     }
817 
818     public boolean getIsATypeOfRCVGDoc() {
819         return false;
820     }
821 
822     public boolean getIsATypeOfCORRDoc() {
823         return false;
824     }
825 
826     public List<OlePurchaseOrderLineForInvoice> getOlePurchaseOrderLineForInvoiceList() {
827         return olePurchaseOrderLineForInvoiceList;
828     }
829 
830     public void setOlePurchaseOrderLineForInvoiceList(List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList) {
831         this.olePurchaseOrderLineForInvoiceList = olePurchaseOrderLineForInvoiceList;
832     }
833 
834     public List<OlePurchaseOrderTotal> getPurchaseOrderTotalList() {
835         return purchaseOrderTotalList;
836     }
837 
838     public void setPurchaseOrderTotalList(List<OlePurchaseOrderTotal> purchaseOrderTotalList) {
839         this.purchaseOrderTotalList = purchaseOrderTotalList;
840     }
841 
842     public Date getPoEndDate() {
843         return poEndDate;
844     }
845 
846     public void setPoEndDate(Date poEndDate) {
847         this.poEndDate = poEndDate;
848     }
849 
850     public boolean isClosePO() {
851         return closePO;
852     }
853 
854     public void setClosePO(boolean closePO) {
855         this.closePO = closePO;
856     }
857 
858     public String getPoNotes() {
859         return poNotes;
860     }
861 
862     public void setPoNotes(String poNotes) {
863         this.poNotes = poNotes;
864     }
865 
866     public String getPoItemLink() {
867         String documentTypeName = PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_DOCUMENT;
868         DocumentType docType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(documentTypeName);
869         String docHandlerUrl = docType.getResolvedDocumentHandlerUrl();
870         int endSubString = docHandlerUrl.lastIndexOf("/");
871         String serverName = docHandlerUrl.substring(0, endSubString);
872         String handler = docHandlerUrl.substring(endSubString + 1, docHandlerUrl.lastIndexOf("?"));
873         return serverName + "/" + KRADConstants.PORTAL_ACTION + "?channelTitle=" + docType.getName() + "&channelUrl=" +
874                 handler + "?" + KRADConstants.DISPATCH_REQUEST_PARAMETER + "=" + KRADConstants.DOC_HANDLER_METHOD + "&" +
875                 KRADConstants.PARAMETER_DOC_ID + "=" + this.getDocumentNumber() + "&" + KRADConstants.PARAMETER_COMMAND + "=" +
876                 KewApiConstants.DOCSEARCH_COMMAND;
877     }
878 
879     public void setPoItemLink(String poItemLink) {
880         this.poItemLink = poItemLink;
881     }
882 }