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