001/*
002 * Copyright 2011 The Kuali Foundation.
003 *
004 * Licensed under the Educational Community License, Version 1.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/ecl1.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.module.purap.document.service.impl;
017
018import org.apache.commons.lang.StringEscapeUtils;
019import org.apache.commons.lang.StringUtils;
020import org.apache.commons.lang.time.DateUtils;
021import org.kuali.ole.DocumentUniqueIDPrefix;
022import org.kuali.ole.docstore.common.document.Bib;
023import org.kuali.ole.docstore.common.document.content.bib.marc.BibMarcRecord;
024import org.kuali.ole.docstore.common.document.content.bib.marc.DataField;
025import org.kuali.ole.docstore.engine.service.storage.rdbms.pojo.BibInfoRecord;
026import org.kuali.ole.module.purap.businessobject.PurApItem;
027import org.kuali.ole.module.purap.businessobject.PurchaseOrderType;
028import org.kuali.ole.module.purap.document.*;
029import org.kuali.ole.module.purap.document.service.OlePurapService;
030import org.kuali.ole.select.OleSelectConstant;
031import org.kuali.ole.select.businessobject.*;
032import org.kuali.ole.select.document.OleInvoiceDocument;
033import org.kuali.ole.select.document.OlePaymentRequestDocument;
034import org.kuali.ole.select.document.OleRequisitionDocument;
035import org.kuali.ole.sys.OLEConstants;
036import org.kuali.ole.sys.context.SpringContext;
037import org.kuali.ole.vnd.businessobject.VendorDetail;
038import org.kuali.rice.core.api.datetime.DateTimeService;
039import org.kuali.rice.core.api.util.type.KualiDecimal;
040import org.kuali.rice.coreservice.framework.parameter.ParameterService;
041import org.kuali.rice.coreservice.impl.parameter.ParameterBo;
042import org.kuali.rice.kim.api.identity.Person;
043import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
044import org.kuali.rice.krad.service.BusinessObjectService;
045import org.kuali.rice.krad.service.DocumentHeaderService;
046import org.kuali.rice.krad.service.KRADServiceLocator;
047import org.kuali.rice.krad.util.GlobalVariables;
048
049import java.math.BigDecimal;
050import java.util.*;
051
052public class OlePurapServiceImpl implements OlePurapService {
053
054    protected static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePurapServiceImpl.class);
055    protected ParameterService parameterService;
056    private static transient BusinessObjectService businessObjectService;
057    private DateTimeService dateTimeService;
058    private static final String timeStampFormat = "MMddyyHHmm";
059
060    public BusinessObjectService getBusinessObjectService() {
061        if (businessObjectService == null) {
062            businessObjectService = SpringContext.getBean(BusinessObjectService.class);
063        }
064        return businessObjectService;
065    }
066
067    public DateTimeService getDateTimeService() {
068        if (dateTimeService == null) {
069            dateTimeService = SpringContext.getBean(DateTimeService.class);
070        }
071        return dateTimeService;
072    }
073
074    public void setBusinessObjectService(BusinessObjectService businessObjectService) {
075        this.businessObjectService = businessObjectService;
076    }
077
078    public void setParameterService(ParameterService parameterService) {
079        this.parameterService = parameterService;
080    }
081    @Override
082    public BigDecimal calculateDiscount(OleRequisitionItem oleRequisition) {
083
084        if (oleRequisition.getItemListPrice() != null && oleRequisition.getItemDiscountType() != null) {
085
086            if (oleRequisition.getItemDiscount() == null) {
087                oleRequisition.setItemDiscount(new KualiDecimal(0));
088            }
089            if (oleRequisition.getItemDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
090                LOG.debug("###### Percentage ##### ");
091                return oleRequisition.getItemListPrice().bigDecimalValue().subtract((oleRequisition.getItemDiscount().bigDecimalValue().multiply(new BigDecimal(0.01))).multiply(oleRequisition.getItemListPrice().bigDecimalValue()));
092            } else {
093                LOG.debug("###### Dollor ##### ");
094                if (LOG.isDebugEnabled()) {
095                    LOG.debug("oleRequisition.getItemDiscountType()**********" + oleRequisition.getItemDiscountType());
096                }
097                return oleRequisition.getItemListPrice().bigDecimalValue().subtract(oleRequisition.getItemDiscount().bigDecimalValue());
098            }
099        } else {
100            oleRequisition.setItemListPrice(new KualiDecimal(0.0));
101            return new BigDecimal(0.0);
102        }
103
104    }
105
106    @Override
107    public BigDecimal calculateDiscount(OlePurchaseOrderItem olePurchaseOrder) {
108
109        if (olePurchaseOrder.getItemListPrice() != null && olePurchaseOrder.getItemDiscountType() != null) {
110            if (olePurchaseOrder.getItemDiscount() == null) {
111                olePurchaseOrder.setItemDiscount(new KualiDecimal(0));
112            }
113            if (olePurchaseOrder.getItemDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
114                return olePurchaseOrder.getItemListPrice().bigDecimalValue().subtract((olePurchaseOrder.getItemDiscount().bigDecimalValue().multiply(new BigDecimal(0.01))).multiply(olePurchaseOrder.getItemListPrice().bigDecimalValue()));
115            } else {
116                return olePurchaseOrder.getItemListPrice().bigDecimalValue().subtract(olePurchaseOrder.getItemDiscount().bigDecimalValue());
117            }
118        } else {
119            olePurchaseOrder.setItemListPrice(new KualiDecimal(0.0));
120            return new BigDecimal(0.0);
121        }
122
123    }
124
125
126// Foreign Currency Conversion
127
128    @Override
129    public OleRequisitionItem calculateForeignCurrency(OleRequisitionItem oleRequisition) {
130        if (oleRequisition.getItemForeignListPrice() != null && oleRequisition.getItemForeignDiscountType() != null) {
131            if (oleRequisition.getItemForeignDiscount() == null) {
132                oleRequisition.setItemForeignDiscount(new KualiDecimal(0));
133            }
134            if (oleRequisition.getItemForeignDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
135                BigDecimal calculatedForeignDiscountAmt = oleRequisition.getItemForeignDiscount().bigDecimalValue().multiply(new BigDecimal(0.01)).multiply(oleRequisition.getItemForeignListPrice().bigDecimalValue());
136                oleRequisition.setItemForeignDiscountAmt(new KualiDecimal(calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
137                oleRequisition.setItemForeignUnitCost(oleRequisition.getItemForeignListPrice().subtract(oleRequisition.getItemForeignDiscountAmt()));
138                return oleRequisition;
139            } else {
140                oleRequisition.setItemForeignDiscountAmt((oleRequisition.getItemForeignDiscount()));
141                oleRequisition.setItemForeignUnitCost(new KualiDecimal(oleRequisition.getItemForeignListPrice().bigDecimalValue().subtract(oleRequisition.getItemForeignDiscount().bigDecimalValue())));
142                return oleRequisition;
143            }
144        } else {
145            return oleRequisition;
146        }
147    }
148
149    @Override
150    public OlePurchaseOrderItem calculateForeignCurrency(OlePurchaseOrderItem olePurchaseOrder) {
151        if (olePurchaseOrder.getItemForeignListPrice() != null && olePurchaseOrder.getItemForeignDiscountType() != null) {
152            if (olePurchaseOrder.getItemForeignDiscount() == null) {
153                olePurchaseOrder.setItemForeignDiscount(new KualiDecimal(0));
154            }
155            if (olePurchaseOrder.getItemForeignDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
156                BigDecimal calculatedForeignDiscountAmt = olePurchaseOrder.getItemForeignDiscount().bigDecimalValue().multiply(new BigDecimal(0.01)).multiply(olePurchaseOrder.getItemForeignListPrice().bigDecimalValue());
157                olePurchaseOrder.setItemForeignDiscountAmt(new KualiDecimal(calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
158                olePurchaseOrder.setItemForeignUnitCost(olePurchaseOrder.getItemForeignListPrice().subtract(olePurchaseOrder.getItemForeignDiscountAmt()));
159                return olePurchaseOrder;
160            } else {
161                olePurchaseOrder.setItemForeignDiscountAmt(olePurchaseOrder.getItemForeignDiscount());
162                olePurchaseOrder.setItemForeignUnitCost(olePurchaseOrder.getItemForeignListPrice().subtract(olePurchaseOrder.getItemForeignDiscount()));
163                return olePurchaseOrder;
164            }
165        } else {
166            return olePurchaseOrder;
167        }
168    }
169
170    @Override
171    public BigDecimal calculateDiscount(OlePaymentRequestItem olePaymentRequestOrder) {
172
173        if (olePaymentRequestOrder.getItemListPrice() != null) {
174            if (olePaymentRequestOrder.getItemDiscount() == null) {
175                olePaymentRequestOrder.setItemDiscount(new KualiDecimal(0));
176            }
177            if (olePaymentRequestOrder.getItemDiscountType() != null && olePaymentRequestOrder.getItemDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
178                return olePaymentRequestOrder.getItemListPrice().bigDecimalValue().subtract((olePaymentRequestOrder.getItemDiscount().bigDecimalValue().multiply(new BigDecimal(0.01))).multiply(olePaymentRequestOrder.getItemListPrice().bigDecimalValue()));
179            } else {
180                return olePaymentRequestOrder.getItemListPrice().bigDecimalValue().subtract(olePaymentRequestOrder.getItemDiscount().bigDecimalValue());
181            }
182        } else {
183            olePaymentRequestOrder.setItemListPrice(new KualiDecimal(0.0));
184            return new BigDecimal(0.0);
185        }
186
187    }
188
189    @Override
190    public BigDecimal calculateDiscount(OleInvoiceItem oleInvoiceOrder) {
191
192        if (oleInvoiceOrder.getItemListPrice() != null) {
193            if (oleInvoiceOrder.getItemDiscount() == null) {
194                oleInvoiceOrder.setItemDiscount(new KualiDecimal(0));
195            }
196            if (oleInvoiceOrder.getItemDiscountType() != null && oleInvoiceOrder.getItemDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
197                return oleInvoiceOrder.getItemListPrice().bigDecimalValue().subtract((oleInvoiceOrder.getItemDiscount().bigDecimalValue().multiply(new BigDecimal(0.01))).multiply(oleInvoiceOrder.getItemListPrice().bigDecimalValue()));
198            } else {
199                return oleInvoiceOrder.getItemListPrice().bigDecimalValue().subtract(oleInvoiceOrder.getItemDiscount().bigDecimalValue());
200            }
201        } else {
202            oleInvoiceOrder.setItemListPrice(new KualiDecimal(0.0));
203            return new BigDecimal(0.0);
204        }
205
206    }
207
208    @Override
209    public OlePaymentRequestItem calculateForeignCurrency(OlePaymentRequestItem item) {
210        if (item.getItemForeignListPrice() != null) {
211            if (item.getItemForeignDiscount() == null) {
212                item.setItemForeignDiscount(new KualiDecimal(0));
213            }
214            if (item.getItemForeignDiscountType() != null && item.getItemForeignDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
215                BigDecimal calculatedForeignDiscountAmt = item.getItemForeignDiscount().bigDecimalValue().multiply(new BigDecimal(0.01)).multiply(item.getItemForeignListPrice().bigDecimalValue());
216                item.setItemForeignDiscountAmt(new KualiDecimal(calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
217                item.setItemForeignUnitCost(item.getItemForeignListPrice().subtract(item.getItemForeignDiscountAmt()));
218                return item;
219            } else {
220                item.setItemForeignDiscountAmt(item.getItemForeignDiscount());
221                item.setItemForeignUnitCost(item.getItemForeignListPrice().subtract(item.getItemForeignDiscount()));
222                return item;
223            }
224        } else {
225            return item;
226        }
227    }
228
229
230    @Override
231    public OleInvoiceItem calculateForeignCurrency(OleInvoiceItem item) {
232        if (item.getItemForeignListPrice() != null) {
233            if (item.getItemForeignDiscount() == null) {
234                item.setItemForeignDiscount(new KualiDecimal(0));
235            }
236            if (item.getItemForeignDiscountType() != null && item.getItemForeignDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
237                BigDecimal calculatedForeignDiscountAmt = item.getItemForeignDiscount().bigDecimalValue().multiply(new BigDecimal(0.01)).multiply(item.getItemForeignListPrice().bigDecimalValue());
238                item.setItemForeignDiscountAmt(new KualiDecimal(calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
239                item.setItemForeignUnitCost(item.getItemForeignListPrice().subtract(item.getItemForeignDiscountAmt()));
240                return item;
241            } else {
242                item.setItemForeignDiscountAmt(item.getItemForeignDiscount());
243                item.setItemForeignUnitCost(item.getItemForeignListPrice().subtract(item.getItemForeignDiscount()));
244                return item;
245            }
246        } else {
247            return item;
248        }
249    }
250
251
252    /**
253     * Returns first, middle and last initials of logged in user
254     * to be appended in the document description
255     *
256     * @return initials of logged in user
257     */
258    public String getOperatorInitials() {
259        LOG.debug("Inside getOperatorInitials()");
260        StringBuffer operatorInitials = new StringBuffer();
261        Person person = GlobalVariables.getUserSession().getPerson();
262        operatorInitials.append(StringUtils.isEmpty(person.getFirstName()) ? "" : person.getFirstName().toLowerCase().charAt(0));
263        operatorInitials.append(StringUtils.isEmpty(person.getMiddleName()) ? "" : person.getMiddleName().toLowerCase().charAt(0));
264        operatorInitials.append(StringUtils.isEmpty(person.getLastName()) ? "" : person.getLastName().toLowerCase().charAt(0));
265        LOG.debug("End of getOperatorInitials()");
266        return operatorInitials.toString();
267    }
268
269    public OleCreditMemoItem calculateForeignCurrency(OleCreditMemoItem oleCreditMemoItem) {
270        if (oleCreditMemoItem.getItemForeignListPrice() != null && oleCreditMemoItem.getItemForeignDiscountType() != null) {
271            if (oleCreditMemoItem.getItemForeignDiscount() == null) {
272                oleCreditMemoItem.setItemForeignDiscount(new KualiDecimal(0));
273            }
274            if (oleCreditMemoItem.getItemForeignDiscountType().equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) {
275                BigDecimal calculatedForeignDiscountAmt = oleCreditMemoItem.getItemForeignDiscount().bigDecimalValue().multiply(new BigDecimal(0.01)).multiply(oleCreditMemoItem.getItemForeignListPrice().bigDecimalValue());
276                oleCreditMemoItem.setItemForeignDiscountAmt(new KualiDecimal(calculatedForeignDiscountAmt.setScale(KualiDecimal.SCALE, KualiDecimal.ROUND_BEHAVIOR)));
277                oleCreditMemoItem.setItemForeignUnitCost(oleCreditMemoItem.getItemForeignListPrice().subtract(oleCreditMemoItem.getItemForeignDiscountAmt()));
278                return oleCreditMemoItem;
279            } else {
280                oleCreditMemoItem.setItemForeignDiscountAmt(oleCreditMemoItem.getItemForeignDiscount());
281                oleCreditMemoItem.setItemForeignUnitCost(oleCreditMemoItem.getItemForeignListPrice().subtract(oleCreditMemoItem.getItemForeignDiscount()));
282                return oleCreditMemoItem;
283            }
284        } else {
285            return oleCreditMemoItem;
286        }
287    }
288
289    /**
290     * This method returns the section Name that are to be collapsed while opening the document
291     * @param document
292     * @return collapseSections
293     */
294    public void getInitialCollapseSections(PurchasingAccountsPayableDocument document) {
295        LOG.debug("Inside getInitialCollapseSections()");
296        String[] collapseSections = new String[]{};
297        try {
298            if (document instanceof RequisitionDocument) {
299                OleRequisitionDocument requisitionDocument = (OleRequisitionDocument)document;
300                collapseSections = parameterService.getParameterValuesAsString(RequisitionDocument.class,
301                        OLEConstants.INITIAL_COLLAPSE_SECTIONS).toArray(new String[]{});
302                requisitionDocument.setOverviewFlag(canCollapse(OLEConstants.OVERVIEW_SECTION, collapseSections));
303                requisitionDocument.setDeliveryFlag(canCollapse(OLEConstants.DELIVERY_SECTION, collapseSections));
304                requisitionDocument.setVendorFlag(canCollapse(OLEConstants.VENDOR_SECTION, collapseSections));
305                requisitionDocument.setTitlesFlag(canCollapse(OLEConstants.TITLES_SECTION, collapseSections));
306                requisitionDocument.setPaymentInfoFlag(canCollapse(OLEConstants.PAYMENT_INFO_SECTION, collapseSections));
307                requisitionDocument.setAdditionalInstitutionalInfoFlag(canCollapse(OLEConstants.ADDITIONAL_INSTUT_SECTION, collapseSections));
308                requisitionDocument.setAccountSummaryFlag(canCollapse(OLEConstants.ACCOUNT_SUMMARY_SECTION, collapseSections));
309                requisitionDocument.setRelatedDocumentsFlag(canCollapse(OLEConstants.RELATED_DOCUMENT_SECTION, collapseSections));
310                requisitionDocument.setPaymentHistoryFlag(canCollapse(OLEConstants.PAYMENT_HISTORY_SECTION, collapseSections));
311                requisitionDocument.setNotesAndAttachmentFlag(canCollapse(OLEConstants.NOTES_AND_ATTACH_SECTION, collapseSections));
312                requisitionDocument.setAdHocRecipientsFlag(canCollapse(OLEConstants.ADHOC_RECIPIENT_SECTION, collapseSections));
313                requisitionDocument.setRouteLogFlag(canCollapse(OLEConstants.ROUTE_LOG_SECTION, collapseSections));
314            }
315            else if (document instanceof PurchaseOrderDocument) {
316                PurchaseOrderDocument poDocument = (PurchaseOrderDocument)document;
317                collapseSections = parameterService.getParameterValuesAsString(PurchaseOrderDocument.class,
318                        OLEConstants.INITIAL_COLLAPSE_SECTIONS).toArray(new String[]{});
319                poDocument.setOverviewFlag(canCollapse(OLEConstants.OVERVIEW_SECTION,collapseSections));
320                poDocument.setDeliveryFlag(canCollapse(OLEConstants.DELIVERY_SECTION,collapseSections));
321                poDocument.setVendorFlag(canCollapse(OLEConstants.VENDOR_SECTION,collapseSections));
322                poDocument.setTitlesFlag(canCollapse(OLEConstants.TITLES_SECTION,collapseSections));
323                poDocument.setPaymentInfoFlag(canCollapse(OLEConstants.PAYMENT_INFO_SECTION,collapseSections));
324                poDocument.setAdditionalInstitutionalInfoFlag(canCollapse(OLEConstants.ADDITIONAL_INSTUT_SECTION,collapseSections));
325                poDocument.setAccountSummaryFlag(canCollapse(OLEConstants.ACCOUNT_SUMMARY_SECTION,collapseSections));
326                poDocument.setRelatedDocumentsFlag(canCollapse(OLEConstants.RELATED_DOCUMENT_SECTION,collapseSections));
327                poDocument.setPaymentHistoryFlag(canCollapse(OLEConstants.PAYMENT_HISTORY_SECTION,collapseSections));
328                poDocument.setNotesAndAttachmentFlag(canCollapse(OLEConstants.NOTES_AND_ATTACH_SECTION,collapseSections));
329                poDocument.setAdHocRecipientsFlag(canCollapse(OLEConstants.ADHOC_RECIPIENT_SECTION,collapseSections));
330                poDocument.setRouteLogFlag(canCollapse(OLEConstants.ROUTE_LOG_SECTION,collapseSections));
331            }
332            else if (document instanceof PaymentRequestDocument) {
333                PaymentRequestDocument paymentRequestDoc = (PaymentRequestDocument)document;
334                collapseSections = parameterService.getParameterValuesAsString(PaymentRequestDocument.class,
335                        OLEConstants.INITIAL_COLLAPSE_SECTIONS).toArray(new String[]{});
336                paymentRequestDoc.setOverviewFlag(canCollapse(OLEConstants.OVERVIEW_SECTION,collapseSections));
337                paymentRequestDoc.setDeliveryFlag(canCollapse(OLEConstants.DELIVERY_SECTION,collapseSections));
338                paymentRequestDoc.setInvoiceInfoFlag(canCollapse(OLEConstants.INVOICE_SECTION,collapseSections));
339                paymentRequestDoc.setProcessItemsFlag(canCollapse(OLEConstants.PROCESS_ITEM_SECTION,collapseSections));
340                paymentRequestDoc.setAccountSummaryFlag(canCollapse(OLEConstants.ACCOUNT_SUMMARY_SECTION,collapseSections));
341                paymentRequestDoc.setRelatedDocumentsFlag(canCollapse(OLEConstants.RELATED_DOCUMENT_SECTION,collapseSections));
342                paymentRequestDoc.setPaymentHistoryFlag(canCollapse(OLEConstants.PAYMENT_HISTORY_SECTION,collapseSections));
343                paymentRequestDoc.setGeneralEntriesFlag(canCollapse(OLEConstants.GENERAL_ENTRY_SECTION,collapseSections));
344                paymentRequestDoc.setNotesAndAttachmentFlag(canCollapse(OLEConstants.NOTES_AND_ATTACH_SECTION,collapseSections));
345                paymentRequestDoc.setAdHocRecipientsFlag(canCollapse(OLEConstants.ADHOC_RECIPIENT_SECTION,collapseSections));
346                paymentRequestDoc.setRouteLogFlag(canCollapse(OLEConstants.ROUTE_LOG_SECTION,collapseSections));
347            }
348            else if (document instanceof VendorCreditMemoDocument) {
349                VendorCreditMemoDocument vmDocument = (VendorCreditMemoDocument)document;
350                collapseSections = parameterService.getParameterValuesAsString(VendorCreditMemoDocument.class,
351                        OLEConstants.INITIAL_COLLAPSE_SECTIONS).toArray(new String[]{});
352                vmDocument.setOverviewFlag(canCollapse(OLEConstants.OVERVIEW_SECTION,collapseSections));
353                vmDocument.setVendorFlag(canCollapse(OLEConstants.VENDOR_SECTION,collapseSections));
354                vmDocument.setCreditMemoInfoFlag(canCollapse(OLEConstants.VENDOR_SECTION,collapseSections));
355                vmDocument.setProcessItemsFlag(canCollapse(OLEConstants.PROCESS_ITEM_SECTION,collapseSections));
356                vmDocument.setAccountSummaryFlag(canCollapse(OLEConstants.ACCOUNT_SUMMARY_SECTION,collapseSections));
357                vmDocument.setRelatedDocumentsFlag(canCollapse(OLEConstants.RELATED_DOCUMENT_SECTION,collapseSections));
358                vmDocument.setPaymentHistoryFlag(canCollapse(OLEConstants.PAYMENT_HISTORY_SECTION,collapseSections));
359                vmDocument.setGeneralEntriesFlag(canCollapse(OLEConstants.GENERAL_ENTRY_SECTION,collapseSections));
360                vmDocument.setNotesAndAttachmentFlag(canCollapse(OLEConstants.NOTES_AND_ATTACH_SECTION,collapseSections));
361                vmDocument.setAdHocRecipientsFlag(canCollapse(OLEConstants.ADHOC_RECIPIENT_SECTION,collapseSections));
362                vmDocument.setRouteLogFlag(canCollapse(OLEConstants.ROUTE_LOG_SECTION,collapseSections));
363            }
364
365        }
366        catch (Exception e) {
367            LOG.error("Error while getting the default Collapse section on PurchasingAccountsPayable Document");
368            throw new RuntimeException(e);
369        }
370        LOG.debug("Leaving getInitialCollapseSections()");
371
372    }
373
374    private boolean canCollapse(String sectionName, String[] collapseSections) {
375        LOG.debug("Inside method canCollapse()");
376        List<String> sectionLists = Arrays.asList(collapseSections);
377        if (sectionLists.contains(sectionName)) {
378            return false;
379        }
380        return true;
381    }
382
383
384    /*
385    Method to return the First and Last name of a patron given the patronid
386    This method is used only for the purpose of displaying the Patron name information on the Requisition Document..
387     */
388    public String getPatronName(String patronId){
389        StringBuffer patronName = new StringBuffer();
390        try{
391            if(LOG.isDebugEnabled()){
392                LOG.debug("Getting name for patron -" + patronId);
393            }
394            Map<String,String> map=new HashMap<String,String>();
395            map.put("entityId",patronId);
396            EntityNameBo entityNameBo=(EntityNameBo) KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(EntityNameBo.class,map);
397            patronName.append(entityNameBo.getLastName()).append(", ").append(entityNameBo.getFirstName());
398            if(LOG.isDebugEnabled()){
399                LOG.debug("Returning Name:" + patronName + ": for patronId :" + patronId + ":");
400            }
401        } catch(Exception e){
402            LOG.error("Exception while trying to get name for patron ",e);
403        }
404        return patronName.toString();
405    }//end getPatronName method...
406
407    /**
408     * This method is used to set the BibMarcRecord which in turn used for creation of Bib record into docstore.
409     * @param bibMarcRecord
410     * @param bibInfoBean
411     */
412    public void setBibMarcRecord(BibMarcRecord bibMarcRecord,BibInfoBean bibInfoBean){
413        LOG.debug("Inside setBibMarcRecord method.....");
414        List<org.kuali.ole.docstore.common.document.content.bib.marc.DataField> dataFieldList = new ArrayList<DataField>();
415        if(bibInfoBean.getTitle() != null){
416            dataFieldList.add(setDataField(org.kuali.ole.OLEConstants.MARC_EDITOR_TITLE_245,bibInfoBean.getTitle()));
417        }
418        if(bibInfoBean.getAuthor() !=null){
419            dataFieldList.add(setDataField(org.kuali.ole.OLEConstants.MARC_EDITOR_TITLE_100,bibInfoBean.getAuthor()));
420        }
421        bibMarcRecord.setDataFields(dataFieldList);
422        LOG.debug("setBibMarcRecord method successfull.....");
423    }
424
425    /**
426     * This method is used the set the Datafield for the given tag and value
427     * @param tag
428     * @param value
429     * @return
430     */
431    private DataField setDataField(String tag,String value){
432        if(LOG.isDebugEnabled()){
433            LOG.debug("inside setDataField method.....");
434            LOG.debug("tag---->"+tag+" "+"value---->"+value);
435        }
436        DataField dataField = new DataField();
437        dataField.setTag(tag);
438        List<org.kuali.ole.docstore.common.document.content.bib.marc.SubField> subFields = new ArrayList<org.kuali.ole.docstore.common.document.content.bib.marc.SubField>();
439        org.kuali.ole.docstore.common.document.content.bib.marc.SubField subField = new org.kuali.ole.docstore.common.document.content.bib.marc.SubField();
440        subField.setCode(org.kuali.ole.OLEConstants.A);
441        subField.setValue(value);
442        subFields.add(subField);
443        dataField.setSubFields(subFields);
444        return dataField;
445    }
446
447    /**
448     * This method is to retrieve the Invoice Documents related to Requisition
449     * @param purApItem
450     */
451    public void setInvoiceDocumentsForRequisition(PurApItem purApItem) {
452        OleRequisitionItem singleItem = (OleRequisitionItem) purApItem;
453        Map<String, OleInvoiceDocument> paidDocuments = new HashMap<String, OleInvoiceDocument>();
454        Map<String, OlePaymentRequestDocument> paymentRequests = new HashMap<String, OlePaymentRequestDocument>();
455        for (OleCopy oleCopy : singleItem.getCopyList()) {
456            if (oleCopy.getOlePaidCopies().size() > 0) {
457                for (OLEPaidCopy olePaidCopy : oleCopy.getOlePaidCopies()) {
458                    OleInvoiceDocument invoiceDocument = null;
459                    if (olePaidCopy.getInvoiceItemId() != null &&
460                            paidDocuments.containsKey(olePaidCopy.getInvoiceItemId().toString())) {
461                        OleInvoiceItem invoiceItem = olePaidCopy.getInvoiceItem();
462                        invoiceDocument = paidDocuments.get(olePaidCopy.getInvoiceItemId());
463                        if (invoiceItem.getPoItemIdentifier().compareTo(oleCopy.getPoItemId()) == 0 && invoiceDocument != null) {
464                            ((OleInvoiceItem)invoiceDocument.getItem(invoiceItem.getItemLineNumber())).setRequisitionItemIdentifier(oleCopy.getReqItemId());
465                        }
466                    }
467                    else if (olePaidCopy.getInvoiceItem().getInvoiceDocument() != null && olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier() != null
468                            && (paidDocuments.containsKey(olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier().toString()))) {
469                        OleInvoiceItem invoiceItem = olePaidCopy.getInvoiceItem();
470                        invoiceDocument = paidDocuments.get(olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier());
471                        if (invoiceItem.getPoItemIdentifier().compareTo(oleCopy.getPoItemId()) == 0 && invoiceDocument != null) {
472                            ((OleInvoiceItem)invoiceDocument.getItem(invoiceItem.getItemLineNumber())).setRequisitionItemIdentifier(oleCopy.getReqItemId());
473                        }
474                    }
475                    else {
476                        if (olePaidCopy.getInvoiceItem() != null && olePaidCopy.getInvoiceItem().isDebitItem()) {
477                            OleInvoiceItem invoiceItem = olePaidCopy.getInvoiceItem();
478                            invoiceDocument = (OleInvoiceDocument)olePaidCopy.getInvoiceItem().getInvoiceDocument();
479                            if (invoiceDocument != null && SpringContext.getBean(DocumentHeaderService.class) != null) {
480                                invoiceDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(invoiceDocument.getDocumentNumber()));
481                                if (invoiceItem.getPoItemIdentifier().compareTo(oleCopy.getPoItemId()) == 0) {
482                                    invoiceItem.setRequisitionItemIdentifier(oleCopy.getReqItemId());
483                                }
484                                paidDocuments.put(invoiceDocument.getPurapDocumentIdentifier().toString(),
485                                        invoiceDocument);
486                                invoiceDocument.setPaymentRequestDocuments(new ArrayList<OlePaymentRequestDocument>());
487                            }
488                        }
489                    }
490                    if (invoiceDocument != null && olePaidCopy.getPreqItem() != null) {
491                        OlePaymentRequestDocument preq = (OlePaymentRequestDocument) olePaidCopy.getPreqItem().getPaymentRequestDocument();
492                        if (preq != null && !paymentRequests.containsKey(preq.getDocumentNumber())) {
493                            paymentRequests.put(preq.getDocumentNumber(), preq);
494                            invoiceDocument.getPaymentRequestDocuments().add(preq);
495                        }
496                    }
497                    if (invoiceDocument != null && SpringContext.getBean(DocumentHeaderService.class) != null) {
498                        invoiceDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(invoiceDocument.getDocumentNumber()));
499                        paidDocuments.put(invoiceDocument.getPurapDocumentIdentifier().toString(),
500                                invoiceDocument);
501                    }
502                }
503            }
504        }
505        Collection collection = (Collection) (paidDocuments.values());
506        List list = new ArrayList(collection);
507        singleItem.setInvoiceDocuments(list);
508    }
509
510    /**
511     * This method is to retrieve the Invoice Documents related to PO
512     * @param purApItem
513     */
514    public void setInvoiceDocumentsForPO(PurApItem purApItem) {
515        OlePurchaseOrderItem singleItem = (OlePurchaseOrderItem) purApItem;
516        Map<String, OleInvoiceDocument> paidDocuments = new HashMap<String, OleInvoiceDocument>();
517        Map<String, OlePaymentRequestDocument> paymentRequests = new HashMap<String, OlePaymentRequestDocument>();
518        for (OleCopy oleCopy : singleItem.getCopyList()) {
519            if (oleCopy.getOlePaidCopies().size() > 0) {
520                for (OLEPaidCopy olePaidCopy : oleCopy.getOlePaidCopies()) {
521                    OleInvoiceDocument invoiceDocument = null;
522                    if (olePaidCopy.getInvoiceItemId() != null &&
523                            paidDocuments.containsKey(olePaidCopy.getInvoiceItemId().toString())) {
524                        invoiceDocument = paidDocuments.get(olePaidCopy.getInvoiceItemId());
525                    }
526                    else if (olePaidCopy.getInvoiceItem().getInvoiceDocument() != null && olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier() != null
527                            && (paidDocuments.containsKey(olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier().toString()))) {
528                        invoiceDocument = paidDocuments.get(olePaidCopy.getInvoiceItem().getInvoiceDocument().getPurapDocumentIdentifier());
529                    }
530                    else {
531                        if (olePaidCopy.getInvoiceItem() != null) {
532                            invoiceDocument = (OleInvoiceDocument)olePaidCopy.getInvoiceItem().getInvoiceDocument();
533                            if (invoiceDocument != null && SpringContext.getBean(DocumentHeaderService.class) != null) {
534                                invoiceDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(invoiceDocument.getDocumentNumber()));
535                                paidDocuments.put(invoiceDocument.getPurapDocumentIdentifier().toString(),
536                                        invoiceDocument);
537                                invoiceDocument.setPaymentRequestDocuments(new ArrayList<OlePaymentRequestDocument>());
538                            }
539                        }
540                    }
541                    if (invoiceDocument != null && olePaidCopy.getPreqItem() != null) {
542                        OlePaymentRequestDocument preq = (OlePaymentRequestDocument)olePaidCopy.getPreqItem().getPaymentRequestDocument();
543                        if (preq != null && !paymentRequests.containsKey(preq.getDocumentNumber())) {
544                            paymentRequests.put(preq.getDocumentNumber(),preq);
545                            invoiceDocument.getPaymentRequestDocuments().add(preq);
546                        }
547                    }
548                    if (invoiceDocument != null && SpringContext.getBean(DocumentHeaderService.class) != null) {
549                        invoiceDocument.setDocumentHeader(SpringContext.getBean(DocumentHeaderService.class).getDocumentHeaderById(invoiceDocument.getDocumentNumber()));
550                        paidDocuments.put(invoiceDocument.getPurapDocumentIdentifier().toString(),
551                                invoiceDocument);
552                    }
553                }
554            }
555        }
556        Collection collection = (Collection)(paidDocuments.values());
557        List list = new ArrayList(collection);
558        singleItem.setInvoiceDocuments(list);
559    }
560
561    /**
562     * This method is used to get the requestor type id for the given requestor type
563     * @param requestorType
564     * @return
565     */
566    public Integer getRequestorTypeId(String requestorType) {
567        Map<String, Object> criteria = new HashMap<String, Object>();
568        criteria.put(OleSelectConstant.REQUESTOR_TYPE, requestorType);
569        Collection<OleRequestorType> requestorTypeList = getBusinessObjectService().findMatching(OleRequestorType.class, criteria);
570        return requestorTypeList.iterator().next().getRequestorTypeId();
571    }
572
573    /**
574     * This method is used to set the claimdate for Requisition
575     * @param oleRequisitionItem
576     */
577    public void setClaimDateForReq(OleRequisitionItem oleRequisitionItem,VendorDetail vendorDetail){
578        if (vendorDetail != null) {
579            String claimInterval = vendorDetail.getClaimInterval();
580            if (StringUtils.isNotBlank(claimInterval)) {
581                Integer actIntvl = Integer.parseInt(claimInterval);
582                oleRequisitionItem.setClaimDate(new java.sql.Date(DateUtils.addDays(new java.util.Date(), actIntvl).getTime()));
583            }
584        }
585    }
586
587    /**
588     * This method is used to set the claimdate for Purchase Order
589     * @param olePurchaseOrderItem
590     */
591    public void setClaimDateForPO(OlePurchaseOrderItem olePurchaseOrderItem,VendorDetail vendorDetail){
592        if (vendorDetail != null) {
593            String claimInterval = vendorDetail.getClaimInterval();
594            if (StringUtils.isNotBlank(claimInterval)) {
595                Integer actIntvl = Integer.parseInt(claimInterval);
596                olePurchaseOrderItem.setClaimDate(new java.sql.Date(DateUtils.addDays(new java.util.Date(), actIntvl).getTime()));
597            }
598        }
599    }
600
601    /**
602     * This method is used to get the item description for the given Bib
603     * @param bib
604     */
605    public String getItemDescription(Bib bib){
606        LOG.debug("### Inside setItemDescription() of OleRequisitionDocument ###");
607        String itemDescription = ((bib.getTitle() != null && !bib.getTitle().isEmpty()) ? bib.getTitle() + "," : "") + ((bib.getAuthor() != null && !bib.getAuthor().isEmpty()) ? bib.getAuthor() + "," : "") + ((bib.getPublisher() != null && !bib.getPublisher().isEmpty()) ? bib.getPublisher() + "," : "") + ((bib.getIsbn() != null && !bib.getIsbn().isEmpty()) ? bib.getIsbn() + "," : "");
608        itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription :
609                itemDescription.substring(0, itemDescription.lastIndexOf(","));
610        if(LOG.isDebugEnabled()){
611            LOG.debug("Item Description---------->"+itemDescription);
612        }
613        StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
614        itemDescription = stringEscapeUtils.unescapeHtml(itemDescription);
615        return itemDescription;
616    }
617
618
619    public String getItemDescription(OlePurchaseOrderItem olePurchaseOrderItem) {
620        BibInfoRecord bibInfoRecord = olePurchaseOrderItem.getBibInfoRecord();
621        String itemDescription = null;
622        if (bibInfoRecord != null) {
623            olePurchaseOrderItem.setBibUUID(bibInfoRecord.getBibIdStr());
624            olePurchaseOrderItem.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(olePurchaseOrderItem.getItemTitleId()));
625
626            itemDescription = ((bibInfoRecord.getTitle() != null && !bibInfoRecord.getTitle().isEmpty()) ? bibInfoRecord.getTitle().trim() + ", " : "")
627                    + ((bibInfoRecord.getAuthor() != null && !bibInfoRecord
628                    .getAuthor().isEmpty()) ? bibInfoRecord.getAuthor().trim() + ", "
629                    : "")
630                    + ((bibInfoRecord.getPublisher() != null && !bibInfoRecord
631                    .getPublisher().isEmpty()) ? bibInfoRecord.getPublisher().trim()
632                    + ", " : "")
633                    + ((bibInfoRecord.getIsxn() != null && !bibInfoRecord.getIsxn()
634                    .isEmpty()) ? bibInfoRecord.getIsxn().trim() + ", " : "");
635        }
636        if (itemDescription != null && !(itemDescription.equals(""))) {
637            itemDescription = itemDescription.lastIndexOf(",") < 0 ? itemDescription :
638                    itemDescription.substring(0, itemDescription.lastIndexOf(","));
639            StringEscapeUtils stringEscapeUtils = new StringEscapeUtils();
640            itemDescription = stringEscapeUtils.unescapeXml(itemDescription);
641        }
642        return itemDescription;
643    }
644
645    /**
646     *  This method is used to get the Purchase Order Type object based on the given purchase order type id
647     * @param purchaseOrderTypeId
648     * @return
649     */
650    public PurchaseOrderType getPurchaseOrderType(BigDecimal purchaseOrderTypeId){
651        Map purchaseOrderTypeIdMap = new HashMap();
652        purchaseOrderTypeIdMap.put(org.kuali.ole.OLEConstants.PURCHASE_ORDER_TYPE_ID, purchaseOrderTypeId);
653        List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List) getBusinessObjectService().findMatching(PurchaseOrderType.class, purchaseOrderTypeIdMap);
654        if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
655            return purchaseOrderTypeDocumentList.get(0);
656        }else{
657            return null;
658        }
659    }
660
661    /**
662     * This method returns the system parameter value for the given input.
663     * @param name
664     * @return
665     */
666    public String getParameter(String name) {
667        LOG.debug("Inside getParameter()");
668        String parameter = "";
669        try {
670            Map<String, String> criteriaMap = new HashMap<String, String>();
671            criteriaMap.put(org.kuali.ole.OLEConstants.NAMESPACE_CODE, org.kuali.ole.OLEConstants.SELECT_NMSPC);
672            criteriaMap.put(org.kuali.ole.OLEConstants.COMPONENT_CODE, org.kuali.ole.OLEConstants.SELECT_CMPNT);
673            criteriaMap.put(org.kuali.ole.OLEConstants.NAME_SELECTOR, name);
674            List<ParameterBo> parametersList = (List<ParameterBo>) getBusinessObjectService().findMatching(ParameterBo.class, criteriaMap);
675            for (ParameterBo parameterBo : parametersList) {
676                parameter = parameterBo.getValue();
677            }
678        } catch (Exception e) {
679            LOG.error("Exception while getting parameter value", e);
680        }
681        LOG.debug("End of getParameter()");
682        return parameter;
683    }
684
685    /**
686     * This method gives the current date time value.
687     * @return
688     */
689    public String getCurrentDateTime() {
690        LOG.debug("Inside getCurrentDateTime()");
691        Date date = getDateTimeService().getCurrentDate();
692        String currentDate = SpringContext.getBean(DateTimeService.class).toString(date, timeStampFormat);
693        LOG.debug("End of getCurrentDateTime()");
694        return currentDate;
695    }
696
697    /**
698     * This method is used to set the Document Description from system parameters.
699     * @param description
700     * @param descMap
701     * @return
702     */
703    public String setDocumentDescription(String description,Map descMap){
704        LOG.debug("Inside setDocumentDescription()");
705        if(description.contains(OLEConstants.OPERATOR_INITIALS)){
706            description = description.replace(OLEConstants.OPERATOR_INITIALS,getOperatorInitials());
707        }
708        if(description.contains(OLEConstants.CURRENT_DATE_TIME)){
709            description = description.replace(OLEConstants.CURRENT_DATE_TIME,getCurrentDateTime());
710        }
711        if(descMap != null){
712            if(description.contains(OLEConstants.PO_DOC_ID)){
713                description = description.replace(OLEConstants.PO_DOC_ID,descMap.get(OLEConstants.PO_DOC_ID) != null ?descMap.get(OLEConstants.PO_DOC_ID).toString():"");
714            }
715            if(description.contains(OLEConstants.VENDOR_NAME)){
716                description = description.replace(OLEConstants.VENDOR_NAME,descMap.get(OLEConstants.VENDOR_NAME) != null ?descMap.get(OLEConstants.VENDOR_NAME).toString():"");
717            }
718            if(description.contains(OLEConstants.ORDER_TYP)){
719                description = description.replace(OLEConstants.ORDER_TYP,descMap.get(OLEConstants.ORDER_TYP) != null ? descMap.get(OLEConstants.ORDER_TYP).toString():"");
720            }
721            if(description.contains(OLEConstants.VND_ITM_ID)){
722                description = description.replace(OLEConstants.VND_ITM_ID,descMap.get(OLEConstants.VND_ITM_ID) != null ? descMap.get(OLEConstants.VND_ITM_ID).toString():"");
723            }
724        }
725        if(LOG.isDebugEnabled()) {
726            LOG.debug("Document Description ----------------->" +  description);
727        }
728        LOG.debug("End of setDocumentDescription()");
729        return description;
730
731    }
732}