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.service.impl;
017
018import org.apache.commons.collections.CollectionUtils;
019import org.apache.commons.lang.StringUtils;
020import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
021import org.kuali.ole.docstore.common.document.*;
022import org.kuali.ole.DocumentUniqueIDPrefix;
023import org.kuali.ole.docstore.common.document.content.instance.xstream.HoldingOlemlRecordProcessor;
024import org.kuali.ole.docstore.common.document.content.instance.xstream.InstanceOlemlRecordProcessor;
025import org.kuali.ole.docstore.common.document.content.instance.xstream.ItemOlemlRecordProcessor;
026import org.kuali.ole.integration.purap.CapitalAssetSystem;
027import org.kuali.ole.module.purap.PurapConstants;
028import org.kuali.ole.module.purap.PurapConstants.PurchaseOrderStatuses;
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.select.OleSelectConstant;
035import org.kuali.ole.select.OleSelectNotificationConstant;
036import org.kuali.ole.select.businessobject.*;
037import org.kuali.ole.select.document.OlePurchaseOrderDocument;
038import org.kuali.ole.select.document.OleRequisitionDocument;
039import org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService;
040import org.kuali.ole.select.document.service.OleRequestorService;
041import org.kuali.ole.select.document.service.OleSelectDocumentService;
042import org.kuali.ole.select.service.BibInfoWrapperService;
043import org.kuali.ole.select.service.FileProcessingService;
044import org.kuali.ole.select.service.OleUrlResolver;
045import org.kuali.ole.select.service.impl.BibInfoWrapperServiceImpl;
046import org.kuali.ole.sys.OLEConstants;
047import org.kuali.ole.sys.context.SpringContext;
048import org.kuali.rice.core.api.config.property.ConfigurationService;
049import org.kuali.rice.core.api.datetime.DateTimeService;
050import org.kuali.rice.core.api.util.type.KualiDecimal;
051import org.kuali.rice.core.api.util.type.KualiInteger;
052import org.kuali.rice.kew.api.WorkflowDocument;
053import org.kuali.rice.kew.api.exception.WorkflowException;
054import org.kuali.rice.kim.api.identity.Person;
055import org.kuali.rice.kim.api.identity.PersonService;
056import org.kuali.rice.krad.UserSession;
057import org.kuali.rice.krad.rules.rule.event.KualiDocumentEvent;
058import org.kuali.rice.krad.service.KRADServiceLocator;
059import org.kuali.rice.krad.util.GlobalVariables;
060import java.math.BigDecimal;
061import java.util.*;
062
063public class OlePurchaseOrderDocumentHelperServiceImpl implements OlePurchaseOrderDocumentHelperService {
064
065    protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurchaseOrderDocumentHelperServiceImpl.class);
066    private final String UPDATE_EXISTING_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkIn&stringContent=";
067    private final String CHECKOUT_DOCSTORE_RECORD_QUERY_STRING = "docAction=checkOut&uuid=";
068    private final String CREATE_NEW_DOCSTORE_RECORD_QUERY_STRING = "docAction=ingestContent&stringContent=";
069    private ItemOlemlRecordProcessor itemOlemlRecordProcessor;
070    private HoldingOlemlRecordProcessor holdingOlemlRecordProcessor;
071    private InstanceOlemlRecordProcessor instanceOlemlRecordProcessor;
072    private transient OleUrlResolver oleUrlResolver;
073    private static transient OlePatronRecordHandler olePatronRecordHandler;
074    private static transient OlePatronDocumentList olePatronDocumentList;
075    private static transient OleSelectDocumentService oleSelectDocumentService;
076    private static transient OlePurapService olePurapService;
077    private DocstoreClientLocator docstoreClientLocator;
078    protected ConfigurationService kualiConfigurationService;
079
080    public DocstoreClientLocator getDocstoreClientLocator() {
081        if (docstoreClientLocator == null) {
082            docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
083        }
084        return docstoreClientLocator;
085    }
086    public static OleSelectDocumentService getOleSelectDocumentService() {
087        if (oleSelectDocumentService == null) {
088            oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
089        }
090        return oleSelectDocumentService;
091    }
092
093    public static void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
094        OlePurchaseOrderDocumentHelperServiceImpl.oleSelectDocumentService = oleSelectDocumentService;
095    }
096
097    public static OlePatronDocumentList getOlePatronDocumentList() {
098        if (olePatronDocumentList == null) {
099            olePatronDocumentList = SpringContext.getBean(OlePatronDocumentList.class);
100        }
101        return olePatronDocumentList;
102    }
103
104    public static void setOlePatronDocumentList(OlePatronDocumentList olePatronDocumentList) {
105        OlePurchaseOrderDocumentHelperServiceImpl.olePatronDocumentList = olePatronDocumentList;
106    }
107
108
109    public OlePatronRecordHandler getOlePatronRecordHandler() {
110        if (null == olePatronRecordHandler) {
111            olePatronRecordHandler = new OlePatronRecordHandler();
112        }
113        return olePatronRecordHandler;
114    }
115
116    public void setOlePatronRecordHandler(OlePatronRecordHandler olePatronRecordHandler) {
117        this.olePatronRecordHandler = olePatronRecordHandler;
118    }
119
120    public static OlePurapService getOlePurapService() {
121        if (olePurapService == null) {
122            olePurapService = SpringContext.getBean(OlePurapService.class);
123        }
124        return olePurapService;
125    }
126
127    public static void setOlePurapService(OlePurapService olePurapService) {
128        OlePurchaseOrderDocumentHelperServiceImpl.olePurapService = olePurapService;
129    }
130
131
132    /**
133     * This method is overridden to populate newly added ole fields from requisition into Purchase Order Document.
134     *
135     * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#populatePurchaseOrderFromRequisition(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.ole.module.purap.document.RequisitionDocument)
136     */
137    @Override
138    public void populatePurchaseOrderFromRequisition(PurchaseOrderDocument purchaseOrderDoc, RequisitionDocument requisitionDoc) {
139        LOG.debug("Inside populatePurchaseOrderFromRequisition of OlePurchaseOrderDocumentHelperServiceImpl");
140        OlePurchaseOrderDocument purchaseOrderDocument = (OlePurchaseOrderDocument) purchaseOrderDoc;
141        OleRequisitionDocument requisitionDocument = (OleRequisitionDocument) requisitionDoc;
142        purchaseOrderDocument.setPurchaseOrderCreateTimestamp(SpringContext.getBean(DateTimeService.class).getCurrentTimestamp());
143        purchaseOrderDocument.getDocumentHeader().setOrganizationDocumentNumber(requisitionDocument.getDocumentHeader().getOrganizationDocumentNumber());
144        purchaseOrderDocument.getDocumentHeader().setDocumentDescription(requisitionDocument.getDocumentHeader().getDocumentDescription());
145        purchaseOrderDocument.getDocumentHeader().setExplanation(requisitionDocument.getDocumentHeader().getExplanation());
146        purchaseOrderDocument.setBillingName(requisitionDocument.getBillingName());
147        purchaseOrderDocument.setBillingLine1Address(requisitionDocument.getBillingLine1Address());
148        purchaseOrderDocument.setBillingLine2Address(requisitionDocument.getBillingLine2Address());
149        purchaseOrderDocument.setBillingCityName(requisitionDocument.getBillingCityName());
150        purchaseOrderDocument.setBillingStateCode(requisitionDocument.getBillingStateCode());
151        purchaseOrderDocument.setBillingPostalCode(requisitionDocument.getBillingPostalCode());
152        purchaseOrderDocument.setBillingCountryCode(requisitionDocument.getBillingCountryCode());
153        purchaseOrderDocument.setBillingPhoneNumber(requisitionDocument.getBillingPhoneNumber());
154
155        purchaseOrderDocument.setReceivingName(requisitionDocument.getReceivingName());
156        purchaseOrderDocument.setReceivingCityName(requisitionDocument.getReceivingCityName());
157        purchaseOrderDocument.setReceivingLine1Address(requisitionDocument.getReceivingLine1Address());
158        purchaseOrderDocument.setReceivingLine2Address(requisitionDocument.getReceivingLine2Address());
159        purchaseOrderDocument.setReceivingStateCode(requisitionDocument.getReceivingStateCode());
160        purchaseOrderDocument.setReceivingPostalCode(requisitionDocument.getReceivingPostalCode());
161        purchaseOrderDocument.setReceivingCountryCode(requisitionDocument.getReceivingCountryCode());
162        purchaseOrderDocument.setAddressToVendorIndicator(requisitionDocument.getAddressToVendorIndicator());
163
164        purchaseOrderDocument.setDeliveryBuildingCode(requisitionDocument.getDeliveryBuildingCode());
165        purchaseOrderDocument.setDeliveryBuildingRoomNumber(requisitionDocument.getDeliveryBuildingRoomNumber());
166        purchaseOrderDocument.setDeliveryBuildingName(requisitionDocument.getDeliveryBuildingName());
167        purchaseOrderDocument.setDeliveryCampusCode(requisitionDocument.getDeliveryCampusCode());
168        purchaseOrderDocument.setDeliveryCityName(requisitionDocument.getDeliveryCityName());
169        purchaseOrderDocument.setDeliveryCountryCode(requisitionDocument.getDeliveryCountryCode());
170        purchaseOrderDocument.setDeliveryInstructionText(requisitionDocument.getDeliveryInstructionText());
171        purchaseOrderDocument.setDeliveryBuildingLine1Address(requisitionDocument.getDeliveryBuildingLine1Address());
172        purchaseOrderDocument.setDeliveryBuildingLine2Address(requisitionDocument.getDeliveryBuildingLine2Address());
173        purchaseOrderDocument.setDeliveryPostalCode(requisitionDocument.getDeliveryPostalCode());
174        purchaseOrderDocument.setDeliveryRequiredDate(requisitionDocument.getDeliveryRequiredDate());
175        purchaseOrderDocument.setDeliveryRequiredDateReasonCode(requisitionDocument.getDeliveryRequiredDateReasonCode());
176        purchaseOrderDocument.setDeliveryStateCode(requisitionDocument.getDeliveryStateCode());
177        purchaseOrderDocument.setDeliveryToEmailAddress(requisitionDocument.getDeliveryToEmailAddress());
178        purchaseOrderDocument.setDeliveryToName(requisitionDocument.getDeliveryToName());
179        purchaseOrderDocument.setDeliveryToPhoneNumber(requisitionDocument.getDeliveryToPhoneNumber());
180        purchaseOrderDocument.setDeliveryBuildingOtherIndicator(requisitionDocument.isDeliveryBuildingOtherIndicator());
181        purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
182        purchaseOrderDocument.setPurchaseOrderBeginDate(requisitionDocument.getPurchaseOrderBeginDate());
183        purchaseOrderDocument.setPurchaseOrderCostSourceCode(requisitionDocument.getPurchaseOrderCostSourceCode());
184        purchaseOrderDocument.setPostingYear(requisitionDocument.getPostingYear());
185        purchaseOrderDocument.setPurchaseOrderEndDate(requisitionDocument.getPurchaseOrderEndDate());
186        purchaseOrderDocument.setChartOfAccountsCode(requisitionDocument.getChartOfAccountsCode());
187        purchaseOrderDocument.setDocumentFundingSourceCode(requisitionDocument.getDocumentFundingSourceCode());
188        purchaseOrderDocument.setInstitutionContactEmailAddress(requisitionDocument.getInstitutionContactEmailAddress());
189        purchaseOrderDocument.setInstitutionContactName(requisitionDocument.getInstitutionContactName());
190        purchaseOrderDocument.setInstitutionContactPhoneNumber(requisitionDocument.getInstitutionContactPhoneNumber());
191        purchaseOrderDocument.setNonInstitutionFundAccountNumber(requisitionDocument.getNonInstitutionFundAccountNumber());
192        purchaseOrderDocument.setNonInstitutionFundChartOfAccountsCode(requisitionDocument.getNonInstitutionFundChartOfAccountsCode());
193        purchaseOrderDocument.setNonInstitutionFundOrgChartOfAccountsCode(requisitionDocument.getNonInstitutionFundOrgChartOfAccountsCode());
194        purchaseOrderDocument.setNonInstitutionFundOrganizationCode(requisitionDocument.getNonInstitutionFundOrganizationCode());
195        purchaseOrderDocument.setOrganizationCode(requisitionDocument.getOrganizationCode());
196        purchaseOrderDocument.setRecurringPaymentTypeCode(requisitionDocument.getRecurringPaymentTypeCode());
197        purchaseOrderDocument.setRequestorPersonEmailAddress(requisitionDocument.getRequestorPersonEmailAddress());
198        purchaseOrderDocument.setRequestorPersonName(requisitionDocument.getRequestorPersonName());
199        purchaseOrderDocument.setRequestorPersonPhoneNumber(requisitionDocument.getRequestorPersonPhoneNumber());
200        purchaseOrderDocument.setRequisitionIdentifier(requisitionDocument.getPurapDocumentIdentifier());
201        purchaseOrderDocument.setPurchaseOrderTotalLimit(requisitionDocument.getPurchaseOrderTotalLimit());
202        purchaseOrderDocument.setPurchaseOrderTransmissionMethodCode(requisitionDocument.getPurchaseOrderTransmissionMethodCode());
203        purchaseOrderDocument.setUseTaxIndicator(requisitionDocument.isUseTaxIndicator());
204        purchaseOrderDocument.setPurchaseOrderTypeId(requisitionDocument.getPurchaseOrderTypeId());
205        purchaseOrderDocument.setVendorCityName(requisitionDocument.getVendorCityName());
206        purchaseOrderDocument.setVendorContractGeneratedIdentifier(requisitionDocument.getVendorContractGeneratedIdentifier());
207        purchaseOrderDocument.setVendorCountryCode(requisitionDocument.getVendorCountryCode());
208        purchaseOrderDocument.setVendorCustomerNumber(requisitionDocument.getVendorCustomerNumber());
209        purchaseOrderDocument.setVendorAttentionName(requisitionDocument.getVendorAttentionName());
210        purchaseOrderDocument.setVendorDetailAssignedIdentifier(requisitionDocument.getVendorDetailAssignedIdentifier());
211        purchaseOrderDocument.setVendorFaxNumber(requisitionDocument.getVendorFaxNumber());
212        purchaseOrderDocument.setVendorHeaderGeneratedIdentifier(requisitionDocument.getVendorHeaderGeneratedIdentifier());
213        purchaseOrderDocument.setVendorLine1Address(requisitionDocument.getVendorLine1Address());
214        purchaseOrderDocument.setVendorLine2Address(requisitionDocument.getVendorLine2Address());
215        purchaseOrderDocument.setVendorAddressInternationalProvinceName(requisitionDocument.getVendorAddressInternationalProvinceName());
216        purchaseOrderDocument.setVendorName(requisitionDocument.getVendorName());
217        purchaseOrderDocument.setVendorNoteText(requisitionDocument.getVendorNoteText());
218        purchaseOrderDocument.setVendorPhoneNumber(requisitionDocument.getVendorPhoneNumber());
219        purchaseOrderDocument.setVendorPostalCode(requisitionDocument.getVendorPostalCode());
220        purchaseOrderDocument.setVendorStateCode(requisitionDocument.getVendorStateCode());
221        purchaseOrderDocument.setVendorRestrictedIndicator(requisitionDocument.getVendorRestrictedIndicator());
222        purchaseOrderDocument.setVendorPoNumber(requisitionDocument.getVendorPoNumber());
223        purchaseOrderDocument.setExternalOrganizationB2bSupplierIdentifier(requisitionDocument.getExternalOrganizationB2bSupplierIdentifier());
224        purchaseOrderDocument.setRequisitionSourceCode(requisitionDocument.getRequisitionSourceCode());
225        purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(requisitionDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
226        purchaseOrderDocument.setReceivingDocumentRequiredIndicator(requisitionDocument.isReceivingDocumentRequiredIndicator());
227        purchaseOrderDocument.setPaymentRequestPositiveApprovalIndicator(requisitionDocument.isPaymentRequestPositiveApprovalIndicator());
228        /*purchaseOrderDocument.setLicensingRequirementIndicator(requisitionDocument.isLicensingRequirementIndicator());*/
229       /* purchaseOrderDocument.setLicensingRequirementCode(requisitionDocument.getLicensingRequirementCode());*/
230
231        purchaseOrderDocument.setStatusCode(PurapConstants.PurchaseOrderStatuses.APPDOC_IN_PROCESS);
232
233        // Copy items from requisition (which will copy the item's accounts and capital assets)
234        List<OlePurchaseOrderItem> items = new ArrayList();
235        for (PurApItem reqItem : ((PurchasingAccountsPayableDocument) requisitionDocument).getItems()) {
236            RequisitionCapitalAssetItem reqCamsItem = (RequisitionCapitalAssetItem) requisitionDocument.getPurchasingCapitalAssetItemByItemIdentifier(reqItem.getItemIdentifier().intValue());
237            items.add(new OlePurchaseOrderItem((OleRequisitionItem) reqItem, purchaseOrderDocument, reqCamsItem));
238        }
239        purchaseOrderDocument.setItems(items);
240
241        // Copy capital asset information that is directly off the document.
242        purchaseOrderDocument.setCapitalAssetSystemTypeCode(requisitionDocument.getCapitalAssetSystemTypeCode());
243        purchaseOrderDocument.setCapitalAssetSystemStateCode(requisitionDocument.getCapitalAssetSystemStateCode());
244        for (CapitalAssetSystem capitalAssetSystem : requisitionDocument.getPurchasingCapitalAssetSystems()) {
245            purchaseOrderDocument.getPurchasingCapitalAssetSystems().add(new PurchaseOrderCapitalAssetSystem(capitalAssetSystem));
246        }
247
248        purchaseOrderDocument.fixItemReferences();
249    }
250
251    /**
252     * This method is overriden to populate bib info in  Purchase Order Document
253     *
254     * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#prepareForSave(org.kuali.ole.module.purap.document.PurchaseOrderDocument, org.kuali.rice.krad.rule.event.KualiDocumentEvent)
255     */
256    @Override
257    public void prepareForSave(PurchaseOrderDocument purchaseOrderDocument, KualiDocumentEvent event) {
258        LOG.debug("Inside prepareForSave of OlePurchaseOrderDocumentHelperServiceImpl");
259        WorkflowDocument workFlowDocument = purchaseOrderDocument.getDocumentHeader().getWorkflowDocument();
260        try {
261            List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
262            Iterator iterator = items.iterator();
263            while (iterator.hasNext()) {
264                Object object = iterator.next();
265                if (object instanceof OlePurchaseOrderItem) {
266                    OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
267                    if ((!StringUtils.isEmpty(singleItem.getInternalRequestorId()) || !StringUtils.isEmpty(singleItem
268                            .getRequestorId())) && singleItem.getRequestorTypeId() == null) {
269                        KualiInteger staffRequestorTypeId = getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_STAFF);
270                        singleItem.setRequestorTypeId(staffRequestorTypeId.intValue());
271                    }
272                }
273            }
274        } catch (Exception e) {
275            LOG.error("Exception in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
276            throw new RuntimeException(e);
277        }
278        if (event instanceof org.kuali.rice.krad.rules.rule.event.RouteDocumentEvent &&
279                purchaseOrderDocument.getRequisitionIdentifier() == null) {
280            try {
281                UserSession userSession = GlobalVariables.getUserSession();
282                //TODO: need to configure a user/role
283                //GlobalVariables.setUserSession(new UserSession("ole-khuntley"));
284                String user = null;
285                if (GlobalVariables.getUserSession() == null) {
286                    kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
287                    user = kualiConfigurationService.getPropertyValueAsString(getOleSelectDocumentService().getSelectParameterValue(OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR));
288                    GlobalVariables.setUserSession(new UserSession(user));
289                }
290                RequisitionDocument rdoc = SpringContext.getBean(org.kuali.ole.module.purap.document.service.RequisitionService.class)
291                        .generateRequisitionFromPurchaseOrder(purchaseOrderDocument);
292                if (LOG.isDebugEnabled()) {
293                    LOG.debug("Requisition Document Status Code---->" + rdoc.getApplicationDocumentStatus());
294                }
295                rdoc.setRequisitionSourceCode("STAN");
296                List adhocRouteRecipientList = new ArrayList();
297                adhocRouteRecipientList.addAll(purchaseOrderDocument.getAdHocRoutePersons());
298                adhocRouteRecipientList.addAll(purchaseOrderDocument.getAdHocRouteWorkgroups());
299                SpringContext.getBean(org.kuali.rice.krad.service.DocumentService.class).blanketApproveDocument(rdoc, "Automatic Approval From PO", adhocRouteRecipientList);
300                GlobalVariables.setUserSession(userSession);
301                purchaseOrderDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(rdoc.getPurapDocumentIdentifier());
302                purchaseOrderDocument.setRequisitionIdentifier(rdoc.getPurapDocumentIdentifier());
303            } catch (WorkflowException e) {
304                LOG.error("Exception in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
305                throw new RuntimeException("Error in OlePurchaseOrderDocumentHelperServiceImpl:prepareForSave: " + e.getMessage());
306            }
307
308            purchaseOrderDocument.setStatusCode(PurchaseOrderStatuses.APPDOC_IN_PROCESS);
309        }
310    }
311
312    private KualiInteger getRequestorTypeId(String requestorType) {
313        KualiInteger requestorTypeId = null;
314        Map<String, Object> criteria = new HashMap<String, Object>();
315        criteria.put(OleSelectConstant.REQUESTOR_TYPE, requestorType);
316        org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
317        Collection<OleRequestorType> requestorTypeList = businessObjectService.findMatching(OleRequestorType.class, criteria);
318        requestorTypeId = new KualiInteger(requestorTypeList.iterator().next().getRequestorTypeId());
319        return requestorTypeId;
320    }
321
322    protected void setRequestorNameOnItem(OlePurchasingItem singleItem) {
323        String requestorFirstName = singleItem.getRequestorFirstName();
324        if ((singleItem.getRequestorId() != null) || (singleItem.getInternalRequestorId() != null)) {
325            int requestorTypeId = singleItem.getRequestorTypeId();
326            Map requestorTypeIdMap = new HashMap();
327            requestorTypeIdMap.put("requestorTypeId", requestorTypeId);
328            org.kuali.rice.krad.service.BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
329            List<OleRequestorType> oleRequestorTypeList = (List) businessObjectService.findMatching(OleRequestorType.class, requestorTypeIdMap);
330            for (int i = 0; i < oleRequestorTypeList.size(); i++) {
331                if (oleRequestorTypeList.get(i).getRequestorType().equalsIgnoreCase(OleSelectConstant.REQUESTOR_TYPE_STAFF)) {
332                    Person personImpl = SpringContext.getBean(PersonService.class).getPerson(singleItem.getInternalRequestorId());
333                    if (singleItem.getRequestorId() == null && singleItem.getInternalRequestorId() != null) {
334                        if (personImpl != null) {
335                            singleItem.setRequestorFirstName(personImpl.getName());
336                        }
337                    }
338                }
339                /*
340                 * else { Map requestorIdMap = new HashMap(); requestorIdMap.put("requestorId", singleItem.getRequestorId());
341                 * List<OleRequestor> oleRequestorList = (List) businessObjectService.findMatching(OleRequestor.class,
342                 * requestorIdMap); singleItem.setRequestorFirstName(oleRequestorList.get(0).getRequestorFirstName()); }
343                 */
344            }
345        }
346    }
347
348
349    /**
350     * This method is overriden to populate bib info in  Purchase Order Document
351     *
352     * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#processAfterRetrieve(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
353     */
354    @Override
355    public void processAfterRetrieve(PurchaseOrderDocument purchaseOrderDocument) {
356        // super.processAfterRetrieve();
357        LOG.debug("Inside processAfterRetrieve of OlePurchaseOrderDocumentHelperServiceImpl");
358         // if(!purchaseOrderDocument.getFinancialDocumentTypeCode().equals("OLE_POC")) {
359        try {
360            PurchaseOrderType purchaseOrderTypeDoc = getOlePurapService().getPurchaseOrderType(purchaseOrderDocument.getPurchaseOrderTypeId());
361            if(purchaseOrderTypeDoc != null){
362                purchaseOrderDocument.setOrderType(purchaseOrderTypeDoc);
363            }
364            List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
365            Iterator iterator = items.iterator();
366            while (iterator.hasNext()) {
367                Object object = iterator.next();
368                if (object instanceof OlePurchaseOrderItem) {
369                    OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) object;
370                    setItemDetailWhileProcessAfterRetrive(singleItem);
371                }
372            }
373        } catch (Exception e) {
374            LOG.error("Exception in OlePurchaseOrderDocument:processAfterRetrieve for OlePurchaseOrderItem " + e.getMessage());
375            throw new RuntimeException(e);
376        }
377    // }
378    }
379
380    /**
381     * This method is used to set the item detail while processafterretrive method is executed
382     * @param olePurchaseOrderItem
383     */
384    private void setItemDetailWhileProcessAfterRetrive(OlePurchaseOrderItem olePurchaseOrderItem)throws Exception{
385        if(olePurchaseOrderItem.getRequestorId()!=null){
386            olePurchaseOrderItem.setRequestorFirstName(getOlePurapService().getPatronName(olePurchaseOrderItem.getRequestorId()));
387        }
388        // Added for jira OLE-2811 ends
389        setRequestorNameOnItem(olePurchaseOrderItem);
390        HashMap<String, String> dataMap = new HashMap<String, String>();
391        if(olePurchaseOrderItem.getItemUnitPrice()!=null){
392            olePurchaseOrderItem.setItemUnitPrice(olePurchaseOrderItem.getItemUnitPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
393        }
394        if (olePurchaseOrderItem.getItemTitleId() != null) {
395            Bib bib = new BibMarc();
396            if (olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != "") {
397                bib = getDocstoreClientLocator().getDocstoreClient().retrieveBib(olePurchaseOrderItem.getItemTitleId());
398            }
399            olePurchaseOrderItem.setBibUUID(bib.getId());
400            dataMap.put(OleSelectConstant.TITLE_ID, olePurchaseOrderItem.getItemTitleId());
401            dataMap.put(OleSelectConstant.DOC_CATEGORY_TYPE, OleSelectConstant.DOC_CATEGORY_TYPE_ITEMLINKS);
402            olePurchaseOrderItem.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(olePurchaseOrderItem.getItemTitleId()));
403            olePurchaseOrderItem.setItemDescription(getOlePurapService().getItemDescription(bib));
404        }
405        BibTree bibTree = new BibTree();
406        if(olePurchaseOrderItem.getItemTitleId() != null && olePurchaseOrderItem.getItemTitleId() != ""){
407            bibTree = getDocstoreClientLocator().getDocstoreClient().retrieveBibTree(olePurchaseOrderItem.getItemTitleId());
408        }
409        if (null != olePurchaseOrderItem.getItemTitleId()) {
410            if (olePurchaseOrderItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
411                    || olePurchaseOrderItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
412                List<OleCopies> copies = setCopiesToLineItem(olePurchaseOrderItem, bibTree);
413                if(CollectionUtils.isNotEmpty(bibTree.getHoldingsTrees())){
414                    if(CollectionUtils.isNotEmpty(bibTree.getHoldingsTrees().get(0).getItems())){
415                        olePurchaseOrderItem.setItemTypeDescription(bibTree.getHoldingsTrees().get(0).getItems().get(0).getItemType());
416                    }else{
417                        olePurchaseOrderItem.setItemTypeDescription("");
418                    }
419                }else {
420                    olePurchaseOrderItem.setItemTypeDescription("");
421                }
422                olePurchaseOrderItem.setCopies(copies);
423            }
424        }
425        if (olePurchaseOrderItem.getItemQuantity() != null && olePurchaseOrderItem.getItemNoOfParts() != null && !olePurchaseOrderItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
426                && !olePurchaseOrderItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))&&olePurchaseOrderItem.getCopyList().size()>0) {
427            olePurchaseOrderItem.setSingleCopyNumber(olePurchaseOrderItem.getCopyList().get(0).getCopyNumber());
428        }
429    }
430
431    public List<OleCopies> setCopiesToLineItem(OlePurchaseOrderItem singleItem, BibTree bibTree) {
432        List<HoldingsTree> instanceDocuments = bibTree.getHoldingsTrees();
433        List<OleCopies> copies = new ArrayList<OleCopies>();
434        for (HoldingsTree holdingsTree : instanceDocuments) {
435            List<Item> itemDocuments = holdingsTree.getItems();
436            StringBuffer enumeration = new StringBuffer();
437            for (int itemDocs = 0; itemDocs < itemDocuments.size(); itemDocs++) {
438                if (itemDocs + 1 == itemDocuments.size()) {
439                    enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration());
440                } else {
441                    enumeration = enumeration.append(itemDocuments.get(itemDocs).getEnumeration() + ";");
442                }
443
444            }
445            int startingCopy = 0;
446            if (singleItem.getItemNoOfParts().intValue() != 0 && null != enumeration && StringUtils.isNotEmpty(enumeration.toString())) {
447                String enumerationSplit = enumeration.substring(1, 2);
448                boolean isint = checkIsEnumerationSplitIsIntegerOrNot(enumerationSplit);
449                if (isint) {
450                    startingCopy = Integer.parseInt(enumerationSplit);
451                }
452            }
453            if (singleItem.getItemQuantity().isGreaterThan(new KualiDecimal(1))
454                    || singleItem.getItemNoOfParts().isGreaterThan(new KualiInteger(1))) {
455                int noOfCopies = holdingsTree.getItems().size()
456                        / singleItem.getItemNoOfParts().intValue();
457                OleRequisitionCopies copy = new OleRequisitionCopies();
458                copy.setParts(singleItem.getItemNoOfParts());
459                copy.setLocationCopies(holdingsTree.getHoldings().getLocationName());
460                copy.setItemCopies(new KualiDecimal(noOfCopies));
461                copy.setPartEnumeration(enumeration.toString());
462                copy.setStartingCopyNumber(new KualiInteger(startingCopy));
463                copies.add(copy);
464            }
465        }
466        return copies;
467    }
468
469    public boolean checkIsEnumerationSplitIsIntegerOrNot(String enumerationSplit) {
470        try {
471            int startingCopy = Integer.parseInt(enumerationSplit);
472        } catch (NumberFormatException e) {
473            return false;
474        }
475        return true;
476    }
477
478    /**
479     * This method takes List of UUids as parameter and creates a LinkedHashMap with instance as key and id as value. and calls
480     * Docstore's QueryServiceImpl class getWorkBibRecords method and return workBibDocument for passed instance Id.
481     *
482     * @param instanceIdsList
483     * @return List<WorkBibDocument>
484     */
485//    private List<WorkBibDocument> getWorkBibDocuments(List<String> instanceIdsList) {
486//        List<LinkedHashMap<String, String>> instanceIdMapList = new ArrayList<LinkedHashMap<String, String>>();
487//        for (String instanceId : instanceIdsList) {
488//            LinkedHashMap<String, String> instanceIdMap = new LinkedHashMap<String, String>();
489//            instanceIdMap.put(DocType.BIB.getDescription(), instanceId);
490//            instanceIdMapList.add(instanceIdMap);
491//        }
492//
493//        QueryService queryService = QueryServiceImpl.getInstance();
494//        List<WorkBibDocument> workBibDocuments = new ArrayList<WorkBibDocument>();
495//        try {
496//            workBibDocuments = queryService.getWorkBibRecords(instanceIdMapList);
497//        } catch (Exception ex) {
498//            // TODO Auto-generated catch block
499//            ex.printStackTrace();
500//        }
501//        return workBibDocuments;
502//    }
503
504    // Added for Jira OLE-1900 Ends
505
506    @Override
507    public void setBibInfoBean(BibInfoBean bibInfoBean, OlePurchaseOrderItem singleItem) {
508        bibInfoBean.setTitle(singleItem.getItemTitle());
509        bibInfoBean.setAuthor(singleItem.getItemAuthor());
510        bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
511    }
512
513    @Override
514    public void setBibInfoBean(BibInfoBean bibInfoBean, OleRequisitionItem singleItem) {
515        bibInfoBean.setTitle(singleItem.getBibInfoBean().getTitle());
516        bibInfoBean.setAuthor(singleItem.getBibInfoBean().getAuthor());
517        bibInfoBean.setRequestor(singleItem.getRequestorId() == null ? null : singleItem.getRequestorId().toString());
518    }
519
520    /**
521     * This method returns if Purchase Order Document created is in Final Status
522     *
523     * @see org.kuali.ole.select.document.service.OlePurchaseOrderDocumentHelperService#getIsFinalReqs(org.kuali.ole.module.purap.document.PurchaseOrderDocument)
524     */
525    @Override
526    public boolean getIsFinalReqs(PurchaseOrderDocument purchaseOrderDocument) {
527        LOG.debug("Inside getIsFinalReqs of OlePurchaseOrderDocumentHelperServiceImpl");
528        if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isFinal()) {
529            return true;
530        }
531        return false;
532    }
533
534
535    @Override
536    public boolean getIsSplitPO(PurchaseOrderDocument purchaseOrderDocument) {
537        LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
538        if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_SPLIT) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
539            return true;
540        }
541        return false;
542    }
543
544    @Override
545    public boolean getIsReOpenPO(PurchaseOrderDocument purchaseOrderDocument) {
546        LOG.debug("Inside getIsSplitPO of OlePurchaseOrderDocumentHelperServiceImpl");
547        if (purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName().equalsIgnoreCase(OLEConstants.FinancialDocumentTypeCodes.PURCHASE_ORDER_REOPEN) && purchaseOrderDocument.getDocumentHeader().getWorkflowDocument().isSaved()) {
548            return true;
549        }
550        return false;
551    }
552
553    /**
554     * This method is used to get the bibedtior creat url from propertie file
555     *
556     * @return Bibeditor creat url string
557     */
558    @Override
559    public String getBibeditorCreateURL() {
560        String bibeditorCreateURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_CREATE_URL_KEY);
561        return bibeditorCreateURL;
562    }
563
564    @Override
565    public String getBibSearchURL() {
566        String bibSearchURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_SEARCH_URL_KEY);
567        return bibSearchURL;
568    }
569
570    /**
571     * This method is used to get the bibedtior edit url from propertie file
572     *
573     * @return Bibeditor edit url string
574     */
575    @Override
576    public String getBibeditorEditURL() {
577        String bibeditorEditURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.BIBEDITOR_URL_KEY);
578        return bibeditorEditURL;
579    }
580
581    /**
582     * This method is used to get the dublinedtior edit url from propertie file
583     *
584     * @return Dublineditor edit url string
585     */
586    public String getDublinEditorEditURL() {
587        String dublinEditorEditURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DUBLINEDITOR_URL_KEY);
588        return dublinEditorEditURL;
589    }
590    /**
591     * This method is used to get the bibedtior view url from propertie file
592     *
593     * @return Bibeditor view url string
594     */
595    @Override
596    public String getBibeditorViewURL() {
597        String bibeditorViewURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSTORE_APP_URL_KEY);
598        return bibeditorViewURL;
599    }
600    /**
601     * This method is used to get the dublinedtior view url from propertie file
602     *
603     * @return dublineditor view url string
604     */
605    public String getDublinEditorViewURL() {
606        String dublinEditorViewURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(OLEConstants.DOCSTORE_VIEW_URL_KEY);
607        return dublinEditorViewURL;
608    }
609    /**
610     * This method is used to get the Instanceeditor url from propertie file
611     *
612     * @return Instanceeditor url string
613     */
614    @Override
615    public String getInstanceEditorURL() {
616        String instanceEditorURL = SpringContext.getBean(ConfigurationService.class).getPropertyValueAsString(
617                OLEConstants.INSTANCEEDITOR_URL_KEY);
618        return instanceEditorURL;
619    }
620
621    /**
622     * This method is used to get the directory path where the marc xml files need to be created
623     *
624     * @return Directory path string
625     */
626    @Override
627    public String getMarcXMLFileDirLocation() throws Exception {
628        FileProcessingService fileProcessingService = SpringContext.getBean(FileProcessingService.class);
629        String externaleDirectory = fileProcessingService.getMarcXMLFileDirLocation();
630        return externaleDirectory;
631    }
632
633
634    @Override
635    public List getItemsActiveOnly(PurchaseOrderDocument purchaseOrderDocument) {
636        List returnList = new ArrayList();
637        for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
638            OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
639            if (item.isItemActiveIndicator()) {
640                returnList.add(item);
641            }
642        }
643        return returnList;
644    }
645
646    /**
647     * Gets the active items in this Purchase Order, and sets up the alternate amount for GL entry creation.
648     *
649     * @return the list of all active items in this Purchase Order.
650     */
651    @Override
652    public List getItemsActiveOnlySetupAlternateAmount(PurchaseOrderDocument purchaseOrderDocument) {
653        List returnList = new ArrayList();
654        for (Iterator iter = purchaseOrderDocument.getItems().iterator(); iter.hasNext(); ) {
655            OlePurchaseOrderItem item = (OlePurchaseOrderItem) iter.next();
656            if (item.isItemActiveIndicator()) {
657                for (Object element : item.getSourceAccountingLines()) {
658                    PurchaseOrderAccount account = (PurchaseOrderAccount) element;
659                    account.setAlternateAmountForGLEntryCreation(account.getItemAccountOutstandingEncumbranceAmount());
660                }
661                returnList.add(item);
662            }
663        }
664        return returnList;
665    }
666
667    @Override
668    public boolean getAdditionalChargesExist(PurchaseOrderDocument purchaseOrderDocument) {
669        List<OlePurchaseOrderItem> items = purchaseOrderDocument.getItems();
670        for (OlePurchaseOrderItem item : items) {
671            if ((item != null) &&
672                    (item.getItemType() != null) &&
673                    (item.getItemType().isAdditionalChargeIndicator()) &&
674                    (item.getExtendedPrice() != null) &&
675                    (!KualiDecimal.ZERO.equals(item.getExtendedPrice()))) {
676                return true;
677            }
678        }
679        return false;
680    }
681}