001/*
002 * Copyright 2011 The Kuali Foundation.
003 *
004 * Licensed under the Educational Community License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.opensource.org/licenses/ecl2.php
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.kuali.ole.select.document;
017
018import org.apache.commons.lang.StringUtils;
019import org.kuali.ole.DocumentUniqueIDPrefix;
020import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
021import org.kuali.ole.docstore.common.document.Bib;
022import org.kuali.ole.gl.service.SufficientFundsService;
023import org.kuali.ole.integration.purap.CapitalAssetSystem;
024import org.kuali.ole.module.purap.PurapConstants;
025import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
026import org.kuali.ole.module.purap.PurapConstants.RequisitionSources;
027import org.kuali.ole.module.purap.PurapParameterConstants;
028import org.kuali.ole.module.purap.PurapWorkflowConstants;
029import org.kuali.ole.module.purap.businessobject.*;
030import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
031import org.kuali.ole.module.purap.document.PurchasingAccountsPayableDocument;
032import org.kuali.ole.module.purap.document.RequisitionDocument;
033import org.kuali.ole.module.purap.document.service.OlePurapService;
034import org.kuali.ole.module.purap.document.service.RequisitionService;
035import org.kuali.ole.module.purap.service.PurapAccountingService;
036import org.kuali.ole.select.OleSelectConstant;
037import org.kuali.ole.select.businessobject.*;
038import org.kuali.ole.select.document.service.OleCopyHelperService;
039import org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService;
040import org.kuali.ole.select.document.service.OleSelectDocumentService;
041import org.kuali.ole.select.service.BibInfoService;
042import org.kuali.ole.select.service.BibInfoWrapperService;
043import org.kuali.ole.select.service.FileProcessingService;
044import org.kuali.ole.select.service.impl.BibInfoServiceImpl;
045import org.kuali.ole.sys.OLEConstants;
046import org.kuali.ole.sys.businessobject.GeneralLedgerPendingEntry;
047import org.kuali.ole.sys.businessobject.SourceAccountingLine;
048import org.kuali.ole.sys.businessobject.SufficientFundsItem;
049import org.kuali.ole.sys.context.SpringContext;
050import org.kuali.ole.sys.service.GeneralLedgerPendingEntryService;
051import org.kuali.ole.sys.service.UniversityDateService;
052import org.kuali.ole.vnd.businessobject.VendorAlias;
053import org.kuali.rice.core.api.config.property.ConfigurationService;
054import org.kuali.rice.core.api.datetime.DateTimeService;
055import org.kuali.rice.core.api.util.type.KualiDecimal;
056import org.kuali.rice.core.api.util.type.KualiInteger;
057import org.kuali.rice.coreservice.framework.parameter.ParameterService;
058import org.kuali.rice.kew.api.KewApiConstants;
059import org.kuali.rice.kew.api.KewApiServiceLocator;
060import org.kuali.rice.kew.api.doctype.DocumentType;
061import org.kuali.rice.kew.api.exception.WorkflowException;
062import org.kuali.rice.kew.framework.postprocessor.DocumentRouteLevelChange;
063import org.kuali.rice.krad.UserSession;
064import org.kuali.rice.krad.bo.Note;
065import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent;
066import org.kuali.rice.krad.service.BusinessObjectService;
067import org.kuali.rice.krad.service.DocumentService;
068import org.kuali.rice.krad.util.GlobalVariables;
069import org.kuali.rice.krad.util.KRADConstants;
070import java.math.BigDecimal;
071import java.util.*;
072
073public class OlePurchaseOrderDocument extends PurchaseOrderDocument {
074    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderDocument.class);
075    /*    public void populatePurchaseOrderFromRequisition(RequisitionDocument requisitionDocument) {
076            super.populatePurchaseOrderFromRequisition(requisitionDocument);
077        }*/
078    private String vendorPoNumber;
079
080    private static transient ConfigurationService kualiConfigurationService;
081    private static transient BibInfoWrapperService bibInfoWrapperService;
082    private static transient DateTimeService dateTimeService;
083    private static transient FileProcessingService fileProcessingService;
084    private static transient BusinessObjectService businessObjectService;
085    private static transient ParameterService parameterService;
086    private static transient RequisitionService RequisitionService;
087    private static transient OlePurchaseOrderDocumentHelperService olePurchaseOrderDocumentHelperService;
088    private static transient DocumentService documentService;
089    protected List<SourceAccountingLine> accountsForRouting = new ArrayList<SourceAccountingLine>();
090    private static transient BibInfoService bibInfoService;
091    private static transient OlePatronRecordHandler olePatronRecordHandler;
092    private static transient OlePurapService olePurapService;
093    private static transient OleCopyHelperService oleCopyHelperService;
094    protected List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList = new ArrayList<OlePurchaseOrderLineForInvoice>();
095    protected List<OlePurchaseOrderTotal> purchaseOrderTotalList = new ArrayList<OlePurchaseOrderTotal>();
096    private Date poEndDate;
097    private boolean closePO;
098    private String poNotes;
099    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        }
521    }
522
523    /**
524     * This method is used to set the item description on item for the given Bib
525     * @param olePurchaseOrderItem
526     * @param newBib
527     */
528/*    private void setItemDescription(OlePurchaseOrderItem olePurchaseOrderItem, Bib newBib){
529        LOG.debug("### Inside setItemDescription() of OleRequisitionDocument ###");
530        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() + "," : "");
531        itemDescription = itemDescription.substring(0, itemDescription.lastIndexOf(","));
532        if(LOG.isDebugEnabled()){
533            LOG.debug("Item Description---------->"+itemDescription);
534        }
535        StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
536        itemDescription = stringEscapeUtils.unescapeHtml(itemDescription);
537        olePurchaseOrderItem.setItemDescription(itemDescription);
538    }*/
539
540    /**
541     * This method is used to populated the copies section details
542     * @param singleItem
543     */
544    private void populateCopiesSection(OlePurchaseOrderItem singleItem) {
545        LOG.debug("### Inside populateCopiesSection of OlePurchaseOrderDocument ###");
546        if (singleItem.getCopies().size() > 0) {
547            List<OleCopy> copyList = getOleCopyHelperService().setCopyValuesForList(singleItem.getCopies(), singleItem.getItemTitleId(), null);
548            if (copyList.size() >= singleItem.getCopyList().size()) {
549                int copyCount = 0;
550                for (OleCopy oleCopy : singleItem.getCopyList()) {
551                    OleCopy copy = copyList.get(copyCount);
552                    oleCopy.setLocation(copy.getLocation());
553                    oleCopy.setEnumeration(copy.getEnumeration());
554                    oleCopy.setCopyNumber(copy.getCopyNumber());
555                    oleCopy.setPartNumber(copy.getPartNumber());
556                    copyCount++;
557                }
558                for(int i = copyCount ; i<copyList.size() ; i++){
559                    singleItem.getCopyList().add(copyList.get(copyCount));
560                    copyCount++;
561                }
562            }
563        }
564        else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && !singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
565                && !singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))&&singleItem.getCopyList().size()>0) {
566            singleItem.setSingleCopyNumber(singleItem.getCopyList().get(0).getCopyNumber());
567        }
568        else if (singleItem.getItemQuantity() != null && singleItem.getItemNoOfParts() != null && (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
569                    || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1)))) {
570            singleItem.setCopies(getOleCopyHelperService().setCopiesToLineItem(singleItem.getCopyList(), singleItem.getItemNoOfParts(), singleItem.getItemTitleId()));
571        }
572        if(singleItem.getCopyList().size() > 0) {
573            getOlePurapService().setInvoiceDocumentsForPO(singleItem);
574        }
575    }
576
577    /**
578     * Sets default values for APO.
579     */
580    @Override
581    public void setDefaultValuesForAPO() {
582        this.setPurchaseOrderAutomaticIndicator(Boolean.TRUE);
583        if (!RequisitionSources.B2B.equals(this.getRequisitionSourceCode())) {
584            String paramName = PurapParameterConstants.DEFAULT_B2B_VENDOR_CHOICE;
585            String paramValue = getParameterService().getParameterValueAsString(PurchaseOrderDocument.class, paramName);
586            this.setPurchaseOrderVendorChoiceCode(paramValue);
587        }
588    }
589
590    @Override
591    public Class getItemClass() {
592        // TODO Auto-generated method stub
593        return OlePurchaseOrderItem.class;
594    }
595
596
597    public boolean getIsFinalReqs() {
598
599        if (this.getDocumentHeader().getWorkflowDocument().isFinal()) {
600            return true;
601        }
602        return false;
603    }
604    /**
605     * This method is used to get the dublinedtior edit url from propertie file
606     *
607     * @return Dublineditor edit url string
608     */
609    public String getDublinEditorEditURL() {
610        return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorEditURL();
611    }
612
613    /**
614     * This method is used to get the dublinedtior view url from propertie file
615     *
616     * @return dublineditor view url string
617     */
618    public String getDublinEditorViewURL() {
619        return SpringContext.getBean(OlePurchaseOrderDocumentHelperService.class).getDublinEditorViewURL();
620    }
621    /**
622
623     /**
624     * This method is used to get the bibedtior creat url from propertie file
625     *
626     * @return Bibeditor creat url string
627     */
628    public String getBibeditorCreateURL() {
629        String bibeditorCreateURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
630        return bibeditorCreateURL;
631    }
632
633    public String getBibSearchURL() {
634        String bibSearchURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
635        return bibSearchURL;
636    }
637
638    /**
639     * This method is used to get the bibedtior edit url from propertie file
640     *
641     * @return Bibeditor edit url string
642     */
643    public String getBibeditorEditURL() {
644        String bibeditorEditURL = getConfigurationService().getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
645        return bibeditorEditURL;
646    }
647
648    /**
649     * This method is used to get the Instanceeditor url from propertie file
650     *
651     * @return Instanceeditor url string
652     */
653    public String getInstanceEditorURL() {
654        String instanceEditorURL = getConfigurationService().getPropertyValueAsString(
655                OLEConstants.INSTANCEEDITOR_URL_KEY);
656        return instanceEditorURL;
657    }
658
659    /**
660     * This method is used to get the bibedtior view url from propertie file
661     *
662     * @return Bibeditor view url string
663     */
664    public String getBibeditorViewURL() {
665        String bibeditorViewURL = getConfigurationService().getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
666        return bibeditorViewURL;
667    }
668
669    /**
670     * This method is used to get the directory path where the marc xml files need to be created
671     *
672     * @return Directory path string
673     */
674    public String getMarcXMLFileDirLocation() throws Exception {
675        String externaleDirectory = getFileProcessingService().getMarcXMLFileDirLocation();
676        return externaleDirectory;
677    }
678
679    public boolean getIsSplitPO() {
680        LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocument");
681        return getOlePurchaseOrderDocumentHelperService().getIsSplitPO(this);
682    }
683
684    public boolean getIsReOpenPO() {
685        LOG.debug("Inside getIsReOpenPO of OlePurchaseOrderDocument");
686        return getOlePurchaseOrderDocumentHelperService().getIsReOpenPO(this);
687    }
688
689
690    public String getVendorPoNumber() {
691        return vendorPoNumber;
692    }
693
694    public void setVendorPoNumber(String vendorPoNumber) {
695        this.vendorPoNumber = vendorPoNumber;
696    }
697
698
699    /**
700     * This method is used to check the status of the document for displaying view and edit buttons in line item
701     *
702     * @return boolean
703     */
704    public boolean getIsSaved() {
705        if (this.getDocumentHeader().getWorkflowDocument().isSaved() || this.getDocumentHeader().getWorkflowDocument().isInitiated()) {
706            return true;
707        }
708        return false;
709    }
710
711    /**
712     * Method overridden for JIRA OLE-2359 Fund Check
713     * Makes sure that accounts for routing has been generated, so that other information can be retrieved from that
714     */
715    @Override
716    protected void populateAccountsForRouting() {
717        List<SufficientFundsItem> fundsItems = new ArrayList<SufficientFundsItem>();
718        String documentId = this.getDocumentNumber();
719        try {
720            //  String nodeName = SpringContext.getBean(WorkflowDocumentService.class).getCurrentRouteLevelName(getFinancialSystemDocumentHeader().getWorkflowDocument());
721            String nodeName = getFinancialSystemDocumentHeader().getWorkflowDocument().getCurrentNodeNames().iterator()
722                    .next();
723            if (nodeName != null
724                    && (nodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || nodeName
725                    .equalsIgnoreCase(PurapWorkflowConstants.BUDGET_REVIEW_REQUIRED))) {
726                if (SpringContext.getBean(UniversityDateService.class).getCurrentFiscalYear().compareTo(getPostingYear()) >= 0) {
727                    List<GeneralLedgerPendingEntry> pendingEntries = getPendingLedgerEntriesForSufficientFundsChecking();
728                    for (GeneralLedgerPendingEntry glpe : pendingEntries) {
729                        glpe.getChartOfAccountsCode();
730                    }
731                    SpringContext.getBean(GeneralLedgerPendingEntryService.class).delete(getDocumentNumber());
732                    fundsItems = SpringContext.getBean(SufficientFundsService.class).checkSufficientFunds(pendingEntries);
733                    SpringContext.getBean(GeneralLedgerPendingEntryService.class).generateGeneralLedgerPendingEntries(this);
734                    SpringContext.getBean(BusinessObjectService.class).save(getGeneralLedgerPendingEntries());
735                }
736                SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(this);
737                accountsForRouting = (SpringContext.getBean(PurapAccountingService.class).generateSummary(getItems()));
738                List<String> fundsItemList = new ArrayList<String>();
739                for (SufficientFundsItem fundsItem : fundsItems) {
740                    fundsItemList.add(fundsItem.getAccount().getChartOfAccountsCode());
741                }
742                for (Iterator accountsForRoutingIter = accountsForRouting.iterator(); accountsForRoutingIter.hasNext(); ) {
743                    if (!(fundsItemList.contains(((SourceAccountingLine) accountsForRoutingIter.next()).getChartOfAccountsCode()))) {
744                        accountsForRoutingIter.remove();
745                    }
746                }
747                setAccountsForRouting(accountsForRouting);
748                // need to refresh to get the references for the searchable attributes (ie status) and for invoking route levels (ie account
749                // objects) -hjs
750                refreshNonUpdateableReferences();
751                for (SourceAccountingLine sourceLine : getAccountsForRouting()) {
752                    sourceLine.refreshNonUpdateableReferences();
753                }
754            } else {
755                super.populateAccountsForRouting();
756            }
757        } catch (Exception e) {
758            logAndThrowRuntimeException("Error in populateAccountsForRouting while submitting document with id " + getDocumentNumber(), e);
759        }
760    }
761
762
763    @Override
764    public void doRouteLevelChange(DocumentRouteLevelChange levelChangeEvent) {
765        super.doRouteLevelChange(levelChangeEvent);
766        try {
767            String newNodeName = levelChangeEvent.getNewNodeName();
768            String documentId = this.getDocumentNumber();
769            LOG.info("********** Purchase order document Id: " + documentId + " ***********************");
770            if (!OLEConstants.PO_NOTE_MAP.containsKey(documentId)
771                    && newNodeName != null
772                    && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
773                    .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
774                if (LOG.isDebugEnabled()){
775                    LOG.debug("********** Attachement List:  " + this.getNotes() + "***********************");
776                }
777                addPurchaseOrderNote(levelChangeEvent);
778                if (LOG.isDebugEnabled()){
779                    LOG.debug("********** After Adding Attachement List:  " + this.getNotes() + "***********************");
780                }
781                OLEConstants.PO_NOTE_MAP.put(documentId, true);// boolean variable is not used, but in future if required for any
782                // manipulation this can be used.
783            }
784        } catch (Exception e) {
785            String errorMsg = "Workflow Error found checking actions requests on document with id "
786                    + getDocumentNumber() + ". *** WILL NOT UPDATE PURAP STATUS ***";
787            LOG.error(errorMsg, e);
788        }
789    }
790
791    public void addPurchaseOrderNote(DocumentRouteLevelChange levelChangeEvent) {
792
793        String newNodeName = levelChangeEvent.getNewNodeName();
794        if (newNodeName != null
795                && (newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE) || newNodeName
796                .equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET))) {
797            String note = "";
798            if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.BUDGET_NODE)){
799                note = OLEConstants.SufficientFundCheck.PO_NOTE;
800            }
801            if(newNodeName.equalsIgnoreCase(PurapWorkflowConstants.FYI_BUDGET)){
802                note = OLEConstants.SufficientFundCheck.FYI_NOTE;
803            }
804            DocumentService documentService = SpringContext.getBean(DocumentService.class);
805            Note apoNote = documentService.createNoteFromDocument(this, note);
806            this.addNote(apoNote);
807            documentService.saveDocumentNotes(this);
808        }
809
810    }
811
812    private void populateVendorAliasName() {
813        Map vendorDetailMap = new HashMap();
814        vendorDetailMap.put(OLEConstants.VENDOR_HEADER_IDENTIFIER, this.getVendorHeaderGeneratedIdentifier());
815        vendorDetailMap.put(OLEConstants.VENDOR_DETAIL_IDENTIFIER, this.getVendorDetailAssignedIdentifier());
816        List<VendorAlias> vendorDetailList = (List) getBusinessObjectService().findMatching(VendorAlias.class, vendorDetailMap);
817        if (vendorDetailList != null && vendorDetailList.size() > 0) {
818            this.setVendorAliasName(vendorDetailList.get(0).getVendorAliasName());
819        }
820    }
821
822    public boolean getIsATypeOfRCVGDoc() {
823        return false;
824    }
825
826    public boolean getIsATypeOfCORRDoc() {
827        return false;
828    }
829
830    public List<OlePurchaseOrderLineForInvoice> getOlePurchaseOrderLineForInvoiceList() {
831        return olePurchaseOrderLineForInvoiceList;
832    }
833
834    public void setOlePurchaseOrderLineForInvoiceList(List<OlePurchaseOrderLineForInvoice> olePurchaseOrderLineForInvoiceList) {
835        this.olePurchaseOrderLineForInvoiceList = olePurchaseOrderLineForInvoiceList;
836    }
837
838    public List<OlePurchaseOrderTotal> getPurchaseOrderTotalList() {
839        return purchaseOrderTotalList;
840    }
841
842    public void setPurchaseOrderTotalList(List<OlePurchaseOrderTotal> purchaseOrderTotalList) {
843        this.purchaseOrderTotalList = purchaseOrderTotalList;
844    }
845
846    public Date getPoEndDate() {
847        return poEndDate;
848    }
849
850    public void setPoEndDate(Date poEndDate) {
851        this.poEndDate = poEndDate;
852    }
853
854    public boolean isClosePO() {
855        return closePO;
856    }
857
858    public void setClosePO(boolean closePO) {
859        this.closePO = closePO;
860    }
861
862    public String getPoNotes() {
863        return poNotes;
864    }
865
866    public void setPoNotes(String poNotes) {
867        this.poNotes = poNotes;
868    }
869
870    public String getPoItemLink() {
871        String documentTypeName = PurapConstants.PurchaseOrderDocTypes.PURCHASE_ORDER_DOCUMENT;
872        DocumentType docType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(documentTypeName);
873        String docHandlerUrl = docType.getResolvedDocumentHandlerUrl();
874        int endSubString = docHandlerUrl.lastIndexOf("/");
875        String serverName = docHandlerUrl.substring(0, endSubString);
876        String handler = docHandlerUrl.substring(endSubString + 1, docHandlerUrl.lastIndexOf("?"));
877        return serverName + "/" + KRADConstants.PORTAL_ACTION + "?channelTitle=" + docType.getName() + "&channelUrl=" +
878                handler + "?" + KRADConstants.DISPATCH_REQUEST_PARAMETER + "=" + KRADConstants.DOC_HANDLER_METHOD + "&" +
879                KRADConstants.PARAMETER_DOC_ID + "=" + this.getDocumentNumber() + "&" + KRADConstants.PARAMETER_COMMAND + "=" +
880                KewApiConstants.DOCSEARCH_COMMAND;
881    }
882
883    public void setPoItemLink(String poItemLink) {
884        this.poItemLink = poItemLink;
885    }
886
887    public OleSelectDocumentService getOleSelectDocumentService() {
888        if(oleSelectDocumentService == null){
889            oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
890        }
891        return oleSelectDocumentService;
892    }
893
894    public void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
895        this.oleSelectDocumentService = oleSelectDocumentService;
896    }
897}