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