View Javadoc

1   package org.kuali.ole.batch.ingest;
2   
3   import org.apache.commons.lang.StringUtils;
4   import org.apache.log4j.Logger;
5   import org.kuali.ole.OLEConstants;
6   import org.kuali.ole.OLETranscationalRecordGenerator;
7   import org.kuali.ole.batch.impl.AbstractBatchProcess;
8   import org.kuali.ole.coa.businessobject.Account;
9   import org.kuali.ole.converter.OLEINVConverter;
10  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
11  import org.kuali.ole.docstore.common.document.Bib;
12  import org.kuali.ole.docstore.common.search.SearchResponse;
13  import org.kuali.ole.ingest.OleInvoiceRecordBuilder;
14  import org.kuali.ole.module.purap.PurapConstants;
15  import org.kuali.ole.module.purap.document.service.InvoiceService;
16  import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
17  import org.kuali.ole.module.purap.businessobject.InvoiceAccount;
18  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
19  import org.kuali.ole.module.purap.businessobject.PurchaseOrderAccount;
20  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
21  import org.kuali.ole.module.purap.service.PurapAccountingService;
22  import org.kuali.ole.pojo.OleInvoiceRecordHandler;
23  import org.kuali.ole.pojo.edi.INVOrders;
24  import org.kuali.ole.pojo.edi.INVOrder;
25  import org.kuali.ole.select.bo.OleVendorAccountInfo;
26  import org.kuali.ole.select.document.OleInvoiceDocument;
27  import org.kuali.ole.sys.document.validation.event.AttributedBlanketApproveDocumentEvent;
28  import org.kuali.rice.core.api.config.property.ConfigurationService;
29  import org.kuali.rice.kew.api.exception.WorkflowException;
30  import org.kuali.rice.kim.api.identity.Person;
31  import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
32  import org.kuali.rice.krad.UserSession;
33  import org.kuali.rice.krad.service.BusinessObjectService;
34  import org.kuali.rice.krad.service.DocumentService;
35  import org.kuali.rice.krad.service.KualiRuleService;
36  import org.kuali.rice.krad.service.SequenceAccessorService;
37  import org.kuali.rice.krad.util.GlobalVariables;
38  import org.kuali.ole.sys.context.SpringContext;
39  import org.kuali.ole.sys.service.BankService;
40  import org.kuali.ole.sys.businessobject.Bank;
41  import org.kuali.ole.sys.service.UniversityDateService;
42  import org.kuali.rice.core.api.util.type.KualiDecimal;
43  import org.kuali.rice.core.api.util.type.KualiInteger;
44  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
45  import org.kuali.ole.pojo.OleInvoiceRecord;
46  import java.io.BufferedReader;
47  import java.io.File;
48  import java.io.FileReader;
49  import java.io.IOException;
50  import java.math.BigDecimal;
51  import java.text.ParseException;
52  import java.text.SimpleDateFormat;
53  import java.util.*;
54  
55  import org.kuali.ole.select.document.service.*;
56  import org.kuali.ole.select.businessobject.OleInvoiceItem;
57  
58  /**
59   * Created with IntelliJ IDEA.
60   * User: palanivel
61   * Date: 7/27/13
62   * Time: 3:37 PM
63   * To change this template use File | Settings | File Templates.
64   */
65  public class BatchProcessInvoiceIngest extends AbstractBatchProcess {
66  
67      private static final Logger LOG = Logger.getLogger(BatchProcessLocationIngest.class);
68  
69      private static transient BusinessObjectService businessObjectService;
70      private String xml;
71      protected DocumentService documentService;
72      public OleInvoiceService oleInvoiceService;
73      OLETranscationalRecordGenerator oleTranscationalRecordGenerator = new OLETranscationalRecordGenerator();
74      private StringBuffer failureRecords = new StringBuffer();
75      private DocstoreClientLocator docstoreClientLocator;
76  
77      public DocstoreClientLocator getDocstoreClientLocator() {
78  
79          if (docstoreClientLocator == null) {
80              docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
81  
82          }
83          return docstoreClientLocator;
84      }
85  
86      List<INVOrder> invOrder;
87      List<INVOrders> mismatchRecord = new ArrayList();
88  
89      protected BusinessObjectService getBusinessObjectService() {
90          if (businessObjectService == null) {
91              businessObjectService = SpringContext.getBean(BusinessObjectService.class);
92          }
93          return businessObjectService;
94      }
95  
96  
97      private OleInvoiceService getInvoiceService() {
98          if (oleInvoiceService == null) {
99              oleInvoiceService = SpringContext.getBean(OleInvoiceService.class);
100         }
101         return oleInvoiceService;
102     }
103 
104     public String readFile(File file) throws IOException {
105         BufferedReader reader = new BufferedReader(new FileReader(file));
106         String line = null;
107         StringBuilder stringBuilder = new StringBuilder();
108         String ls = System.getProperty("line.separator");
109         while ((line = reader.readLine()) != null) {
110             stringBuilder.append(line);
111             stringBuilder.append(ls);
112         }
113         return stringBuilder.toString();
114     }
115 
116 
117     @Override
118     public void prepareForRead() throws Exception {
119         try {
120             convertRawDataToXML();
121         } catch (Exception e) {
122             failureRecords.append("Please ensure the file is an Edifact file (OR) EDIFACT data has an extra EDIFACT segment.");
123             failureRecords.append("\n");
124             failureRecords.append("Unable to map the Edifact file.");
125             failureRecords.append("\n");
126             failureRecords.append("org.milyn.SmooksException:" + e.getMessage());
127             failureRecords.append("\n");
128             createBatchFailureFile(failureRecords.append(new Throwable(e.getCause())).toString());
129             LOG.error(e, e);
130             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
131             job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
132             throw e;
133         }
134     }
135 
136 
137     private void convertRawDataToXML() throws Exception {
138         String fileContent = getBatchProcessFileContent();
139         OLEINVConverter OLEEDITranslator = new OLEINVConverter();
140         xml = OLEEDITranslator.convertToXML(fileContent);
141     }
142 
143     private void convertXMLToPojos(Map<Integer, List<OleInvoiceRecord>> map) throws Exception {
144         LOG.info("--------------xml----------" + xml);
145         INVOrders invOrders = null;
146         if (xml != null) {
147             invOrders = oleTranscationalRecordGenerator.fromInvoiceXml(xml);
148             invOrder = invOrders.getInvOrder();
149         }
150 
151         for (int i = 0; i < invOrder.size(); i++) {
152             OleInvoiceRecordBuilder oleInvoiceRecordBuilder = OleInvoiceRecordBuilder.getInstance();
153             OleInvoiceRecord oleInvoiceRecord = null;
154 
155             List<OleInvoiceRecord> oleInvoiceRecordList = new ArrayList<OleInvoiceRecord>();
156             for (int j = 0; j < invOrder.get(i).getLineItemOrder().size(); j++) {
157                 try {
158                     oleInvoiceRecord = oleInvoiceRecordBuilder.build(invOrder.get(i).getLineItemOrder().get(j), invOrder.get(i));
159                     oleInvoiceRecordList.add(oleInvoiceRecord);
160                 } catch (Exception e) {
161                     failureRecords.append("Unable to create Invoice document");
162                     failureRecords.append("\n");
163                     failureRecords.append(e.getMessage());
164                     failureRecords.append("\n");
165                     job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
166                     job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
167                     throw e;
168                 }
169 
170             }
171             map.put(i, oleInvoiceRecordList);
172         }
173     }
174 
175 
176     public void updatePrice(OleInvoiceDocument oleInvoiceDocument) {
177 
178 
179         for (OleInvoiceItem item : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
180             if (item.getItemDiscount() != null) {
181                 if (item.getItemDiscountType().equals("%")) {
182                     BigDecimal discount = ((item.getItemListPrice().bigDecimalValue().multiply(item.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
183                     item.setItemUnitPrice(item.getItemListPrice().bigDecimalValue().subtract(discount));
184                 } else {
185                     item.setItemUnitPrice(((OleInvoiceItem) item).getItemListPrice().bigDecimalValue().subtract(item.getItemDiscount().bigDecimalValue()));
186                 }
187             } else {
188                 item.setItemUnitPrice(((OleInvoiceItem) item).getItemListPrice().bigDecimalValue());
189             }
190 
191             getInvoiceService().calculateAccount(item);
192         }
193     }
194 
195 
196     private OleInvoiceDocument initiateInvoiceDocument(OleInvoiceDocument invoiceDocument, Person currentUser) throws Exception {
197         try {
198             invoiceDocument = (OleInvoiceDocument) SpringContext.getBean(DocumentService.class).getNewDocument("OLE_PRQS");
199         } catch (WorkflowException e) {
200             LOG.error(e, e);
201         }
202         invoiceDocument.initiateDocument();
203 
204         UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
205         invoiceDocument.setPostingYear(universityDateService.getCurrentUniversityDate().getUniversityFiscalYear());
206         Bank defaultBank = SpringContext.getBean(BankService.class).getDefaultBankByDocType(invoiceDocument.getClass());
207         if (defaultBank != null) {
208             invoiceDocument.setBankCode(defaultBank.getBankCode());
209             invoiceDocument.setBank(defaultBank);
210 
211         }
212         invoiceDocument.getDocumentHeader().setDocumentDescription("Create Invoice Document - Invoice Ingest");
213         invoiceDocument.setAccountsPayableProcessorIdentifier(currentUser.getPrincipalId());
214         invoiceDocument.setProcessingCampusCode(currentUser.getCampusCode());
215         return invoiceDocument;
216     }
217 
218     private OleVendorAccountInfo populateBFN(String code) {
219         Map matchBFN = new HashMap();
220         matchBFN.put("vendorRefNumber", code);
221         List<OleVendorAccountInfo> oleVendorAccountInfo = (List<OleVendorAccountInfo>) getBusinessObjectService().findMatching(OleVendorAccountInfo.class, matchBFN);
222         return oleVendorAccountInfo != null && oleVendorAccountInfo.size() > 0 ? oleVendorAccountInfo.get(0) : null;
223     }
224 
225     private String populateChartOfAccount(String accountNumber) {
226         Map matchChartCode = new HashMap();
227         matchChartCode.put("accountNumber", accountNumber);
228         List<Account> accountList = (List<Account>) getBusinessObjectService().findMatching(Account.class, matchChartCode);
229         return accountList != null && accountList.size() > 0 ? accountList.get(0).getChartOfAccountsCode() : null;
230     }
231 
232     private HashMap addInvoiceItem(List<OlePurchaseOrderItem> olePurchaseOrderItems, OleInvoiceRecord invoiceRecord, OleInvoiceDocument invoiceDocument, PurchaseOrderDocument purchaseOrderDocument, HashMap itemMap) throws Exception {
233 
234         for (OlePurchaseOrderItem poItem : olePurchaseOrderItems) {
235             if (poItem.getItemTypeCode().equalsIgnoreCase("ITEM")) {
236                 OleInvoiceItem oleInvoiceItem = new OleInvoiceItem();
237                 oleInvoiceItem.setItemQuantity(new KualiDecimal(invoiceRecord.getQuantity()));
238                 oleInvoiceItem.setItemListPrice(new KualiDecimal(invoiceRecord.getListPrice()));
239                 oleInvoiceItem.setItemDescription(poItem.getItemDescription());      // invoiceRecord.getItemDescription()
240                 oleInvoiceItem.setItemUnitPrice(new BigDecimal(invoiceRecord.getUnitPrice()));
241                 oleInvoiceItem.setItemTitleId(poItem.getItemTitleId());
242                 if(invoiceRecord.getLineItemAdditionalCharge() != null){
243                     oleInvoiceItem.setVendorItemIdentifier(poItem.getVendorItemPoNumber());
244                 }
245                 PurchaseOrderService purchaseOrderService = (PurchaseOrderService) SpringContext.getBean("purchaseOrderService");
246                 purchaseOrderDocument = purchaseOrderService.getPurchaseOrderByDocumentNumber(poItem.getDocumentNumber());
247                 oleInvoiceItem.setPurchaseOrderIdentifier(purchaseOrderDocument.getPurapDocumentIdentifier());
248                 oleInvoiceItem.setItemLineNumber(poItem.getItemLineNumber());
249                 oleInvoiceItem.setItemNoOfParts(poItem.getItemNoOfParts());
250                 oleInvoiceItem.setPoItemIdentifier(poItem.getItemIdentifier());
251                 oleInvoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier(purchaseOrderDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
252                 oleInvoiceItem.setOlePoOutstandingQuantity(new KualiInteger(poItem.getOutstandingQuantity().bigDecimalValue()));
253                 //call populate VendorInfo
254                 OleVendorAccountInfo oleVendorAccountInfo = populateBFN(invoiceRecord.getBfnNumber());
255                 List accountingLine = new ArrayList();
256                 if (oleVendorAccountInfo != null && oleVendorAccountInfo.isActive()) {
257 
258                     InvoiceAccount invoiceAccount = new InvoiceAccount();
259                     invoiceAccount.setAccountNumber(oleVendorAccountInfo.getAccountNumber());
260                     invoiceAccount.setFinancialObjectCode(oleVendorAccountInfo.getObjectCode());
261                     invoiceAccount.setAmount(new KualiDecimal(invoiceRecord.getUnitPrice()));
262                     invoiceAccount.setAccountLinePercent(new BigDecimal("100"));  // TODO: Need to get from edifact.
263                     invoiceAccount.setPurapItem(oleInvoiceItem);
264                     invoiceAccount.setItemIdentifier(oleInvoiceItem.getItemIdentifier());
265                     invoiceAccount.setChartOfAccountsCode(populateChartOfAccount(oleVendorAccountInfo.getAccountNumber()) != null ? populateChartOfAccount(oleVendorAccountInfo.getAccountNumber()) : invoiceRecord.getItemChartCode());     // TODO: Need to get chart of Account based on account number and object code.
266                     accountingLine.add(invoiceAccount);
267 
268                 } else {
269                     for (PurApAccountingLine poa : poItem.getSourceAccountingLines()) {
270                         InvoiceAccount invoiceAccount = new InvoiceAccount(oleInvoiceItem, (PurchaseOrderAccount) poa);
271                         accountingLine.add(invoiceAccount);
272                     }
273                 }
274 
275                 oleInvoiceItem.setSourceAccountingLines(accountingLine);
276                 oleInvoiceItem.setPostingYear(poItem.getPurchaseOrder().getPostingYear());
277                 invoiceDocument.getItems().add(oleInvoiceItem);
278 
279             }
280         }
281 
282         itemMap.put("invoiceDocument", invoiceDocument);
283         itemMap.put("purchaseOrderDocument", purchaseOrderDocument);
284         return itemMap;
285     }
286 
287 
288     @Override
289     public void prepareForWrite() throws Exception {
290         ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
291         GlobalVariables.setUserSession(new UserSession(processDef.getUser()));
292         OleInvoiceDocument invoiceDocument = null;
293         OleInvoiceRecord invoiceRecord = null;
294         List<OleInvoiceDocument> allInvoiceDocument = new ArrayList<>();
295         OleInvoiceRecordHandler oleInvoiceRecordHandler = new OleInvoiceRecordHandler();
296         Map<Integer, List<OleInvoiceRecord>> map = new HashMap();
297         try {
298             convertXMLToPojos(map);
299         } catch (Exception e) {
300             createBatchFailureFile(failureRecords.append(e.getMessage()).toString());
301             LOG.error(e, e);
302             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
303             job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
304             throw e;
305         }
306         oleInvoiceRecordHandler.setOleInvoiceLineItemRecords(map);
307         int totalInvoiceFileCount = 0;
308         // int totalInvoiceProcessedCount = 0;
309         int successCount = 0;
310         for (int i = 0; i < oleInvoiceRecordHandler.getOleInvoiceLineItemRecords().size(); i++) {
311             totalInvoiceFileCount = oleInvoiceRecordHandler.getOleInvoiceLineItemRecords().size();
312 
313             Person currentUser = GlobalVariables.getUserSession().getPerson();
314 
315             try {
316                 invoiceDocument = initiateInvoiceDocument(invoiceDocument, currentUser);
317             } catch (Exception e) {
318                 LOG.error(e, e);
319                 failureRecords.append("Unable to create Invoice document");
320                 failureRecords.append("\n");
321                 createBatchFailureFile(failureRecords.append(e.getMessage()).toString());
322                 //job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_STOPPED);
323             }
324             Map<Integer, List<OleInvoiceRecord>> oleInvoiceRecord = oleInvoiceRecordHandler.getOleInvoiceLineItemRecords();
325             List<OleInvoiceRecord> oleInvoiceRecordList = oleInvoiceRecord.get(i);
326             SimpleDateFormat dateFromRawFile = new SimpleDateFormat("yyyyMMdd");
327             OleInvoiceService oleInvoiceService = getInvoiceService();
328             if (oleInvoiceRecordList != null && !oleInvoiceRecordList.isEmpty()) {
329                 OleInvoiceRecord invoiceRecordHeader = oleInvoiceRecordList.get(0);
330                 invoiceDocument.setInvoiceNumber(invoiceRecordHeader.getInvoiceNumber());
331                 invoiceDocument.setVendorInvoiceAmount(new KualiDecimal(invoiceRecordHeader.getVendorInvoiceAmount()));
332                 Date rawDate = null;
333                 try {
334                     rawDate = dateFromRawFile.parse(invoiceRecordHeader.getInvoiceDate());
335                 } catch (ParseException e) {
336                     LOG.error(e, e);
337                     failureRecords.append("Invoice Date: " + invoiceRecordHeader.getInvoiceDate());
338                     failureRecords.append("Cannot parse Invoice Date" + e);
339 
340                 }
341                 if (rawDate != null) {
342                     invoiceDocument.setInvoiceDate(new java.sql.Date(rawDate.getTime()));
343                 }
344             }
345             for (int j = 0; j < oleInvoiceRecordList.size(); j++) {
346                 invoiceRecord = oleInvoiceRecordList.get(j);
347                 List<OlePurchaseOrderItem> olePurchaseOrderItems = null;
348                 Map vendorItemIdentifier = new HashMap();
349                 vendorItemIdentifier.put("vendorItemPoNumber", invoiceRecord.getVendorItemIdentifier());
350                 if (invoiceRecord.getVendorItemIdentifier() != null) {
351                     olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, vendorItemIdentifier);
352                 }
353                 PurchaseOrderDocument purchaseOrderDocument = null;
354                 HashMap itemMap = new HashMap();
355                 if (olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) {
356 
357                     invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
358                     if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
359                         invoiceDocument.setPostingYear((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) ? olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() : null);
360                     }
361                     //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
362                     invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
363                     itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
364                     if (itemMap != null) {
365                         invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
366                         purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
367                     }
368                     //totalInvoiceProcessedCount = i+1;
369                 } else if (olePurchaseOrderItems == null || olePurchaseOrderItems.size() < 1) {
370                     if (invoiceRecord.getVendorNumber() != null && !invoiceRecord.getVendorNumber().isEmpty() &&
371                             invoiceRecord.getISBN() != null && !invoiceRecord.getISBN().isEmpty()) {
372                         org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
373                         SearchResponse searchResponse = null;
374                         // Retrieve bib id through solr query
375                         //StringBuffer query = new StringBuffer("");
376                         //List<HashMap<String, Object>> documentList1 = null;
377                         //query.append("(ISBN_search:" + invoiceRecord.getISBN() + ")");
378                         search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), Bib.ISBN, invoiceRecord.getISBN()), ""));
379                         search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id"));
380                         String titleId=null;
381                         searchResponse=getDocstoreClientLocator().getDocstoreClient().search(search_Params);
382                         if(searchResponse.getSearchResults()!=null&&searchResponse.getSearchResults().size()>0){
383                             titleId=searchResponse.getSearchResults().get(0).getSearchResultFields().get(0).getFieldValue()!=null?searchResponse.getSearchResults().get(0).getSearchResultFields().get(0).getFieldValue():"";
384                         }
385 
386 
387                         //documentList1 = QueryServiceImpl.getInstance().retriveResults(query.toString());
388                         //Map map1 = documentList1 != null && documentList1.size() > 0 ? documentList1.get(0) : null;
389 
390                         //String titleId = map1 != null ? (String) map1.get("id") : null;
391                         String[] vendorIds = invoiceRecord.getVendorNumber() != null ? invoiceRecord.getVendorNumber().split("-") : new String[0];
392 
393                         Map itemTitleIdMap = new HashMap();
394                         itemTitleIdMap.put("itemTitleId", titleId);
395                         itemTitleIdMap.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorIds.length > 0 ? vendorIds[0] : "");
396                         itemTitleIdMap.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorIds.length > 1 ? vendorIds[1] : "");
397                         if (titleId != null) {
398                             olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemTitleIdMap);
399 
400                             invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
401                             if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
402                                 invoiceDocument.setPostingYear(olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear());
403                             }
404                             //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
405                             invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
406                             itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
407                             if (itemMap != null) {
408                                 invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
409                                 purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
410                             }
411                             // totalInvoiceProcessedCount = i+1;
412                         } else if (olePurchaseOrderItems == null || olePurchaseOrderItems.size() < 1) {
413 
414                             String[] vendorId = invoiceRecord.getVendorNumber() != null ? invoiceRecord.getVendorNumber().split("-") : new String[0];
415                             Map itemTitleId = new HashMap();
416                             itemTitleId.put("purchaseOrder.purapDocumentIdentifier", invoiceRecord.getPurchaseOrderNumber());
417                             itemTitleId.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorId.length > 0 ? vendorId[0] : "");
418                             itemTitleId.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorId.length > 1 ? vendorId[1] : "");
419                             if (invoiceRecord.getPurchaseOrderNumber() != null) {
420                                 olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemTitleId);
421                                 if (olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) {
422                                     invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
423                                     if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
424                                         invoiceDocument.setPostingYear(olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear());
425                                     }
426                                     //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
427                                     invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
428 
429                                     itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
430                                     if (itemMap != null) {
431                                         invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
432                                         purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
433                                     }
434                                     // totalInvoiceProcessedCount = i+1;
435                                 }
436                             }
437                         }
438                     }
439 
440 
441                 }
442                 if (purchaseOrderDocument != null) {
443                     for (OleInvoiceItem item : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
444                         if (invoiceRecord.getAdditionalChargeCode() != null && invoiceRecord.getAdditionalChargeCode().equalsIgnoreCase("SVC") && item.getItemTypeCode().equalsIgnoreCase("SPHD")) {
445                             item.setItemUnitPrice(new BigDecimal(invoiceRecord.getAdditionalCharge() != null ? invoiceRecord.getAdditionalCharge() : invoiceRecord.getAdditionalCharge()));
446                             item.setPurchaseOrderIdentifier(purchaseOrderDocument.getPurapDocumentIdentifier());
447                         } else if (invoiceRecord.getLineItemAdditionalChargeCode() != null && invoiceRecord.getLineItemAdditionalChargeCode().equalsIgnoreCase("LD") && item.getItemTypeCode().equalsIgnoreCase("ITEM")) {
448 
449                             if ((item.getItemDescription().contains(invoiceRecord.getISBN())
450                                     || (invoiceRecord.getVendorItemIdentifier() != null ? invoiceRecord.getVendorItemIdentifier().equalsIgnoreCase(olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 ? item.getVendorItemIdentifier() : "") : false)
451                                     || (invoiceRecord.getPurchaseOrderNumber() != null ? invoiceRecord.getPurchaseOrderNumber().equals(item.getPurchaseOrderDocument() != null ? item.getPurchaseOrderDocument().getPurapDocumentIdentifier(): null):false))) {
452 
453 
454                                 item.setItemDiscountType("#"); // % or #
455                                 item.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
456                             }
457                         }
458                     }
459 
460                     String vendorNumber = purchaseOrderDocument.getVendorHeaderGeneratedIdentifier() + "-" + purchaseOrderDocument.getVendorDetailAssignedIdentifier();
461                     oleInvoiceService.populateVendorDetail(vendorNumber, invoiceDocument);
462                     invoiceDocument.setVendorCustomerNumber(invoiceRecord.getBillToCustomerID());
463                     if (invoiceDocument.getPaymentMethodId() != null) {
464                         invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
465                     } else {
466                         invoiceDocument.setPaymentMethodId(Integer.parseInt(OLEConstants.OleInvoiceImport.PAY_METHOD));
467                         invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
468                     }
469                     //   SpringContext.getBean(OleInvoiceService.class).calculateProrateItemSurcharge(invoiceDocument);
470                     SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(invoiceDocument);
471                     Long nextLinkIdentifier = SpringContext.getBean(SequenceAccessorService.class).getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID");
472                     invoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(nextLinkIdentifier.intValue());
473 
474 
475                     if ((invoiceDocument.getProrateBy() != null) && (invoiceDocument.getProrateBy().equals(org.kuali.ole.sys.OLEConstants.PRORATE_BY_QTY) || invoiceDocument.getProrateBy().equals(org.kuali.ole.sys.OLEConstants.PRORATE_BY_DOLLAR) || invoiceDocument.getProrateBy().equals(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE))) {
476                         // set amounts on any empty
477                         invoiceDocument.updateExtendedPriceOnItems();
478 
479                         // calculation just for the tax area, only at tax review stage
480                         // by now, the general calculation shall have been done.
481                         if (invoiceDocument.getApplicationDocumentStatus().equals(PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
482                             SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
483                         }
484 
485                         updatePrice(invoiceDocument);
486 
487                         // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
488                         // Calculate Payment request before rules since the rule check totalAmount.
489                         SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
490                         SpringContext.getBean(KualiRuleService.class).applyRules(
491                                 new AttributedCalculateAccountsPayableEvent(invoiceDocument));
492                     } else {
493                         // set amounts on any empty
494                         invoiceDocument.updateExtendedPriceOnItems();
495 
496                         // calculation just for the tax area, only at tax review stage
497                         // by now, the general calculation shall have been done.
498                         if (StringUtils.equals(invoiceDocument.getApplicationDocumentStatus(), PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
499                             SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
500 
501                         }
502 
503                         updatePrice(invoiceDocument);
504 
505                         // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
506                         //Calculate Payment request before rules since the rule check totalAmount.
507                         SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
508                         SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument));
509                     }
510                     if (!SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedBlanketApproveDocumentEvent(invoiceDocument)) ||
511                             !SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument))) {
512 
513 
514                         //}else {
515                         LOG.info("Invoice Error Message------------------->");
516                         failureRecords.append("Unable to create Invoice document");
517                         failureRecords.append("\n");
518                         failureRecords.append("Invoice Number :" + invoiceRecord.getInvoiceNumber());
519                         failureRecords.append("\n");
520                         failureRecords.append("Invoice Date :" + invoiceDocument.getInvoiceDate());
521                         failureRecords.append("\n");
522                         if ((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")) != null) {
523                             for (int error = 0; error < (GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).size(); error++) {
524                                 failureRecords.append("Error Message:" + kualiConfiguration.getPropertyValueAsString((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).get(error).getErrorKey()));
525                                 failureRecords.append("\n");
526                             }
527                         }
528                         failureRecords.append("\n");
529                     }
530                 } else {
531                     failureRecords.append("Unable to create Invoice document. Below following match points doesn't matches any Purchase Order.");
532                     failureRecords.append("\n");
533                     failureRecords.append("Invoice Number :" + invoiceRecord.getInvoiceNumber());
534                     failureRecords.append("\n");
535                     failureRecords.append("Invoice Date :" + invoiceRecord.getInvoiceDate());
536                     failureRecords.append("\n");
537                     failureRecords.append("\n");
538                     failureRecords.append("Combination 1:");
539                     failureRecords.append("\n");
540                     failureRecords.append("Vendor Item Identifier :" + invoiceRecord.getVendorItemIdentifier());
541                     failureRecords.append("\n");
542                     failureRecords.append("\n");
543                     failureRecords.append("Combination 2:");
544                     failureRecords.append("\n");
545                     failureRecords.append("Vendor Number :" + invoiceRecord.getVendorNumber());
546                     failureRecords.append("\n");
547                     failureRecords.append("ISBN :" + invoiceRecord.getISBN());
548                     failureRecords.append("\n");
549                     failureRecords.append("\n");
550                     failureRecords.append("Combination 3:");
551                     failureRecords.append("\n");
552                     failureRecords.append("Purchase Order Number :" + invoiceRecord.getPurchaseOrderNumber());
553                     failureRecords.append("\n");
554                     failureRecords.append("Vendor Number :" + invoiceRecord.getVendorNumber());
555                     failureRecords.append("\n");
556                     failureRecords.append("----------------------------------------------------------------------------------------------------------");
557                     failureRecords.append("\n");
558 
559                 }
560 
561             }
562             deleteBatchFile();
563             if (!"".equals(failureRecords.toString())) {
564                 createBatchFailureFile(failureRecords.toString());
565             }
566             allInvoiceDocument.add(invoiceDocument);
567         }
568         if (allInvoiceDocument != null && !allInvoiceDocument.isEmpty()) {
569             for (int process = 0; process < allInvoiceDocument.size(); process++) {
570                 invoiceDocument = allInvoiceDocument.get(process);
571                 if (invoiceDocument.getAccountsPayablePurchasingDocumentLinkIdentifier() != null) {
572                     if (SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedBlanketApproveDocumentEvent(invoiceDocument)) &&
573                             SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument))) {
574 
575                         try {
576                             oleInvoiceService.autoApprovePaymentRequest(invoiceDocument);
577                             successCount = process + 1;
578                         } catch (Exception e) {
579                             LOG.info("Invoice Error Message------------------->");
580                             failureRecords.append("Unable to create Invoice document");
581                             failureRecords.append("\n");
582                             failureRecords.append("Invoice Number :" + invoiceRecord.getInvoiceNumber());
583                             failureRecords.append("\n");
584                             failureRecords.append("Invoice Date :" + invoiceDocument.getInvoiceDate());
585                             failureRecords.append("\n");
586                             if ((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")) != null) {
587                                 for (int error = 0; error < (GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).size(); error++) {
588                                     failureRecords.append("Error Message:" + kualiConfiguration.getPropertyValueAsString((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).get(error).getErrorKey()));
589                                     failureRecords.append("\n");
590                                 }
591                             } else {
592                                 failureRecords.append("Error Message:" + e.initCause(new Throwable()));
593                             }
594                             failureRecords.append("\n");
595                             failureRecords.append("\n");
596 
597                         }
598 
599                         job.setTotalNoOfRecords(totalInvoiceFileCount + "");
600                         job.setNoOfRecordsProcessed(totalInvoiceFileCount + "");
601                         job.setNoOfSuccessRecords(String.valueOf(successCount));
602                         job.setNoOfFailureRecords(String.valueOf(totalInvoiceFileCount - successCount));
603                         job.setStatusDesc(OLEConstants.INVOICE_UPLOAD_SUCCESS);
604                         job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
605                         deleteBatchFile();
606                         if (!"".equals(failureRecords.toString())) {
607                             createBatchFailureFile(failureRecords.toString());
608                         }
609                     }
610                     job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
611                 }
612                 job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
613             }
614             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
615         }
616         job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
617     }
618 
619     @Override
620     public void getNextBatch() {
621         //To change body of implemented methods use File | Settings | File Templates.
622     }
623 
624     @Override
625     public void processBatch() {
626         //To change body of implemented methods use File | Settings | File Templates.
627     }
628 
629 }