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)  && !this.getRequisitionSourceCode().equalsIgnoreCase(
409                             OleSelectConstant.REQUISITON_SRC_TYPE_AUTOINGEST)){
410                         singleItem.setVendorItemPoNumber(this.getVendorPoNumber());
411                     }
412                     if (singleItem.getBibInfoBean() != null) {
413                         if (!StringUtils.isEmpty(singleItem.getInternalRequestorId()) && singleItem.getBibInfoBean().getRequestorType() == null) {
414                             singleItem.setRequestorTypeId(getOlePurapService().getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_STAFF));
415                         }
416                     }
417                 }
418             }
419             if (event instanceof org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent && this.getRequisitionIdentifier() == null) {
420                 routePO();
421             }
422         } catch (Exception e) {
423             LOG.error("Exception in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
424             throw new RuntimeException("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
425         }
426         super.prepareForSave(event);
427     }
428 
429     /**
430      *
431      */
432     private void routePO(){
433         String currentUser = GlobalVariables.getUserSession().getPrincipalName();
434         try {
435             UserSession userSession = GlobalVariables.getUserSession();
436             // TODO: need to configure a user/role
437             GlobalVariables.setUserSession(new UserSession(getOleSelectDocumentService().getSelectParameterValue(OLEConstants.SYSTEM_USER)));
438             RequisitionDocument requisitionDocument = getRequisitionService().generateRequisitionFromPurchaseOrder(this);
439             // rdoc.setAccountsPayablePurchasingDocumentLinkIdentifier(this.getDocumentNumber());
440             if (LOG.isDebugEnabled()) {
441                 LOG.debug("Requisition Document Status Code---->" + requisitionDocument.getApplicationDocumentStatus());
442             }
443             requisitionDocument.setRequisitionSourceCode(OLEConstants.REQ_SRC_CD);
444             List adHocRouteRecipientList = new ArrayList();
445             adHocRouteRecipientList.addAll(this.getAdHocRoutePersons());
446             adHocRouteRecipientList.addAll(this.getAdHocRouteWorkgroups());
447 
448             getDocumentService().blanketApproveDocument(requisitionDocument, "Automatic Approval From PO", adHocRouteRecipientList);
449             GlobalVariables.setUserSession(userSession);
450             this.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getPurapDocumentIdentifier());
451             this.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
452         } catch (WorkflowException e) {
453             LOG.error("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
454             throw new RuntimeException("Error in OlePurchaseOrderDocument:prepareForSave: " + e.getMessage());
455         } finally {
456             GlobalVariables.setUserSession(new UserSession(currentUser));
457         }
458         this.setStatusCode(PurchaseOrderStatuses.APPDOC_IN_PROCESS);
459     }
460     @Override
461     public void processAfterRetrieve() {
462         try {
463             PurchaseOrderType purchaseOrderTypeDoc = getOlePurapService().getPurchaseOrderType(this.getPurchaseOrderTypeId());
464             if(purchaseOrderTypeDoc != null){
465                 this.setOrderType(purchaseOrderTypeDoc);
466             }
467             if (this.getVendorAliasName() == null) {
468                 populateVendorAliasName();
469             }
470             List<OlePurchaseOrderItem> items = this.getItems();
471             Iterator iterator = items.iterator();
472             while (iterator.hasNext()) {
473                 try{
474                     OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) iterator.next();
475                     // Added for jira OLE-2811 starts
476                     //Modified for jiar OLE-6032
477                     setItemDetailWhileProcessAfterRetrive(singleItem);
478                 }catch(Exception e){
479                     LOG.error("Exception in OlePurchaseOrderDocument:processAfterRetrieve --Exception while processing receiving purchasing record--->"+e);
480                     e.printStackTrace();
481                 }
482             }//End of Iteration of Purchase order while loop
483         } catch (Exception e) {
484             LOG.error("Error in OlePurchaseOrderDocument:processAfterRetrieve for OlePurchaseOrderItem " + e.getMessage());
485             throw new RuntimeException(e);
486         }
487     }
488 
489     /**
490      * This method is used to set the item detail while processafterretrive method is executed
491      * @param olePurchaseOrderItem
492      */
493     private void setItemDetailWhileProcessAfterRetrive(OlePurchaseOrderItem olePurchaseOrderItem)throws Exception{
494         if(olePurchaseOrderItem.getRequestorId()!=null){
495             olePurchaseOrderItem.setRequestorFirstName(getOlePurapService().getPatronName(olePurchaseOrderItem.getRequestorId()));
496         }
497         if(olePurchaseOrderItem.getItemUnitPrice()!=null){
498             olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
499         }
500         if (olePurchaseOrderItem.getItemTitleId() != null) {
501             olePurchaseOrderItem.setBibInfoBean(new BibInfoBean());
502             if (olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != "") {
503                 Bib bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(olePurchaseOrderItem.getItemTitleId());
504                 olePurchaseOrderItem.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(olePurchaseOrderItem.getItemTitleId()));
505                 if (bib != null) {
506                     olePurchaseOrderItem.setItemDescription(getOlePurapService().getItemDescription(bib));
507                     //setItemDescription(olePurchaseOrderItem,bib);
508                     olePurchaseOrderItem.setBibUUID(bib.getId());
509                 }
510             }
511         }
512         if (olePurchaseOrderItem.getItemType() != null && olePurchaseOrderItem.getItemType().isQuantityBasedGeneralLedgerIndicator()) {
513             populateCopiesSection(olePurchaseOrderItem);
514         }
515         if(olePurchaseOrderItem.getClaimDate()==null){
516             getOlePurapService().setClaimDateForPO(olePurchaseOrderItem,this.vendorDetail);
517         }
518         if(olePurchaseOrderItem.getCopyList().size() > 0) {
519             //getOlePurapService().setInvoiceDocumentsForPO(olePurchaseOrderItem);
520             getOlePurapService().setInvoiceDocumentsForPO(this,olePurchaseOrderItem);
521         }
522     }
523 
524     /**
525      * This method is used to set the item description on item for the given Bib
526      * @param olePurchaseOrderItem
527      * @param newBib
528      */
529 /*    private void setItemDescription(OlePurchaseOrderItem olePurchaseOrderItem, Bib newBib){
530         LOG.debug("### Inside setItemDescription() of OleRequisitionDocument ###");
531         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() + "," : "");
532         itemDescription = itemDescription.substring(0, itemDescription.lastIndexOf(","));
533         if(LOG.isDebugEnabled()){
534             LOG.debug("Item Description---------->"+itemDescription);
535         }
536         StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
537         itemDescription = stringEscapeUtils.unescapeHtml(itemDescription);
538         olePurchaseOrderItem.setItemDescription(itemDescription);
539     }*/
540 
541     /**
542      * This method is used to populated the copies section details
543      * @param singleItem
544      */
545     private void populateCopiesSection(OlePurchaseOrderItem singleItem) {
546         LOG.debug("### Inside populateCopiesSection of OlePurchaseOrderDocument ###");
547         if (singleItem.getCopies().size() > 0) {
548             List<OleCopy> copyList = getOleCopyHelperService().setCopyValuesForList(singleItem.getCopies(), singleItem.getItemTitleId(), null, null);
549             if (copyList.size() >= singleItem.getCopyList().size()) {
550                 int copyCount = 0;
551                 for (OleCopy oleCopy : singleItem.getCopyList()) {
552                     OleCopy copy = copyList.get(copyCount);
553                     oleCopy.setLocation(copy.getLocation());
554                     oleCopy.setEnumeration(copy.getEnumeration());
555                     oleCopy.setCopyNumber(copy.getCopyNumber());
556                     oleCopy.setPartNumber(copy.getPartNumber());
557                     copyCount++;
558                 }
559                 for(int i = copyCount ; i<copyList.size() ; i++){
560                     singleItem.getCopyList().add(copyList.get(copyCount));
561                     copyCount++;
562                 }
563             }
564         }
565         else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && !singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
566                 && !singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))&&singleItem.getCopyList().size()>0) {
567             singleItem.setSingleCopyNumber(singleItem.getCopyList().get(0).getCopyNumber());
568         }
569         else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
570                     || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1)))) {
571             singleItem.setCopies(getOleCopyHelperService().setCopiesToLineItem(singleItem.getCopyList(), singleItem.getItemNoOfParts(), singleItem.getItemTitleId()));
572         }
573         if(singleItem.getCopyList().size() > 0) {
574             //getOlePurapService().setInvoiceDocumentsForPO(singleItem);
575             getOlePurapService().setInvoiceDocumentsForPO(this,singleItem);
576         }
577     }
578 
579     /**
580      * Sets default values for APO.
581      */
582     @Override
583     public void setDefaultValuesForAPO() {
584         this.setPurchaseOrderAutomaticIndicator(Boolean.TRUE);
585         if (!RequisitionSources.B2B.equals(this.getRequisitionSourceCode())) {
586             String paramName = PurapParameterConstants.DEFAULT_B2B_VENDOR_CHOICE;
587             String paramValue = getParameterService().getParameterValueAsString(PurchaseOrderDocument.class, paramName);
588             this.setPurchaseOrderVendorChoiceCode(paramValue);
589         }
590     }
591 
592     @Override
593     public Class getItemClass() {
594         // TODO Auto-generated method stub
595         return OlePurchaseOrderItem.class;
596     }
597 
598 
599     public boolean getIsFinalReqs() {
600 
601         if (this.getDocumentHeader().getWorkflowDocument().isFinal()) {
602             return true;
603         }
604         return false;
605     }
606     /**
607      * This method is used to get the dublinedtior edit url from propertie file
608      *
609      * @return Dublineditor edit url string
610      */
611     public String getDublinEditorEditURL() {
612         return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorEditURL();
613     }
614 
615     /**
616      * This method is used to get the dublinedtior view url from propertie file
617      *
618      * @return dublineditor view url string
619      */
620     public String getDublinEditorViewURL() {
621         return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorViewURL();
622     }
623     /**
624 
625      /**
626      * This method is used to get the bibedtior creat url from propertie file
627      *
628      * @return Bibeditor creat url string
629      */
630     public String getBibeditorCreateURL() {
631         String bibeditorCreateURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
632         return bibeditorCreateURL;
633     }
634 
635     public String getBibSearchURL() {
636         String bibSearchURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
637         return bibSearchURL;
638     }
639 
640     /**
641      * This method is used to get the bibedtior edit url from propertie file
642      *
643      * @return Bibeditor edit url string
644      */
645     public String getBibeditorEditURL() {
646         String bibeditorEditURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
647         return bibeditorEditURL;
648     }
649 
650     /**
651      * This method is used to get the Instanceeditor url from propertie file
652      *
653      * @return Instanceeditor url string
654      */
655     public String getInstanceEditorURL() {
656         String instanceEditorURL = getConfigurationService().getPropertyValueAsString(
657                 OLEConstants.INSTANCEEDITOR_URL_KEY);
658         return instanceEditorURL;
659     }
660 
661     /**
662      * This method is used to get the bibedtior view url from propertie file
663      *
664      * @return Bibeditor view url string
665      */
666     public String getBibeditorViewURL() {
667         String bibeditorViewURL = getConfigurationService().getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
668         return bibeditorViewURL;
669     }
670 
671     /**
672      * This method is used to get the directory path where the marc xml files need to be created
673      *
674      * @return Directory path string
675      */
676     public String getMarcXMLFileDirLocation() throws Exception {
677         String externaleDirectory = getFileProcessingService().getMarcXMLFileDirLocation();
678         return externaleDirectory;
679     }
680 
681     public boolean getIsSplitPO() {
682         LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocument");
683         return getOlePurchaseOrderDocumentHelperService().getIsSplitPO(this);
684     }
685 
686     public boolean getIsReOpenPO() {
687         LOG.debug("Inside getIsReOpenPO of OlePurchaseOrderDocument");
688         return getOlePurchaseOrderDocumentHelperService().getIsReOpenPO(this);
689     }
690 
691 
692     public String getVendorPoNumber() {
693         return vendorPoNumber;
694     }
695 
696     public void setVendorPoNumber(String vendorPoNumber) {
697         this.vendorPoNumber = vendorPoNumber;
698     }
699 
700 
701     /**
702      * This method is used to check the status of the document for displaying view and edit buttons in line item
703      *
704      * @return boolean
705      */
706     public boolean getIsSaved() {
707         if (this.getDocumentHeader().getWorkflowDocument().isSaved() || this.getDocumentHeader().getWorkflowDocument().isInitiated()) {
708             return true;
709         }
710         return false;
711     }
712 
713     /**
714      * Method overridden for JIRA OLE-2359 Fund Check
715      * Makes sure that accounts for routing has been generated, so that other information can be retrieved from that
716      */
717     @Override
718     protected void populateAccountsForRouting() {
719         List<SufficientFundsItem> fundsItems = new ArrayList<SufficientFundsItem>();
720         String documentId = this.getDocumentNumber();
721         try {
722             //  String nodeName = SpringContext.getBean(WorkflowDocumentService.class).getCurrentRouteLevelName(getFinancialSystemDocumentHeader().getWorkflowDocument());
723             String nodeName = getFinancialSystemDocumentHeader().getWorkflowDocument().getCurrentNodeNames().iterator()
724                     .next();
725             if (nodeName != null
726                     && (nodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || nodeName
727                     .equalsIgnoreCase(PurapWorkflowConstants.BUDGET_REVIEW_REQUIRED))) {
728                 if (SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().compareTo(getPostingYear()) >= 0) {
729                     List<GeneralLedgerPendingEntry> pendingEntries = getPendingLedgerEntriesForSufficientFundsChecking();
730                     for (GeneralLedgerPendingEntry glpe : pendingEntries) {
731                         glpe.getChartOfAccountsCode();
732                     }
733                     SpringContext.getBean(GeneralLedgerPendingEntryService.class).delete(getDocumentNumber());
734                     fundsItems = SpringContext.getBean(SufficientFundsService.class).checkSufficientFunds(pendingEntries);
735                     SpringContext.getBean(GeneralLedgerPendingEntryService.class).generateGeneralLedgerPendingEntries(this);
736                     SpringContext.getBean(BusinessObjectService.class).save(getGeneralLedgerPendingEntries());
737                 }
738                 SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(this);
739                 accountsForRouting = (SpringContext.getBean(PurapAccountingService.class).generateSummary(getItems()));
740                 List<String> fundsItemList = new ArrayList<String>();
741                 for (SufficientFundsItem fundsItem : fundsItems) {
742                     fundsItemList.add(fundsItem.getAccount().getChartOfAccountsCode());
743                 }
744                 for (Iterator accountsForRoutingIter = accountsForRouting.iterator(); accountsForRoutingIter.hasNext(); ) {
745                     if (!(fundsItemList.contains(((SourceAccountingLine) accountsForRoutingIter.next()).getChartOfAccountsCode()))) {
746                         accountsForRoutingIter.remove();
747                     }
748                 }
749                 setAccountsForRouting(accountsForRouting);
750                 // need to refresh to get the references for the searchable attributes (ie status) and for invoking route levels (ie account
751                 // objects) -hjs
752                 refreshNonUpdateableReferences();
753                 for (SourceAccountingLine sourceLine : getAccountsForRouting()) {
754                     sourceLine.refreshNonUpdateableReferences();
755                 }
756             } else {
757                 super.populateAccountsForRouting();
758             }
759         } catch (Exception e) {
760             logAndThrowRuntimeException("Error in populateAccountsForRouting while submitting document with id " + getDocumentNumber(), e);
761         }
762     }
763 
764 
765     @Override
766     public void doRouteLevelChange(DocumentRouteLevelChange levelChangeEvent) {
767         super.doRouteLevelChange(levelChangeEvent);
768         try {
769             String newNodeName = levelChangeEvent.getNewNodeName();
770             String documentId = this.getDocumentNumber();
771             LOG.info("********** Purchase order document Id: " + documentId + " ***********************");
772             if (!OLEConstants.PO_NOTE_MAP.containsKey(documentId)
773                     && newNodeName != null
774                     && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
775                     .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
776                 if (LOG.isDebugEnabled()){
777                     LOG.debug("********** Attachement List:  " + this.getNotes() + "***********************");
778                 }
779                 addPurchaseOrderNote(levelChangeEvent);
780                 if (LOG.isDebugEnabled()){
781                     LOG.debug("********** After Adding Attachement List:  " + this.getNotes() + "***********************");
782                 }
783                 OLEConstants.PO_NOTE_MAP.put(documentId, true);// boolean variable is not used, but in future if required for any
784                 // manipulation this can be used.
785             }
786         } catch (Exception e) {
787             String errorMsg = "Workflow Error found checking actions requests on document with id "
788                     + getDocumentNumber() + ". *** WILL NOT UPDATE PURAP STATUS ***";
789             LOG.error(errorMsg, e);
790         }
791     }
792 
793     public void addPurchaseOrderNote(DocumentRouteLevelChange levelChangeEvent) {
794 
795         String newNodeName = levelChangeEvent.getNewNodeName();
796         if (newNodeName != null
797                 && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
798                 .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
799             String note = "";
800             if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE)){
801                 note = OLEConstants.SufficientFundCheck.PO_NOTE;
802             }
803             if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET)){
804                 note = OLEConstants.SufficientFundCheck.FYI_NOTE;
805             }
806             DocumentService documentService = SpringContext.getBean(DocumentService.class);
807             Note apoNote = documentService.createNoteFromDocument(this, note);
808             this.addNote(apoNote);
809             documentService.saveDocumentNotes(this);
810         }
811 
812     }
813 
814     private void populateVendorAliasName() {
815         Map vendorDetailMap = new HashMap();
816         vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, this.getVendorHeaderGeneratedIdentifier());
817         vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, this.getVendorDetailAssignedIdentifier());
818         List<VendorAlias> vendorDetailList = (List) getBusinessObjectService().findMatching(VendorAlias.class, vendorDetailMap);
819         if (vendorDetailList != null && vendorDetailList.size() > 0) {
820             this.setVendorAliasName(vendorDetailList.get(0).getVendorAliasName());
821         }
822     }
823 
824     public boolean getIsATypeOfRCVGDoc() {
825         return false;
826     }
827 
828     public boolean getIsATypeOfCORRDoc() {
829         return false;
830     }
831 
832     public List<OlePurchaseOrderLineForInvoice> getOlePurchaseOrderLineForInvoiceList() {
833         return olePurchaseOrderLineForInvoiceList;
834     }
835 
836     public void setOlePurchaseOrderLineForInvoiceList(List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList) {
837         this.olePurchaseOrderLineForInvoiceList = olePurchaseOrderLineForInvoiceList;
838     }
839 
840     public List<OlePurchaseOrderTotal> getPurchaseOrderTotalList() {
841         return purchaseOrderTotalList;
842     }
843 
844     public void setPurchaseOrderTotalList(List<OlePurchaseOrderTotal> purchaseOrderTotalList) {
845         this.purchaseOrderTotalList = purchaseOrderTotalList;
846     }
847 
848     public Date getPoEndDate() {
849         return poEndDate;
850     }
851 
852     public void setPoEndDate(Date poEndDate) {
853         this.poEndDate = poEndDate;
854     }
855 
856     public boolean isClosePO() {
857         return closePO;
858     }
859 
860     public void setClosePO(boolean closePO) {
861         this.closePO = closePO;
862     }
863 
864     public String getPoNotes() {
865         return poNotes;
866     }
867 
868     public void setPoNotes(String poNotes) {
869         this.poNotes = poNotes;
870     }
871 
872     public String getPoItemLink() {
873         String documentTypeName = PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_DOCUMENT;
874         DocumentType docType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(documentTypeName);
875         String docHandlerUrl = docType.getResolvedDocumentHandlerUrl();
876         int endSubString = docHandlerUrl.lastIndexOf("/");
877         String serverName = docHandlerUrl.substring(0, endSubString);
878         String handler = docHandlerUrl.substring(endSubString + 1, docHandlerUrl.lastIndexOf("?"));
879         return serverName + "/" + KRADConstants.PORTAL_ACTION + "?channelTitle=" + docType.getName() + "&channelUrl=" +
880                 handler + "?" + KRADConstants.DISPATCH_REQUEST_PARAMETER + "=" + KRADConstants.DOC_HANDLER_METHOD + "&" +
881                 KRADConstants.PARAMETER_DOC_ID + "=" + this.getDocumentNumber() + "&" + KRADConstants.PARAMETER_COMMAND + "=" +
882                 KewApiConstants.DOCSEARCH_COMMAND;
883     }
884 
885     public void setPoItemLink(String poItemLink) {
886         this.poItemLink = poItemLink;
887     }
888 
889     public OleSelectDocumentService getOleSelectDocumentService() {
890         if(oleSelectDocumentService == null){
891             oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
892         }
893         return oleSelectDocumentService;
894     }
895 
896     public void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
897         this.oleSelectDocumentService = oleSelectDocumentService;
898     }
899 }