View Javadoc
1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.service;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.ole.module.purap.PurapConstants;
20  import org.kuali.ole.module.purap.PurapParameterConstants;
21  import org.kuali.ole.module.purap.PurapPropertyConstants;
22  import org.kuali.ole.module.purap.businessobject.PurApItemUseTax;
23  import org.kuali.ole.module.purap.businessobject.PurchasingCapitalAssetItem;
24  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
25  import org.kuali.ole.module.purap.document.service.*;
26  import org.kuali.ole.module.purap.util.ExpiredOrClosedAccount;
27  import org.kuali.ole.module.purap.util.ExpiredOrClosedAccountEntry;
28  import org.kuali.ole.select.OleSelectConstant;
29  import org.kuali.ole.select.businessobject.*;
30  import org.kuali.ole.select.document.OleInvoiceDocument;
31  import org.kuali.ole.select.document.OleLineItemReceivingDocument;
32  import org.kuali.ole.select.document.OlePurchaseOrderDocument;
33  import org.kuali.ole.select.document.service.OleCopyHelperService;
34  import org.kuali.ole.select.document.service.OleInvoiceService;
35  import org.kuali.ole.select.document.service.OleLineItemReceivingService;
36  import org.kuali.ole.select.document.service.impl.OleLineItemReceivingServiceImpl;
37  import org.kuali.ole.sys.OLEConstants;
38  import org.kuali.ole.sys.OLEKeyConstants;
39  import org.kuali.ole.sys.businessobject.Bank;
40  import org.kuali.ole.sys.context.SpringContext;
41  import org.kuali.ole.sys.document.validation.event.AttributedBlanketApproveDocumentEvent;
42  import org.kuali.ole.sys.service.BankService;
43  import org.kuali.ole.vnd.VendorConstants;
44  import org.kuali.ole.vnd.businessobject.VendorAddress;
45  import org.kuali.ole.vnd.document.service.VendorService;
46  import org.kuali.rice.core.api.datetime.DateTimeService;
47  import org.kuali.rice.core.api.util.type.AbstractKualiDecimal;
48  import org.kuali.rice.core.api.util.type.KualiDecimal;
49  import org.kuali.rice.core.api.util.type.KualiInteger;
50  import org.kuali.rice.coreservice.framework.parameter.ParameterService;
51  import org.kuali.rice.kew.api.exception.WorkflowException;
52  import org.kuali.rice.kim.api.KimConstants;
53  import org.kuali.rice.kim.api.identity.Person;
54  import org.kuali.rice.kim.api.identity.PersonService;
55  import org.kuali.rice.kns.service.DocumentHelperService;
56  import org.kuali.rice.krad.exception.DocumentAuthorizationException;
57  import org.kuali.rice.krad.service.BusinessObjectService;
58  import org.kuali.rice.krad.service.DocumentService;
59  import org.kuali.rice.krad.service.KRADServiceLocator;
60  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
61  import org.kuali.rice.krad.util.GlobalVariables;
62  import org.kuali.rice.krad.util.KRADConstants;
63  import org.kuali.rice.krad.util.ObjectUtils;
64  
65  import java.math.BigDecimal;
66  import java.math.RoundingMode;
67  import java.sql.Date;
68  import java.util.ArrayList;
69  import java.util.HashMap;
70  import java.util.List;
71  import java.util.Map;
72  import java.util.regex.Matcher;
73  import java.util.regex.Pattern;
74  
75  public class OLEAddTitlesToInvoiceService {
76      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OLEAddTitlesToInvoiceService.class);
77      DocumentService documentService;
78      List<String> receivingDocumentsList = new ArrayList<String>();
79      boolean isAllowedPoForReceiving = false;
80      private static transient OlePurapService olePurapService;
81      private static transient OleInvoiceService invoiceService;
82  
83      public static OlePurapService getOlePurapService() {
84          if (olePurapService == null) {
85              olePurapService = SpringContext.getBean(OlePurapService.class);
86          }
87          return olePurapService;
88      }
89  
90      public List<String> getReceivingDocumentsList() {
91          return receivingDocumentsList;
92      }
93  
94      OleInvoiceDocument oleInvoiceDocument;
95  
96      public OleInvoiceDocument getOleInvoiceDocument() {
97          return oleInvoiceDocument;
98      }
99  
100     public void setOleInvoiceDocument(OleInvoiceDocument oleInvoiceDocument) {
101         this.oleInvoiceDocument = oleInvoiceDocument;
102     }
103 
104     public boolean isAllowedPoForReceiving() {
105         return isAllowedPoForReceiving;
106     }
107 
108     public void setAllowedPoForReceiving(boolean allowedPoForReceiving) {
109         isAllowedPoForReceiving = allowedPoForReceiving;
110     }
111 
112     public static OleInvoiceService getInvoiceService() {
113         if (invoiceService == null) {
114             invoiceService = SpringContext.getBean(OleInvoiceService.class);
115         }
116         return invoiceService;
117     }
118 
119     public List<OlePurchaseOrderItem> populateOlePurchaseOrderItem() {
120         List<OlePurchaseOrderItem> result = new ArrayList<OlePurchaseOrderItem>();
121         List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = (List<OlePurchaseOrderDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePurchaseOrderDocument.class);
122         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
123             String olePurchaseOrderDocumentNumber = olePurchaseOrderDocument.getDocumentNumber();
124             List<OlePurchaseOrderItem> olePurchaseOrderItems = olePurchaseOrderDocument.getItems();
125             for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
126                 if (olePurchaseOrderItem.getItemTypeCode().toString().equals("ITEM") && olePurchaseOrderItem.getDocumentNumber().equals(olePurchaseOrderDocumentNumber)) {
127                     Map<String, String> map = new HashMap<String, String>();
128                     map.put("poItemIdentifier", olePurchaseOrderItem.getItemIdentifier().toString());
129                             /*List<OleInvoiceItem> oleInvoiceItems=(List<OleInvoiceItem>) KRADServiceLocator.getBusinessObjectService().findMatching(OleInvoiceItem.class,map);*/
130                             /* olePurchaseOrderItem.setSelected(true);*/
131                            /* if(!(oleInvoiceItems.size()>0)){*/
132                     if (validateRecords(olePurchaseOrderDocument.getPurapDocumentIdentifier(), olePurchaseOrderDocument.getDocumentNumber())) {
133                         olePurchaseOrderItem.setOlePurchaseOrderDocument(olePurchaseOrderDocument);
134                         result.add(olePurchaseOrderItem);
135                     }
136                             /*}*/
137                 }
138             }
139         }
140         return result;
141     }
142 
143     public List<OlePurchaseOrderItem> populateOlePurchaseOrderItemByPoItemList(List<String> purchaseOrderItemIds, List<String> invoicePrice, List<String> foreignInvoicedPrice) {
144         List<OlePurchaseOrderItem> result = new ArrayList<OlePurchaseOrderItem>();
145       //  List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = (List<OlePurchaseOrderDocument>) KRADServiceLocator.getBusinessObjectService().findAll(OlePurchaseOrderDocument.class);
146 
147 
148         int index = 0;
149         for (String poitmId : purchaseOrderItemIds) {
150             //
151 
152             for (String purchaseOrderItemId : purchaseOrderItemIds) {
153                 HashMap itemMap = new HashMap<>();
154                 itemMap.put("itemIdentifier", purchaseOrderItemId.toString());
155                 List<OlePurchaseOrderItem> olePurchaseOrderItemList = (List<OlePurchaseOrderItem>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemMap);
156                 for (OlePurchaseOrderItem olePOItem : olePurchaseOrderItemList) {
157                     HashMap poMap = new HashMap<>();
158                     poMap.put("documentNumber", olePOItem.getDocumentNumber());
159                     List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = (List<OlePurchaseOrderDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePurchaseOrderDocument.class, poMap);
160                     for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
161                         List<OlePurchaseOrderItem> olePurchaseOrderItems = olePurchaseOrderDocument.getItems();
162                         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
163                             if (olePurchaseOrderItem.getItemIdentifier().toString().equalsIgnoreCase(poitmId.toString())) {
164                                 if (validateRecords(olePurchaseOrderDocument.getPurapDocumentIdentifier(), olePurchaseOrderDocument.getDocumentNumber())) {
165                                     olePurchaseOrderItem.setSelected(true);
166                                     olePurchaseOrderItem.setOlePurchaseOrderDocument(olePurchaseOrderDocument);
167                                     if (invoicePrice.get(index) != null && (!invoicePrice.get(index).trim().equalsIgnoreCase(""))) {
168                                         olePurchaseOrderItem.setInvoiceItemListPrice(invoicePrice.get(index));
169                                     } else {
170                                         olePurchaseOrderItem.setInvoiceItemListPrice(olePurchaseOrderItem.getExtendedPrice().toString());
171                                     }
172                                     if (foreignInvoicedPrice.get(index) != null && (!foreignInvoicedPrice.get(index).trim().equalsIgnoreCase(""))) {
173                                         olePurchaseOrderItem.setInvoiceForeignItemListPrice(foreignInvoicedPrice.get(index));
174                                     }
175                                     result.add(olePurchaseOrderItem);
176 
177                                 }
178                             }
179                         }
180 
181                     }
182                     index++;
183                 }
184             }
185         }
186         return result;
187     }
188 
189     public boolean validateSelectOlePurchaseOrderItem(List<OlePurchaseOrderItem> olePurchaseOrderItems) {
190         boolean isSuccess = false;
191 
192         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
193             if (olePurchaseOrderItem.isSelected()) {
194                 isSuccess = true;
195             }
196         }
197 
198         return isSuccess;
199     }
200 
201     public boolean validateOlePurchaseOrderItemByPoId(List<OlePurchaseOrderItem> olePurchaseOrderItems) {
202         List<OlePurchaseOrderItem> result = new ArrayList<OlePurchaseOrderItem>();
203         boolean isSuccess = true;
204         String poId = "";
205         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
206             if (poId.equalsIgnoreCase("")) {
207                 poId = olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString();
208             } else {
209                 if (!poId.equalsIgnoreCase(olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString())) {
210                     isSuccess = false;
211                 }
212             }
213 
214         }
215         return isSuccess;
216     }
217 
218     public boolean validateSelectedPurchaseOrderByVendor(List<OlePurchaseOrderItem> olePurchaseOrderItems, String vendorId) {
219         boolean isSuccess = true;
220         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
221             if (!olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorHeaderGeneratedIdentifier().toString().equalsIgnoreCase(vendorId.toString())) {
222                 isSuccess = false;
223             }
224         }
225         return isSuccess;
226     }
227 
228     public boolean validateInvoiceDocumentVendor(String invoiceDocumentNumber, List<OlePurchaseOrderItem> purchaseOrderItems) {
229         boolean isValid = true;
230         Map<String, String> map = new HashMap<String, String>();
231         map.put("documentNumber", invoiceDocumentNumber);
232         List<OleInvoiceDocument> oleInvoiceDocuments = (List<OleInvoiceDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleInvoiceDocument.class, map);
233         OleInvoiceDocument oleInvoiceDocument = oleInvoiceDocuments.get(0);
234         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
235             if (olePurchaseOrderItem.isSelected()) {
236                 if (oleInvoiceDocument.getVendorAddressGeneratedIdentifier() != null) {
237                     if (!(olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorHeaderGeneratedIdentifier().toString().equalsIgnoreCase(oleInvoiceDocument.getVendorHeaderGeneratedIdentifier().toString()))) {
238                         if (oleInvoiceDocument.getVendorAddressGeneratedIdentifier().toString().equalsIgnoreCase(olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorAddressGeneratedIdentifier().toString())) {
239                             isValid = false;
240                         }
241                     }
242                 } else {
243 
244                     if (!(olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorHeaderGeneratedIdentifier().toString().equalsIgnoreCase(oleInvoiceDocument.getVendorHeaderGeneratedIdentifier().toString()))) {
245                         isValid = false;
246                     }
247 
248                 }
249             }
250         }
251         return isValid;
252     }
253 
254     public boolean validateSelectedPurchaseOrderByVendor(List<OlePurchaseOrderItem> purchaseOrderItems) {
255         boolean isSuccess = true;
256         List<String> list = new ArrayList<String>();
257         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
258             if (olePurchaseOrderItem.isSelected()) {
259                 if (!list.contains(olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorHeaderGeneratedIdentifier().toString() + "-" + olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorDetailAssignedIdentifier())) {
260                     list.add(olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorHeaderGeneratedIdentifier().toString() + "-" + olePurchaseOrderItem.getOlePurchaseOrderDocument().getVendorDetailAssignedIdentifier());
261                 }
262             }
263         }
264         if (list.size() > 1) {
265             isSuccess = false;
266         }
267         return isSuccess;
268     }
269 
270     public boolean isSelectedAtleatOneItem(List<OlePurchaseOrderItem> purchaseOrderItems) {
271         boolean isValid = false;
272         List<OlePurchaseOrderItem> olePurchaseOrderItemSelected = new ArrayList<OlePurchaseOrderItem>();
273         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
274             if (olePurchaseOrderItem.isSelected()) {
275                 isValid = true;
276             }
277         }
278         return isValid;
279     }
280 
281     public List<OlePurchaseOrderItem> getSelectedItems(List<OlePurchaseOrderItem> purchaseOrderItems) {
282         List<OlePurchaseOrderItem> olePurchaseOrderItemSelected = new ArrayList<OlePurchaseOrderItem>();
283         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
284             if (olePurchaseOrderItem.isSelected()) {
285                 olePurchaseOrderItemSelected.add(olePurchaseOrderItem);
286             }
287         }
288         return olePurchaseOrderItemSelected;
289     }
290 
291     public boolean createNewInvoiceDocument(List<OlePurchaseOrderDocument> olePurchaseOrderDocuments, List<OlePurchaseOrderItem> olePurchaseOrderItems, String paymentMethodId, Date invoiceDate, String invoiceNumber, String vendorInvoiceAmt, String vendorForeignInvoiceAmt,String principalId) throws Exception {
292         boolean isSuccess = false;
293         try {
294 
295             OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) SpringContext.getBean(DocumentService.class).getNewDocument("OLE_PRQS");
296             java.util.Date date1 = new java.util.Date();
297             if(invoiceDate == null){
298                 oleInvoiceDocument.setInvoiceDate(new Date(SpringContext.getBean(DateTimeService.class).getCurrentDate().getTime()));
299             } else {
300                 oleInvoiceDocument.setInvoiceDate(invoiceDate);
301             }
302             oleInvoiceDocument.setInvoiceNumber(invoiceNumber);
303             oleInvoiceDocument.setPaymentMethodId(Integer.parseInt(paymentMethodId));
304             oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(vendorInvoiceAmt));
305             oleInvoiceDocument.setInvoiceAmount(vendorInvoiceAmt);
306             oleInvoiceDocument.setForeignInvoiceAmount(vendorForeignInvoiceAmt);
307             oleInvoiceDocument.setForeignVendorAmount(vendorForeignInvoiceAmt);
308             oleInvoiceDocument.initiateDocument();
309             /*oleInvoiceDocument.setInvoiceNumber("11112");*/
310 
311             /*for(OlePurchaseOrderDocument purchaseOrderDocument:olePurchaseOrderDocuments){
312                 List<OlePurchaseOrderItem> olePurchaseOrderItems1=purchaseOrderDocument.getItems();
313                 for(OlePurchaseOrderItem olePurchaseOrderItem1:olePurchaseOrderItems){
314                     for(OlePurchaseOrderItem olePurchaseOrderItem2:olePurchaseOrderItems1){
315                         if(olePurchaseOrderItem1.getItemIdentifier().toString().equalsIgnoreCase(olePurchaseOrderItem2.getItemIdentifier().toString())){
316                             olePurchaseOrderItem1.setItemForInvoice(true);
317                         }
318                     }
319                     purchaseOrderDocument.setPendingActionIndicator(false);
320 
321                 }
322 
323             }*/
324             Map<String, ExpiredOrClosedAccount> map1 = new HashMap<String, ExpiredOrClosedAccount>();
325             for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
326                 if (olePurchaseOrderDocument != null) {
327                     this.populateInvoiceFromPurchaseOrder(olePurchaseOrderDocument, oleInvoiceDocument, null, true);
328                     oleInvoiceDocument.getPurchaseOrderDocuments().add(olePurchaseOrderDocument);
329                 }
330             }
331             String description = getOlePurapService().getParameter(OLEConstants.INV_DESC);
332             description = getOlePurapService().setDocumentDescription(description,null);
333             oleInvoiceDocument.getDocumentHeader().setDocumentDescription(description);
334            // updateForeignCurrencyDetails(oleInvoiceDocument);
335             List<OleInvoiceItem> oleInvItems = oleInvoiceDocument.getItems();
336             for (OleInvoiceItem oleInvoiceItem : oleInvItems) {
337                 if(oleInvoiceItem.getItemTypeCode().equals(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE) &&
338                         StringUtils.isNotEmpty(oleInvoiceItem.getForeignUnitCost()) &&
339                         !oleInvoiceItem.getForeignUnitCost().equals("0.00")) {
340                         BigDecimal foreignUnitCost = new BigDecimal(oleInvoiceItem.getForeignUnitCost());
341                         BigDecimal exchangeRate = new BigDecimal(oleInvoiceItem.getExchangeRate());
342                         oleInvoiceItem.setItemListPrice(new KualiDecimal(foreignUnitCost.divide(exchangeRate, 2, RoundingMode.HALF_UP)));
343                         oleInvoiceItem.setItemUnitPrice(foreignUnitCost.divide(exchangeRate, 2, RoundingMode.HALF_UP));
344                 }
345                 getInvoiceService().calculateAccount(oleInvoiceItem);
346             }
347 
348             boolean isRulePassed = (KRADServiceLocatorWeb.getKualiRuleService()).applyRules(new AttributedBlanketApproveDocumentEvent("", oleInvoiceDocument));
349             if (isRulePassed) {
350                 try {
351                     getOleInvoiceServiceImpl().saveInvoiceDocument(oleInvoiceDocument);
352                 } catch (Exception e) {
353                     e.printStackTrace();
354                 }
355             } else {
356                 return false;
357             }
358             isSuccess = true;
359             if (isSuccess) {
360                 this.setOleInvoiceDocument(oleInvoiceDocument);
361             }
362 
363         } catch (WorkflowException e) {
364             LOG.error("Exception Occurred during creating Invoice Document" + e);
365             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
366         }
367 
368         return isSuccess;
369     }
370 
371     public List<OlePurchaseOrderDocument> populatePurchaseOrderDocuments(List<OlePurchaseOrderItem> purchaseOrderItems) {
372         List<OlePurchaseOrderDocument> result = new ArrayList<OlePurchaseOrderDocument>();
373         List<String> poId = new ArrayList<String>();
374         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
375             if (!poId.contains(olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString())) {
376                 if (olePurchaseOrderItem.isSelected()) {
377                     poId.add(olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString());
378                 }
379             }
380 
381         }
382         for (String id : poId) {
383             Map<String, String> map = new HashMap<String, String>();
384             map.put("purapDocumentIdentifier", id);
385             List<OlePurchaseOrderDocument> olePurchaseOrderDocuments = (List<OlePurchaseOrderDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePurchaseOrderDocument.class, map);
386             if (olePurchaseOrderDocuments.size() > 0) {
387                 for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
388                     if (olePurchaseOrderDocument.getPurchaseOrderCurrentIndicatorForSearching()) {
389                         result.add(olePurchaseOrderDocument);
390                     }
391                 }
392             }
393 
394         }
395 
396         for (OlePurchaseOrderItem purchaseOrderItem : purchaseOrderItems) {
397             if (purchaseOrderItem.isSelected()) {
398                 purchaseOrderItem.setItemForInvoice(false);
399                 for (OlePurchaseOrderDocument olePurchaseOrderDocument : result) {
400                     List<OlePurchaseOrderItem> olePurchaseOrderItems = olePurchaseOrderDocument.getItems();
401                     for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
402                         if (purchaseOrderItem.getItemIdentifier().toString().equalsIgnoreCase(olePurchaseOrderItem.getItemIdentifier().toString()) && olePurchaseOrderItem.getItemTypeCode().equals("ITEM")) {
403                             olePurchaseOrderItem.setSelected(true);
404                             olePurchaseOrderItem.setItemForInvoice(true);
405                             olePurchaseOrderItem.setInvoiceItemListPrice(purchaseOrderItem.getInvoiceItemListPrice());
406 
407                         }
408                     }
409                 }
410             }
411         }
412         return result;
413     }
414 
415 
416     public boolean addOlePurchaseOrderItemsToInvoiceDocument(List<OlePurchaseOrderDocument> olePurchaseOrderDocuments, List<OlePurchaseOrderItem> olePurchaseOrderItems, String documentNumber, String principalId, String invoiceAmt, String foreignInvoiceAmount) throws Exception {
417         boolean isSuccess = false;
418         //getting invoice document
419         Map<String, String> map = new HashMap<String, String>();
420         map.put("documentNumber", documentNumber);
421         List<OleInvoiceDocument> oleInvoiceDocuments = (List<OleInvoiceDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleInvoiceDocument.class, map);
422         OleInvoiceDocument oleInvoiceDocument = oleInvoiceDocuments.get(0);
423 
424         if (invoiceAmt != null) {
425             //oleInvoiceDocument.setInvoiceAmount(invoiceAmt);
426             oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(invoiceAmt));
427         }
428 
429         if (foreignInvoiceAmount != null) {
430             //oleInvoiceDocument.setInvoiceAmount(invoiceAmt);
431             oleInvoiceDocument.setForeignVendorAmount(foreignInvoiceAmount);
432         }
433         for (OlePurchaseOrderDocument olePurchaseOrderDocument : olePurchaseOrderDocuments) {
434             if (olePurchaseOrderDocument != null) {
435                 this.populateInvoiceFromPurchaseOrder(olePurchaseOrderDocument, oleInvoiceDocument, null, false);
436                 oleInvoiceDocument.getPurchaseOrderDocuments().add(olePurchaseOrderDocument);
437             }
438         }
439         String description = getOlePurapService().getParameter(OLEConstants.INV_DESC);
440         description = getOlePurapService().setDocumentDescription(description,null);
441         oleInvoiceDocument.getDocumentHeader().setDocumentDescription(description);
442         boolean isRulePassed = (KRADServiceLocatorWeb.getKualiRuleService()).applyRules(new AttributedBlanketApproveDocumentEvent("", oleInvoiceDocument));
443         if (isRulePassed) {
444             try {
445                 getOleInvoiceServiceImpl().saveInvoiceDocument(oleInvoiceDocument);
446             } catch (Exception e) {
447                 LOG.error("Exception Occurred during updating Invoice Document" + e);
448                 e.printStackTrace();
449             }
450         } else {
451             return false;
452         }
453         isSuccess = true;
454         if (isSuccess) {
455             this.setOleInvoiceDocument(oleInvoiceDocument);
456         }
457         return isSuccess;
458 
459 
460     }
461 
462     public boolean validateReceivingForProcess(List<OlePurchaseOrderItem> purchaseOrderItems) {
463         boolean isValid = false;
464         int selectedItem = 0;
465         int receivingExistForItem = 0;
466         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
467             if (olePurchaseOrderItem.isSelected()) {
468                 selectedItem++;
469                 Map<String, String> map = new HashMap<String, String>();
470                 map.put("purchaseOrderIdentifier", olePurchaseOrderItem
471                         .getItemIdentifier().toString());
472                 List<OleLineItemReceivingItem> oleLineItemReceivingItems = (List<OleLineItemReceivingItem>) KRADServiceLocator
473                         .getBusinessObjectService().findMatching(
474                                 OleLineItemReceivingItem.class, map);
475                 if (oleLineItemReceivingItems.size() > 0) {
476                     OleLineItemReceivingItem oleLineItemReceivingItem = oleLineItemReceivingItems.get(0);
477                     /*if (oleLineItemReceivingItem.getReceiptStatusId().toString().equalsIgnoreCase(
478                             getReceiptStatusDetails(OLEConstants.PO_RECEIPT_STATUS_FULLY_RECEIVED) + "")) {
479                         */
480                     receivingExistForItem++;
481                     isValid = true;
482                     olePurchaseOrderItem.setSelected(false);
483                     /*}*/
484                 }
485             }
486         }
487         if (selectedItem != receivingExistForItem) {
488             this.isAllowedPoForReceiving = true;
489         }
490         return isValid;
491     }
492 
493     public int getReceiptStatusDetails(String receiptStatusCd) {
494         int receiptStatusId = 0;
495         Map<String, String> receiptStatusCdMap = new HashMap<String, String>();
496         receiptStatusCdMap.put(OLEConstants.RCPT_STATUS_CD, receiptStatusCd);
497         List<OleReceiptStatus> oleReceiptStatusList = (List) SpringContext.getBean(BusinessObjectService.class)
498                 .findMatching(OleReceiptStatus.class, receiptStatusCdMap);
499         for (OleReceiptStatus oleReceiptStatus : oleReceiptStatusList) {
500             receiptStatusId = oleReceiptStatus.getReceiptStatusId().intValue();
501         }
502         return receiptStatusId;
503     }
504 
505     public OleInvoiceService getOleInvoiceServiceImpl() {
506 
507         OleInvoiceService oleInvoiceService = (OleInvoiceService) SpringContext.getBean(OleInvoiceService.class);
508         return oleInvoiceService;
509     }
510 
511     public boolean validateForReceiving(List<OlePurchaseOrderItem> purchaseOrderItems) {
512         boolean isValid = true;
513         String poid = "";
514         for (OlePurchaseOrderItem olePurchaseOrderItem : purchaseOrderItems) {
515             if (olePurchaseOrderItem.isSelected()) {
516                 if (!poid.equalsIgnoreCase("")) {
517                     if (!olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString().equalsIgnoreCase(poid)) {
518                         isValid = false;
519                         break;
520                     }
521                 } else {
522                     poid = olePurchaseOrderItem.getOlePurchaseOrderDocument().getPurapDocumentIdentifier().toString();
523                 }
524 
525             }
526         }
527         return isValid;
528     }
529 
530 
531     public void populateInvoiceFromPurchaseOrder(PurchaseOrderDocument po, OleInvoiceDocument oleInvoiceDocument, HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList, boolean isNew) {
532         AccountsPayableDocumentSpecificService accountsPayableDocumentSpecificService = SpringContext.getBean(InvoiceService.class);
533         if (isNew) {
534             VendorService vendorService = SpringContext.getBean(VendorService.class);
535             PurapService purapService = SpringContext.getBean(PurapService.class);
536             //oleInvoiceDocument.setPaymentMethodId(po.getVendorDetail().getPaymentMethodId());
537             oleInvoiceDocument.setPurchaseOrderIdentifier(po.getPurapDocumentIdentifier());
538             oleInvoiceDocument.getDocumentHeader().setOrganizationDocumentNumber(po.getDocumentHeader().getOrganizationDocumentNumber());
539             oleInvoiceDocument.setPostingYear(po.getPostingYear());
540             oleInvoiceDocument.setReceivingDocumentRequiredIndicator(po.isReceivingDocumentRequiredIndicator());
541             oleInvoiceDocument.setUseTaxIndicator(po.isUseTaxIndicator());
542             oleInvoiceDocument.setInvoicePositiveApprovalIndicator(po.isPaymentRequestPositiveApprovalIndicator());
543             oleInvoiceDocument.setVendorCustomerNumber(po.getVendorCustomerNumber());
544             oleInvoiceDocument.setReceivingDocumentRequiredIndicator(po.isReceivingDocumentRequiredIndicator());
545 
546             if (po.getPurchaseOrderCostSource() != null) {
547                 oleInvoiceDocument.setInvoiceCostSource(po.getPurchaseOrderCostSource());
548                 oleInvoiceDocument.setInvoiceCostSourceCode(po.getPurchaseOrderCostSourceCode());
549             }
550 
551             if (po.getVendorShippingPaymentTerms() != null) {
552                 oleInvoiceDocument.setVendorShippingPaymentTerms(po.getVendorShippingPaymentTerms());
553                 oleInvoiceDocument.setVendorShippingPaymentTermsCode(po.getVendorShippingPaymentTermsCode());
554             }
555 
556             if (po.getVendorPaymentTerms() != null) {
557                 oleInvoiceDocument.setVendorPaymentTermsCode(po.getVendorPaymentTermsCode());
558                 oleInvoiceDocument.setVendorPaymentTerms(po.getVendorPaymentTerms());
559             }
560 
561             if (po.getRecurringPaymentType() != null) {
562                 oleInvoiceDocument.setRecurringPaymentType(po.getRecurringPaymentType());
563                 oleInvoiceDocument.setRecurringPaymentTypeCode(po.getRecurringPaymentTypeCode());
564             }
565 
566             Bank defaultBank = SpringContext.getBean(BankService.class).getDefaultBankByDocType(oleInvoiceDocument.getClass());
567             if (defaultBank != null) {
568                 oleInvoiceDocument.setBankCode(defaultBank.getBankCode());
569                 oleInvoiceDocument.setBank(defaultBank);
570             }
571             oleInvoiceDocument.setVendorHeaderGeneratedIdentifier(po.getVendorHeaderGeneratedIdentifier());
572             oleInvoiceDocument.setVendorDetailAssignedIdentifier(po.getVendorDetailAssignedIdentifier());
573             oleInvoiceDocument.setVendorCustomerNumber(po.getVendorCustomerNumber());
574             oleInvoiceDocument.setVendorName(po.getVendorName());
575 
576             // set original vendor
577             oleInvoiceDocument.setOriginalVendorHeaderGeneratedIdentifier(po.getVendorHeaderGeneratedIdentifier());
578             oleInvoiceDocument.setOriginalVendorDetailAssignedIdentifier(po.getVendorDetailAssignedIdentifier());
579 
580             // set alternate vendor info as well
581             oleInvoiceDocument.setAlternateVendorHeaderGeneratedIdentifier(po.getAlternateVendorHeaderGeneratedIdentifier());
582             oleInvoiceDocument.setAlternateVendorDetailAssignedIdentifier(po.getAlternateVendorDetailAssignedIdentifier());
583 
584             // populate preq vendor address with the default remit address type for the vendor if found
585             String userCampus = GlobalVariables.getUserSession().getPerson().getCampusCode();
586             VendorAddress vendorAddress = vendorService.getVendorDefaultAddress(po.getVendorHeaderGeneratedIdentifier(), po.getVendorDetailAssignedIdentifier(), VendorConstants.AddressTypes.REMIT, userCampus);
587             if (vendorAddress != null) {
588                 oleInvoiceDocument.templateVendorAddress(vendorAddress);
589                 oleInvoiceDocument.setVendorAddressGeneratedIdentifier(vendorAddress.getVendorAddressGeneratedIdentifier());
590                 oleInvoiceDocument.setVendorAttentionName(StringUtils.defaultString(vendorAddress.getVendorAttentionName()));
591             } else {
592                 // set address from PO
593                 oleInvoiceDocument.setVendorAddressGeneratedIdentifier(po.getVendorAddressGeneratedIdentifier());
594                 oleInvoiceDocument.setVendorLine1Address(po.getVendorLine1Address());
595                 oleInvoiceDocument.setVendorLine2Address(po.getVendorLine2Address());
596                 oleInvoiceDocument.setVendorCityName(po.getVendorCityName());
597                 oleInvoiceDocument.setVendorAddressInternationalProvinceName(po.getVendorAddressInternationalProvinceName());
598                 oleInvoiceDocument.setVendorStateCode(po.getVendorStateCode());
599                 oleInvoiceDocument.setVendorPostalCode(po.getVendorPostalCode());
600                 oleInvoiceDocument.setVendorCountryCode(po.getVendorCountryCode());
601 
602                 boolean blankAttentionLine = StringUtils.equalsIgnoreCase(
603                         "Y",
604                         SpringContext.getBean(ParameterService.class).getParameterValueAsString(
605                                 PurapConstants.PURAP_NAMESPACE, "Document",
606                                 PurapParameterConstants.BLANK_ATTENTION_LINE_FOR_PO_TYPE_ADDRESS));
607 
608                 if (blankAttentionLine) {
609                     oleInvoiceDocument.setVendorAttentionName(StringUtils.EMPTY);
610                 } else {
611                     oleInvoiceDocument.setVendorAttentionName(StringUtils.defaultString(po.getVendorAttentionName()));
612                 }
613             }
614         }
615         oleInvoiceDocument.setInvoicePayDate(getOleInvoiceServiceImpl().calculatePayDate(oleInvoiceDocument.getInvoiceDate(), oleInvoiceDocument.getVendorPaymentTerms()));
616 
617         String currencyType = null;
618         BigDecimal exchangeRate = null;
619 
620         oleInvoiceDocument.setInvoiceCurrencyType(po.getVendorDetail().getCurrencyType().getCurrencyTypeId().toString());
621         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
622             currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
623             if (StringUtils.isNotBlank(currencyType)) {
624                 // local vendor
625                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
626                     oleInvoiceDocument.setForeignCurrencyFlag(true);
627                     oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
628                     exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
629                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
630                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceAmount())) {
631                         oleInvoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(oleInvoiceDocument.getInvoiceAmount()).multiply(exchangeRate));
632                         oleInvoiceDocument.setForeignInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
633                         oleInvoiceDocument.setForeignVendorAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
634                     }
635                     if (StringUtils.isNotBlank(oleInvoiceDocument.getForeignInvoiceAmount())) {
636                         oleInvoiceDocument.setVendorInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getInvoiceAmount()).divide(new KualiDecimal(exchangeRate)));
637                         oleInvoiceDocument.setInvoiceAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
638                         oleInvoiceDocument.setVendorAmount(oleInvoiceDocument.getVendorInvoiceAmount().toString());
639                     }
640                 }
641             }
642         }
643 
644         //   if (getOleInvoiceServiceImpl().encumberedItemExistsForInvoicing(po)) {
645         for (OlePurchaseOrderItem poi : (List<OlePurchaseOrderItem>) po.getItems()) {
646             // check to make sure it's eligible for payment (i.e. active and has encumbrance available
647             if (poi.isSelected()) {
648                 if (poi.getItemTypeCode().equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_ITEM_CODE)) {
649                     poi.setPoOutstandingQuantity(poi.getItemQuantity().subtract(poi.getItemInvoicedTotalQuantity()));
650                     poi.setNoOfCopiesInvoiced(new KualiInteger(poi.getItemQuantity().bigDecimalValue()));
651                     poi.setNoOfPartsInvoiced(poi.getItemNoOfParts());
652                     poi.setInvoiceItemListPrice(poi.getItemListPrice().toString());
653                     poi.setInvoiceForeignItemListPrice(poi.getItemForeignListPrice().toString());
654                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
655                         oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
656                      //   String currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
657                         if (StringUtils.isNotBlank(currencyType)) {
658                             if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
659                                 poi.setInvoiceForeignCurrency(currencyType);
660                                 oleInvoiceDocument.setForeignCurrencyFlag(true);
661                                 poi.setItemDiscount(new KualiDecimal(0.0));
662                                 if (StringUtils.isBlank(oleInvoiceDocument.getInvoiceCurrencyExchangeRate())) {
663                                                 /*BigDecimal exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
664                                                 oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
665                                                 poi.setInvoiceExchangeRate(exchangeRate.toString());*/
666                                     GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_EXCHANGE_RATE_EMPTY, currencyType);
667                                     //     return getUIFModelAndView(oleInvoiceForm);
668                                 } else {
669                                     try {
670                                         Double.parseDouble(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
671                                      //   BigDecimal exchangeRate = new BigDecimal(oleInvoiceDocument.getInvoiceCurrencyExchangeRate());
672                                         if (new KualiDecimal(exchangeRate).isZero()) {
673                                             GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
674                                             //       return getUIFModelAndView(oleInvoiceForm);
675                                         }
676                                         poi.setInvoiceExchangeRate(exchangeRate.toString());
677                                     } catch (NumberFormatException nfe) {
678                                         GlobalVariables.getMessageMap().putError(OleSelectConstant.INVOICE_INFO_SECTION_ID, OLEKeyConstants.ERROR_ENTER_VALID_EXCHANGE_RATE);
679                                         //      return getUIFModelAndView(oleInvoiceForm);
680                                     }
681                                 }
682 
683                                 // if the PO has Foreign Currency
684                                 if (poi.getItemForeignListPrice() != null) {
685                                     poi.setInvoiceForeignItemListPrice(poi.getItemForeignListPrice().toString());
686                                     poi.setInvoiceForeignDiscount(poi.getItemForeignDiscount() != null ? poi.getItemForeignDiscount().toString() : new KualiDecimal("0.0").toString());
687                                     poi.setInvoiceForeignUnitCost(poi.getItemForeignUnitCost().toString());
688                                     poi.setInvoiceForeignCurrency(currencyType);
689 
690                                     if (poi.getInvoiceExchangeRate() != null && poi.getInvoiceForeignUnitCost() != null) {
691                                         poi.setItemUnitCostUSD(new KualiDecimal(new BigDecimal(poi.getInvoiceForeignUnitCost()).divide(new BigDecimal(poi.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP)));
692                                         poi.setItemUnitPrice(new BigDecimal(poi.getInvoiceForeignUnitCost()).divide(new BigDecimal(poi.getInvoiceExchangeRate()), 4, RoundingMode.HALF_UP));
693                                         poi.setItemListPrice(poi.getItemUnitCostUSD());
694                                         poi.setInvoiceItemListPrice(poi.getItemListPrice().toString());
695                                     }
696                                 } else {
697                                     poi.setItemForeignUnitCost(new KualiDecimal(poi.getItemUnitPrice().multiply(new BigDecimal(poi.getInvoiceExchangeRate()))));
698                                     poi.setItemForeignListPrice(poi.getItemForeignUnitCost());
699                                     poi.setInvoiceForeignItemListPrice(poi.getItemForeignListPrice().toString());
700                                     poi.setInvoiceForeignDiscount(new KualiDecimal(0.0).toString());
701                                     poi.setInvoiceForeignUnitCost(poi.getItemForeignUnitCost().toString());
702                                 }
703                                 getInvoiceService().calculateAccount(poi);
704 
705                             } else {
706                                 oleInvoiceDocument.setForeignCurrencyFlag(false);
707                                 oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
708                                 poi.setItemDiscount(poi.getItemDiscount() != null ? poi.getItemDiscount() : new KualiDecimal(0.0));
709                             }
710                         }
711                     } else {
712                         oleInvoiceDocument.setForeignCurrencyFlag(false);
713                         oleInvoiceDocument.setInvoiceCurrencyType(oleInvoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId().toString());
714                         oleInvoiceDocument.setInvoiceCurrencyTypeId(oleInvoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId());
715                         oleInvoiceDocument.setInvoiceCurrencyExchangeRate(null);
716                         poi.setInvoiceExchangeRate(null);
717                         poi.setItemExchangeRate(null);
718                     }
719                     if (poi.getItemTitleId() != null) {
720                         poi.setItemDescription(SpringContext.getBean(OlePurapService.class).getItemDescription(poi));
721                         // poi.setDocFormat(DocumentUniqueIDPrefix.getBibFormatType(poi.getItemTitleId()));
722                     }
723 
724                 }
725 
726 
727 
728 
729                 poi.setNoOfCopiesInvoiced(poi.getOleItemQuantity());
730                 OleInvoiceItem invoiceItem = new OleInvoiceItem(poi, oleInvoiceDocument);
731                 invoiceItem.setPurchaseOrderIdentifier(po.getPurapDocumentIdentifier());
732                 invoiceItem.setItemQuantity(poi.getItemQuantity());
733                 invoiceItem.setOlePoOutstandingQuantity(new KualiInteger(poi.getOutstandingQuantity().bigDecimalValue()));
734                     /*invoiceItem.setExtendedPrice(poi.getExtendedPrice());*/
735                 invoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
736                 invoiceItem.setReceivingDocumentRequiredIndicator(po.isReceivingDocumentRequiredIndicator());
737                     /*if (new KualiDecimal(poi.getInvoiceItemListPrice()).isLessThan(AbstractKualiDecimal.ZERO)) {
738                         invoiceItem.setInvoiceListPrice(poi.getInvoiceItemListPrice());
739                     }
740                     else {
741                         invoiceItem.setItemListPrice(new KualiDecimal(poi.getInvoiceItemListPrice()));
742                     }*/
743                     /*List<OleInvoiceItem> oleInvoiceItems=(List<OleInvoiceItem>)oleInvoiceDocument.getItems();
744                     int pos=1;
745                     if(oleInvoiceItems.size()>0){
746                         for(OleInvoiceItem oleInvoiceItem:oleInvoiceItems){
747                             if(oleInvoiceItem.getItemTypeCode().equalsIgnoreCase("ITEM")){
748                                 pos=oleInvoiceItem.getItemLineNumber();
749                             }
750                         }
751                         invoiceItem.setItemLineNumber(new Integer(pos+1));
752                     }  else{
753                         invoiceItem.setItemLineNumber(new Integer(pos));
754                     }*/
755                 oleInvoiceDocument.getItems().add(invoiceItem);
756                 PurchasingCapitalAssetItem purchasingCAMSItem = po.getPurchasingCapitalAssetItemByItemIdentifier(poi.getItemIdentifier());
757                 if (purchasingCAMSItem != null) {
758                     invoiceItem.setCapitalAssetTransactionTypeCode(purchasingCAMSItem.getCapitalAssetTransactionTypeCode());
759                 }
760 
761 
762                 // copy use tax items over
763                 invoiceItem.getUseTaxItems().clear();
764                 for (PurApItemUseTax useTax : poi.getUseTaxItems()) {
765                     invoiceItem.getUseTaxItems().add(useTax);
766                 }
767 
768             }
769         }
770         // }
771 
772         // add missing below the line
773         /*purapService.addBelowLineItems(oleInvoiceDocument);*/
774         /*oleInvoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());*/
775 
776         //fix up below the line items
777         getOleInvoiceServiceImpl().removeIneligibleAdditionalCharges(oleInvoiceDocument);
778 
779         oleInvoiceDocument.fixItemReferences();
780         oleInvoiceDocument.refreshNonUpdateableReferences();
781     }
782 
783     public boolean receivePO(OleLineItemReceivingDocument oleLineItemReceivingDocument, Integer purchaseOrderIdentifier, boolean isCreateRCV, List<OlePurchaseOrderItem> purchaseOrderItems) {
784         boolean receivePOSuccess = false;
785 
786         // Setting defaults
787         oleLineItemReceivingDocument.setPurchaseOrderIdentifier(purchaseOrderIdentifier);
788         DateTimeService dateTimeService = SpringContext.getBean(DateTimeService.class);
789         oleLineItemReceivingDocument.setShipmentReceivedDate(dateTimeService.getCurrentSqlDate());
790         // Validations Start
791         boolean isValid = true;
792 
793         PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(purchaseOrderIdentifier);
794 
795         if (ObjectUtils.isNotNull(po)) {
796             oleLineItemReceivingDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(po.getAccountsPayablePurchasingDocumentLinkIdentifier());
797             if (!SpringContext.getBean(DocumentHelperService.class).getDocumentAuthorizer(oleLineItemReceivingDocument).isAuthorizedByTemplate(oleLineItemReceivingDocument, KRADConstants.KNS_NAMESPACE, KimConstants.PermissionTemplateNames.OPEN_DOCUMENT, GlobalVariables.getUserSession().getPrincipalId())) {
798                 throw new DocumentAuthorizationException(GlobalVariables.getUserSession().getPerson().getPrincipalName(), "initiate document", oleLineItemReceivingDocument.getDocumentNumber());
799             }
800         } else {
801             GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_RECEIVING_LINE_PO_NOT_EXIST, oleLineItemReceivingDocument.getPurchaseOrderIdentifier().toString());
802         }
803 
804 
805         if (!SpringContext.getBean(ReceivingService.class).isPurchaseOrderActiveForLineItemReceivingDocumentCreation(oleLineItemReceivingDocument.getPurchaseOrderIdentifier())) {
806             GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_RECEIVING_LINE_PONOTACTIVE, oleLineItemReceivingDocument.getPurchaseOrderIdentifier().toString());
807 
808             isValid = false;
809             return isValid;
810         }
811 
812         if (SpringContext.getBean(ReceivingService.class).canCreateLineItemReceivingDocument(oleLineItemReceivingDocument.getPurchaseOrderIdentifier(), oleLineItemReceivingDocument.getDocumentNumber()) == false) {
813             String inProcessDocNum = "";
814             List<String> inProcessDocNumbers = SpringContext.getBean(ReceivingService.class).getLineItemReceivingDocumentNumbersInProcessForPurchaseOrder(oleLineItemReceivingDocument.getPurchaseOrderIdentifier(), oleLineItemReceivingDocument.getDocumentNumber());
815             if (!inProcessDocNumbers.isEmpty()) {    // should not be empty if we reach this point
816                 inProcessDocNum = inProcessDocNumbers.get(0);
817             }
818             GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_RECEIVING_LINE_DOCUMENT_ACTIVE_FOR_PO, oleLineItemReceivingDocument.getPurchaseOrderIdentifier().toString(), inProcessDocNum);
819             isValid = false;
820             return isValid;
821         }
822         try {
823             if (isValid) {
824 
825                 SpringContext.getBean(ReceivingService.class).populateAndSaveLineItemReceivingDocument(oleLineItemReceivingDocument);
826 
827                 List<OleLineItemReceivingItem> itemList = new ArrayList<OleLineItemReceivingItem>();
828                 for (Object item : oleLineItemReceivingDocument.getItems()) {
829                     OleLineItemReceivingItem rlItem = (OleLineItemReceivingItem) item;
830                     // Receiving 100pc
831                     boolean isPOItemPresent = false;
832                     for (OlePurchaseOrderItem poItem : purchaseOrderItems) {
833                         if (poItem.isSelected()) {
834                             if (!isPOItemPresent
835                                     && poItem.getItemIdentifier().equals(rlItem.getPurchaseOrderIdentifier())) {
836                                 rlItem.setOleItemReceivedTotalQuantity(rlItem.getOleItemReceivedToBeQuantity());
837 
838                                 rlItem.setOleItemReceivedTotalParts(rlItem.getOleItemReceivedToBeParts());
839                                 rlItem.setPoSelected(true);
840                                 /*
841                                  * rlItem.setItemReceivedTotalQuantity(rlItem.getItemOrderedQuantity());
842                                  * rlItem.setItemReceivedTotalParts(rlItem.getItemOrderedParts());
843                                  */
844                                 isPOItemPresent = true;
845                             } else if (!isPOItemPresent) {
846                                 rlItem.setItemReceivedTotalQuantity(KualiDecimal.ZERO);
847                                 rlItem.setItemReceivedTotalParts(KualiDecimal.ZERO);
848                             }
849                         }
850                     }
851 
852                     itemList.add(rlItem);
853                 }
854                 if (ObjectUtils.isNotNull(itemList) && itemList.size() > 0) {
855                     oleLineItemReceivingDocument.setItems(itemList);
856 
857                     Person principalPerson = SpringContext.getBean(PersonService.class).getPerson(GlobalVariables.getUserSession().getPerson().getPrincipalId());
858                     //oleLineItemReceivingDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().createWorkflowDocument(oleLineItemReceivingDocument.getDocumentHeader().getWorkflowDocument().getDocumentTypeName(), principalPerson));
859                     oleLineItemReceivingDocument.getDocumentHeader().setWorkflowDocument(KRADServiceLocatorWeb.getWorkflowDocumentService().loadWorkflowDocument(oleLineItemReceivingDocument.getDocumentNumber(), principalPerson));
860                     //oleLineItemReceivingDocument.setAdHocRoutePersons(buildFyiRecipient());
861                     if (isCreateRCV) {
862                         SpringContext.getBean(DocumentService.class).saveDocument(oleLineItemReceivingDocument);
863                     } else {
864                         List<OleLineItemReceivingItem> items = oleLineItemReceivingDocument.getItems();
865                         for (OleLineItemReceivingItem item : items) {
866                             OleLineItemReceivingService oleLineItemReceivingService = SpringContext.getBean(OleLineItemReceivingServiceImpl.class);
867                             OlePurchaseOrderItem olePurchaseOrderItem = oleLineItemReceivingService.getOlePurchaseOrderItem(item.getPurchaseOrderIdentifier());
868                             if (olePurchaseOrderItem != null) {
869                                 if (item.isPoSelected()) {
870                                     for (OleCopy oleCopy : item.getCopyList()) {
871                                         oleCopy.setReceiptStatus(OLEConstants.OleLineItemReceiving.RECEIVED_STATUS);
872                                     }
873                                     OleCopyHelperService oleCopyHelperService = SpringContext.getBean(OleCopyHelperService.class);
874                                     oleCopyHelperService.updateRequisitionAndPOItems(olePurchaseOrderItem, item, null, oleLineItemReceivingDocument.getIsATypeOfRCVGDoc());
875                                 }
876                             }
877                         }
878                         try {
879                             SpringContext.getBean(DocumentService.class).routeDocument(oleLineItemReceivingDocument, "Line Item Receiving from Receiving Queue Search page", null);
880                         } catch (Exception e) {
881                             e.printStackTrace();
882                         }
883 
884                     }
885 
886                     receivePOSuccess = true;
887                 }
888             }
889         } catch (WorkflowException wfe) {
890             String rcvDocNum = oleLineItemReceivingDocument.getDocumentNumber();
891             String poId = oleLineItemReceivingDocument.getPurchaseOrderIdentifier().toString();
892             GlobalVariables.getMessageMap().putError(PurapPropertyConstants.PURCHASE_ORDER_IDENTIFIER, OLEKeyConstants.ERROR_RECEIVING_LINE_SAVE_OR_SUBMIT, new String[]{poId, rcvDocNum, wfe.getMessage()});
893 
894           /*  wfe.printStackTrace();*/
895             isValid = false;
896             return isValid;
897         }
898 
899         return receivePOSuccess;
900     }
901 
902 
903     public boolean receiveAndPay(List<OlePurchaseOrderItem> purchaseOrderItems, OlePurchaseOrderDocument olePurchaseOrderDocument) throws Exception {
904         boolean isSuccess = false;
905 
906         OleLineItemReceivingDocument oleLineItemReceivingDocument = (OleLineItemReceivingDocument) KRADServiceLocatorWeb.getDocumentService().getNewDocument("OLE_RCVL");
907         // Elimiate duplicate POs from the list
908         HashMap<Integer, OlePurchaseOrderItem> selectedPOs = getSelectedPurchaseOrders(purchaseOrderItems);
909         // Map containing PO ID and receive PO status
910         HashMap<Integer, Boolean> receivePOStatus = new HashMap<Integer, Boolean>();
911         boolean isInfoMsg = false;
912         for (Map.Entry<Integer, OlePurchaseOrderItem> entry : selectedPOs.entrySet()) {
913             boolean receivePOSuccess = this.receivePO(oleLineItemReceivingDocument, entry.getKey(), false, purchaseOrderItems);
914             if (receivePOSuccess) {
915                 receivingDocumentsList.add(oleLineItemReceivingDocument.getDocumentNumber());
916                 isInfoMsg = true;
917                 isSuccess = true;
918             }
919             receivePOStatus.put(entry.getKey(), receivePOSuccess);
920 
921         }
922         List<OlePurchaseOrderItem> refreshedPOList = new ArrayList<OlePurchaseOrderItem>();
923         for (OlePurchaseOrderItem poItem : purchaseOrderItems) {
924             Integer poId = poItem.getPurchaseOrder().getPurapDocumentIdentifier();
925             if (ObjectUtils.isNull(receivePOStatus.get(poId))) {
926                 refreshedPOList.add(poItem);
927             } else {
928                 if (receivePOStatus.get(poId) == false) {
929                     refreshedPOList.add(poItem);
930                 }
931             }
932         }
933         return isSuccess;
934     }
935 
936 
937     private HashMap<Integer, OlePurchaseOrderItem> getSelectedPurchaseOrders(List<OlePurchaseOrderItem> purchaseOrders) {
938         HashMap<Integer, OlePurchaseOrderItem> poItemMap = new HashMap<Integer, OlePurchaseOrderItem>();
939         for (OlePurchaseOrderItem poItem : purchaseOrders) {
940             if (poItem.isSelected()) {
941                 if (ObjectUtils.isNull(poItemMap.get(poItem.getPurchaseOrder().getPurapDocumentIdentifier()))) {
942                     poItemMap.put(poItem.getPurchaseOrder().getPurapDocumentIdentifier(), poItem);
943                 }
944             }
945         }
946 
947 
948         return poItemMap;
949     }
950 
951     public boolean validateRecords(Integer purAppNum, String docNumber) {
952         boolean valid = true;
953 
954         PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(purAppNum);
955         valid &= SpringContext.getBean(ReceivingService.class).canCreateLineItemReceivingDocument(purAppNum, null);
956         return valid;
957     }
958 
959     public boolean validateStatusOfPurchaseOrderDocument(OlePurchaseOrderDocument olePurchaseOrderDocument) {
960         boolean isValid = true;
961         PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getCurrentPurchaseOrder(olePurchaseOrderDocument.getPurapDocumentIdentifier());
962         if (po.getApplicationDocumentStatus().equalsIgnoreCase("Closed")) {
963             isValid = false;
964         }
965         return isValid;
966     }
967 
968     public boolean validateInvoiceDocumentNumber(String documentNumber) {
969         Map<String, String> map = new HashMap<String, String>();
970         map.put("documentNumber", documentNumber);
971         List<OleInvoiceDocument> oleInvoiceDocuments = (List<OleInvoiceDocument>) KRADServiceLocator.getBusinessObjectService().findMatching(OleInvoiceDocument.class, map);
972         if (oleInvoiceDocuments.size() > 0) {
973             return true;
974         } else {
975             return false;
976         }
977 
978     }
979 
980     public boolean validateNumber(final String hex) {
981         Pattern pattern = Pattern.compile("[0-9]+");
982         Matcher matcher = pattern.matcher(hex);
983         return matcher.matches();
984 
985     }
986 
987     public boolean isPoAlreadyPaid(List<OlePurchaseOrderItem> olePurchaseOrderItems) {
988         boolean isPaid = false;
989         for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) {
990             if (olePurchaseOrderItem.isSelected()) {
991                 if (olePurchaseOrderItem.getCopyList() != null && olePurchaseOrderItem.getCopyList().size() > 0) {
992                     for (OleCopy oleCopy : olePurchaseOrderItem.getCopyList()) {
993                         if (oleCopy != null && oleCopy.getOlePaidCopies() != null && oleCopy.getOlePaidCopies().size() > 0) {
994                             for (OLEPaidCopy olePaidCopy : oleCopy.getOlePaidCopies()) {
995                                 if (olePaidCopy != null && olePaidCopy.getPaymentRequestIdentifier() != null) {
996                                     isPaid = true;
997                                     break;
998                                 }
999                             }
1000                         }
1001                     }
1002                 }
1003             }
1004         }
1005         return isPaid;
1006     }
1007 
1008     /*
1009         This method updates the Foreign Details on the Invoice Document if it has foreign currency.
1010      */
1011   /*  private void updateForeignCurrencyDetails(OleInvoiceDocument oleInvoiceDocument) {
1012         String currencyType = null;
1013         BigDecimal exchangeRate = null;
1014         oleInvoiceDocument.setInvoiceCurrencyType(oleInvoiceDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId().toString());
1015         if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceCurrencyType())) {
1016             currencyType = getInvoiceService().getCurrencyType(oleInvoiceDocument.getInvoiceCurrencyType());
1017             if (StringUtils.isNotBlank(currencyType)) {
1018                 // local vendor
1019                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
1020                     oleInvoiceDocument.setForeignCurrencyFlag(true);
1021                     oleInvoiceDocument.setInvoiceCurrencyTypeId(new Long(oleInvoiceDocument.getInvoiceCurrencyType()));
1022                     exchangeRate = getInvoiceService().getExchangeRate(oleInvoiceDocument.getInvoiceCurrencyType()).getExchangeRate();
1023                     oleInvoiceDocument.setInvoiceCurrencyExchangeRate(exchangeRate.toString());
1024                     if (StringUtils.isNotBlank(oleInvoiceDocument.getInvoiceAmount())) {
1025                         oleInvoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(oleInvoiceDocument.getInvoiceAmount()).multiply(exchangeRate));
1026                         oleInvoiceDocument.setForeignInvoiceAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
1027                         oleInvoiceDocument.setForeignVendorAmount(new KualiDecimal(oleInvoiceDocument.getForeignVendorInvoiceAmount()).toString());
1028                     }
1029                 }
1030             }
1031         }
1032 
1033     }*/
1034 
1035 
1036 
1037 }