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.DataCarrierService;
6   import org.kuali.ole.OLEConstants;
7   import org.kuali.ole.OLETranscationalRecordGenerator;
8   import org.kuali.ole.batch.bo.OLEBatchBibImportDataObjects;
9   import org.kuali.ole.batch.bo.OLEBatchProcessProfileBo;
10  import org.kuali.ole.batch.controller.OLEBatchProcessJobDetailsController;
11  import org.kuali.ole.batch.impl.AbstractBatchProcess;
12  import org.kuali.ole.coa.businessobject.Account;
13  import org.kuali.ole.coa.businessobject.ObjectCode;
14  import org.kuali.ole.converter.MarcXMLConverter;
15  import org.kuali.ole.converter.OLEINVConverter;
16  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
17  import org.kuali.ole.docstore.common.document.content.bib.marc.*;
18  import org.kuali.ole.docstore.common.document.content.bib.marc.xstream.BibMarcRecordProcessor;
19  import org.kuali.ole.docstore.common.search.SearchResponse;
20  import org.kuali.ole.ingest.OleInvoiceRecordBuilder;
21  import org.kuali.ole.module.purap.PurapConstants;
22  import org.kuali.ole.module.purap.document.service.InvoiceService;
23  import org.kuali.ole.module.purap.document.service.OlePurapService;
24  import org.kuali.ole.module.purap.document.service.PurchaseOrderService;
25  import org.kuali.ole.module.purap.businessobject.InvoiceAccount;
26  import org.kuali.ole.module.purap.businessobject.PurApAccountingLine;
27  import org.kuali.ole.module.purap.businessobject.PurchaseOrderAccount;
28  import org.kuali.ole.module.purap.document.validation.event.AttributedCalculateAccountsPayableEvent;
29  import org.kuali.ole.module.purap.service.PurapAccountingService;
30  import org.kuali.ole.pojo.OleInvoiceRecordHandler;
31  import org.kuali.ole.pojo.edi.INVOrders;
32  import org.kuali.ole.pojo.edi.INVOrder;
33  import org.kuali.ole.select.OleSelectConstant;
34  import org.kuali.ole.select.bo.OleVendorAccountInfo;
35  import org.kuali.ole.select.document.OLEInvoiceIngestLoadReport;
36  import org.kuali.ole.select.document.OleInvoiceDocument;
37  import org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl;
38  import org.kuali.ole.sys.document.validation.event.AttributedSaveDocumentEvent;
39  import org.kuali.ole.vnd.businessobject.OleCurrencyType;
40  import org.kuali.ole.vnd.businessobject.OleExchangeRate;
41  import org.kuali.ole.vnd.businessobject.VendorDetail;
42  import org.kuali.rice.core.api.config.property.ConfigurationService;
43  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
44  import org.kuali.rice.kew.api.exception.WorkflowException;
45  import org.kuali.rice.kim.api.identity.Person;
46  import org.kuali.ole.select.businessobject.OlePurchaseOrderItem;
47  import org.kuali.rice.krad.UserSession;
48  import org.kuali.rice.krad.service.*;
49  import org.kuali.rice.krad.util.ErrorMessage;
50  import org.kuali.rice.krad.util.GlobalVariables;
51  import org.kuali.ole.sys.context.SpringContext;
52  import org.kuali.ole.sys.service.BankService;
53  import org.kuali.ole.sys.businessobject.Bank;
54  import org.kuali.ole.sys.service.UniversityDateService;
55  import org.kuali.rice.core.api.util.type.KualiDecimal;
56  import org.kuali.rice.core.api.util.type.KualiInteger;
57  import org.kuali.ole.module.purap.document.PurchaseOrderDocument;
58  import org.kuali.ole.pojo.OleInvoiceRecord;
59  import java.io.BufferedReader;
60  import java.io.File;
61  import java.io.FileReader;
62  import java.io.IOException;
63  import java.math.BigDecimal;
64  import java.text.SimpleDateFormat;
65  import java.util.*;
66  
67  import org.kuali.ole.select.document.service.*;
68  import org.kuali.ole.select.businessobject.OleInvoiceItem;
69  import org.springframework.util.AutoPopulatingList;
70  
71  /**
72   * Created with IntelliJ IDEA.
73   * User: palanivel
74   * Date: 7/27/13
75   * Time: 3:37 PM
76   * To change this template use File | Settings | File Templates.
77   */
78  public class BatchProcessInvoiceIngest extends AbstractBatchProcess {
79  
80      private static final Logger LOG = Logger.getLogger(BatchProcessLocationIngest.class);
81  
82      private static transient BusinessObjectService businessObjectService;
83      private String xml;
84      protected DocumentService documentService;
85      public OleInvoiceService oleInvoiceService;
86      OLETranscationalRecordGenerator oleTranscationalRecordGenerator = new OLETranscationalRecordGenerator();
87      private StringBuffer failureRecords = new StringBuffer();
88      private DocstoreClientLocator docstoreClientLocator;
89      private String marcXMLContent;
90      DataCarrierService dataCarrierService = GlobalResourceLoader.getService(OLEConstants.DATA_CARRIER_SERVICE);
91      private static transient OlePurapService olePurapService;
92  
93      public static OlePurapService getOlePurapService() {
94          if (olePurapService == null) {
95              olePurapService = SpringContext.getBean(OlePurapService.class);
96          }
97          return olePurapService;
98      }
99  
100     public DocstoreClientLocator getDocstoreClientLocator() {
101 
102         if (docstoreClientLocator == null) {
103             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
104 
105         }
106         return docstoreClientLocator;
107     }
108 
109     List<INVOrder> invOrder;
110     List<INVOrders> mismatchRecord = new ArrayList();
111 
112     protected BusinessObjectService getBusinessObjectService() {
113         if (businessObjectService == null) {
114             businessObjectService = SpringContext.getBean(BusinessObjectService.class);
115         }
116         return businessObjectService;
117     }
118 
119 
120     private OleInvoiceService getInvoiceService() {
121         if (oleInvoiceService == null) {
122             oleInvoiceService = SpringContext.getBean(OleInvoiceService.class);
123         }
124         return oleInvoiceService;
125     }
126 
127     public String readFile(File file) throws IOException {
128         BufferedReader reader = new BufferedReader(new FileReader(file));
129         String line = null;
130         StringBuilder stringBuilder = new StringBuilder();
131         String ls = System.getProperty("line.separator");
132         while ((line = reader.readLine()) != null) {
133             stringBuilder.append(line);
134             stringBuilder.append(ls);
135         }
136         return stringBuilder.toString();
137     }
138 
139 
140     @Override
141     public void prepareForRead() throws Exception {
142         try {
143             convertRawDataToXML();
144         } catch (Exception e) {
145             failureRecords.append("Please ensure the file is an Edifact file (OR) EDIFACT data has an extra EDIFACT segment.");
146             failureRecords.append("\n");
147             failureRecords.append("Unable to map the Edifact file.");
148             failureRecords.append("\n");
149             failureRecords.append("org.milyn.SmooksException:" + e.getMessage());
150             failureRecords.append("\n");
151             createBatchErrorAttachmentFile(failureRecords.append(new Throwable(e.getCause())).toString());
152             LOG.error(e, e);
153             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
154             job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
155             throw e;
156         }
157     }
158 
159     public void byPassLogicForPreProcess(String rawMarcContent, boolean preProcessingReq) {
160         if (preProcessingReq) {
161             preProcess(rawMarcContent);
162         } else {
163             marcXMLContent = rawMarcContent;
164         }
165     }
166 
167     private void preProcess(String rawMarcContent) {
168         marcXMLContent = preProcessMarc(rawMarcContent);
169     }
170 
171     private OLEBatchProcessProfileBo getBibImportProfile() {
172         String bibImportProfileForOrderRecord = this.processDef.getOleBatchProcessProfileBo().getBibImportProfileForOrderRecord();
173         org.kuali.rice.krad.service.BusinessObjectService
174                 businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
175         Map<String, String> bibImportProfileMap = new HashMap<>();
176         bibImportProfileMap.put("batchProcessProfileName", bibImportProfileForOrderRecord);
177         List<OLEBatchProcessProfileBo> oleBatchProcessProfileBoList = (List) businessObjectService.findMatching(OLEBatchProcessProfileBo.class, bibImportProfileMap);
178         if (oleBatchProcessProfileBoList != null && oleBatchProcessProfileBoList.size() > 0) {
179             return oleBatchProcessProfileBoList.get(0);
180         }
181         return null;
182     }
183 
184     public String preProcessMarc(String marcFileContent) {
185         String marcXMLContent = null;
186         MarcXMLConverter marcXMLConverter = new MarcXMLConverter();
187         marcXMLContent = marcXMLConverter.convert(marcFileContent);
188 
189         //TODO: hack to get rid of the extra xmlns entry. Not sure why the second entry gets generated when calling marc4J in ole-docstore-utility.
190         //TODO: the duplicate entry does not get genereated if its run directly in the ole-docstore-utilty project.
191         String modifiedXMLContent =
192                 marcXMLContent.
193                         replace("collection xmlns=\"http://www.loc.gov/MARC21/slim\" xmlns=\"http://www.loc.gov/MARC21/slim",
194                                 "collection xmlns=\"http://www.loc.gov/MARC21/slim");
195         return modifiedXMLContent;
196     }
197 
198     private void convertRawDataToXML() throws Exception {
199         String fileContent = getBatchProcessFileContent();
200         if (this.processDef.getUploadFileName().endsWith(".mrc")) {
201             byPassLogicForPreProcess(fileContent, true);
202             ;
203         } else {
204             OLEINVConverter OLEEDITranslator = new OLEINVConverter();
205             xml = OLEEDITranslator.convertToXML(fileContent);
206         }
207     }
208 
209     private void convertXMLToPojos(Map<String, List<OleInvoiceRecord>> map) throws Exception {
210         LOG.info("--------------xml----------" + xml);
211         INVOrders invOrders = null;
212         if (xml != null) {
213             invOrders = oleTranscationalRecordGenerator.fromInvoiceXml(xml);
214             invOrder = invOrders.getInvOrder();
215         }
216 
217         for (int i = 0; i < invOrder.size(); i++) {
218             OleInvoiceRecordBuilder oleInvoiceRecordBuilder = OleInvoiceRecordBuilder.getInstance();
219             OleInvoiceRecord oleInvoiceRecord = null;
220 
221             List<OleInvoiceRecord> oleInvoiceRecordList = new ArrayList<OleInvoiceRecord>();
222             for (int j = 0; j < invOrder.get(i).getLineItemOrder().size(); j++) {
223                 try {
224                     oleInvoiceRecord = oleInvoiceRecordBuilder.build(invOrder.get(i).getLineItemOrder().get(j), invOrder.get(i));
225                     oleInvoiceService = getInvoiceService();
226                     oleInvoiceService.setOleBatchProcessProfileBo(this.processDef.getOleBatchProcessProfileBo());
227                     oleInvoiceService.setDefaultAndConstantValuesToInvoiceRecord(oleInvoiceRecord);
228                     String invoiceNumber = (oleInvoiceRecord.getInvoiceNumber() != null && !oleInvoiceRecord.getInvoiceNumber().isEmpty())
229                             ? oleInvoiceRecord.getInvoiceNumber() : "0";
230                     oleInvoiceRecordList = map.get(invoiceNumber);
231                     if (oleInvoiceRecordList == null) {
232                         oleInvoiceRecordList = new ArrayList<OleInvoiceRecord>();
233                     }
234                     oleInvoiceRecordList.add(oleInvoiceRecord);
235                     map.put(invoiceNumber, oleInvoiceRecordList);
236                 } catch (Exception e) {
237                     failureRecords.append("Unable to create Invoice document");
238                     failureRecords.append("\n");
239                     failureRecords.append(e.getMessage());
240                     failureRecords.append("\n");
241                     job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
242                     job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
243                     throw e;
244                 }
245             }
246         }
247     }
248 
249     private void convertXMLToPojos(Map<String, List<OleInvoiceRecord>> map, String marcXMLContent) throws Exception {
250         LOG.info("--------------xml----------" + marcXMLContent);
251         List<OleInvoiceRecord> oleInvoiceRecordList = new ArrayList<OleInvoiceRecord>();
252         try {
253             BibMarcRecordProcessor bibMarcRecordProcessor = new BibMarcRecordProcessor();
254             BibMarcRecords bibMarcRecords = bibMarcRecordProcessor.fromXML(marcXMLContent);
255             oleInvoiceService = new OleInvoiceServiceImpl();
256             oleInvoiceService.setOleBatchProcessProfileBo(this.processDef.getOleBatchProcessProfileBo());
257             List<BibMarcRecord> records = bibMarcRecords.getRecords();
258             dataCarrierService.addData("invoiceIngestFailureReason",new ArrayList<>());
259             OLEBatchProcessProfileBo oleBatchProcessProfileBoForBibImport = getBibImportProfile();
260             BatchProcessBibImport batchProcessBibImport = new BatchProcessBibImport();
261             batchProcessBibImport.setOleBatchProcessProfileBo(oleBatchProcessProfileBoForBibImport);
262             OLEBatchBibImportDataObjects oleBatchBibImportDataObjects = new OLEBatchBibImportDataObjects();
263             List<OrderBibMarcRecord> orderBibMarcRecords = oleBatchBibImportDataObjects.processBibImport(records,batchProcessBibImport);
264             if(orderBibMarcRecords != null && orderBibMarcRecords.size() >0){
265                 for(int recCount = 0;recCount < orderBibMarcRecords.size();recCount ++){
266                     // Check for errors in the output of bib import
267                     if(!StringUtils.isBlank(orderBibMarcRecords.get(recCount).getFailureReason())){
268                         failureRecords.append(OLEConstants.OLEBatchProcess.REC_POSITION + (recCount+1) + "  " + OLEConstants.OLEBatchProcess.BIB_IMP_FAILED);
269                         getTitleInformationForFailureRecords(orderBibMarcRecords.get(recCount).getBibMarcRecord());
270                         failureRecords.append(OLEConstants.OLEBatchProcess.REASON + orderBibMarcRecords.get(recCount).getFailureReason() + "\n");
271                     }
272                 }
273             }
274             else {
275                 failureRecords.append(OLEConstants.OLEBatchProcess.BIB_IMP_FAILED);
276             }
277             for (int recordCount = 0; recordCount < records.size(); recordCount++) {
278                 OleInvoiceRecord oleInvoiceRecord = getInvoiceService().populateValuesFromProfile(records.get(recordCount));
279                 String invoiceNumber = (oleInvoiceRecord.getInvoiceNumber() != null && !oleInvoiceRecord.getInvoiceNumber().isEmpty())
280                         ? oleInvoiceRecord.getInvoiceNumber() : "0";
281                 oleInvoiceRecordList = map.get(invoiceNumber);
282                 if (oleInvoiceRecordList == null) {
283                     oleInvoiceRecordList = new ArrayList<OleInvoiceRecord>();
284                 }
285                 oleInvoiceRecordList.add(oleInvoiceRecord);
286                 map.put(invoiceNumber, oleInvoiceRecordList);
287             }
288 
289         } catch (Exception e) {
290             List invoiceIngestFailureReason = (List) dataCarrierService.getData("invoiceIngestFailureReason");
291             if(invoiceIngestFailureReason != null && invoiceIngestFailureReason.size()>0){
292                 for(int failCount = 0;failCount < invoiceIngestFailureReason.size();failCount++){
293                     failureRecords.append(invoiceIngestFailureReason.get(failCount) + "\n");
294                 }
295             }
296             failureRecords.append("Unable to create Invoice document");
297             failureRecords.append("\n");
298             failureRecords.append(e.getMessage());
299             failureRecords.append("\n");
300             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
301             job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
302             throw e;
303         }
304     }
305 
306     private void getTitleInformationForFailureRecords( BibMarcRecord bibMarcRecord){
307         String title = null;
308         for (DataField dataField : bibMarcRecord.getDataFields()){
309             if (dataField.getTag().equals("245")){
310                 for (SubField subfield : dataField.getSubFields()){
311                     if (subfield.getCode().equals("a")){
312                         title = subfield.getValue();
313                     }
314                 }
315             }
316         }
317         if (title!=null){
318             failureRecords.append("For Title : "+title);
319         }
320     }
321 
322 
323     public void updatePrice(OleInvoiceDocument oleInvoiceDocument) {
324 
325 
326         for (OleInvoiceItem item : (List<OleInvoiceItem>) oleInvoiceDocument.getItems()) {
327             if (item.getItemDiscount() != null) {
328                 if (item.getItemDiscountType() != null && item.getItemDiscountType().equals("%")) {
329                     BigDecimal discount = ((item.getItemListPrice().bigDecimalValue().multiply(item.getItemDiscount().bigDecimalValue()))).divide(new BigDecimal(100));
330                     item.setItemUnitPrice(item.getItemListPrice().bigDecimalValue().subtract(discount));
331                 } else {
332                     item.setItemUnitPrice(((OleInvoiceItem) item).getItemListPrice().bigDecimalValue().subtract(item.getItemDiscount().bigDecimalValue()));
333                 }
334             } else {
335                 item.setItemUnitPrice(((OleInvoiceItem) item).getItemListPrice().bigDecimalValue());
336             }
337             getInvoiceService().calculateAccount(item);
338         }
339     }
340 
341 
342     private OleInvoiceDocument initiateInvoiceDocument(OleInvoiceDocument invoiceDocument, Person currentUser) throws Exception {
343         try {
344             invoiceDocument = (OleInvoiceDocument) SpringContext.getBean(DocumentService.class).getNewDocument("OLE_PRQS");
345         } catch (WorkflowException e) {
346             LOG.error(e, e);
347         }
348         invoiceDocument.initiateDocument();
349 
350         UniversityDateService universityDateService = SpringContext.getBean(UniversityDateService.class);
351         invoiceDocument.setPostingYear(universityDateService.getCurrentUniversityDate().getUniversityFiscalYear());
352         Bank defaultBank = SpringContext.getBean(BankService.class).getDefaultBankByDocType(invoiceDocument.getClass());
353         if (defaultBank != null) {
354             invoiceDocument.setBankCode(defaultBank.getBankCode());
355             invoiceDocument.setBank(defaultBank);
356 
357         }
358         String description = getOlePurapService().getParameter(OLEConstants.INVOICE_IMPORT_INV_DESC);
359         if (LOG.isDebugEnabled()){
360             LOG.debug("Description for invoice import ingest is "+description);
361         }
362         description = getOlePurapService().setDocumentDescription(description,null);
363         invoiceDocument.getDocumentHeader().setDocumentDescription(description);
364         invoiceDocument.setAccountsPayableProcessorIdentifier(currentUser.getPrincipalId());
365         invoiceDocument.setProcessingCampusCode(currentUser.getCampusCode());
366         return invoiceDocument;
367     }
368 
369     private OleVendorAccountInfo populateBFN(String code) {
370         Map matchBFN = new HashMap();
371         matchBFN.put("vendorRefNumber", code);
372         List<OleVendorAccountInfo> oleVendorAccountInfo = (List<OleVendorAccountInfo>) getBusinessObjectService().findMatching(OleVendorAccountInfo.class, matchBFN);
373         return oleVendorAccountInfo != null && oleVendorAccountInfo.size() > 0 ? oleVendorAccountInfo.get(0) : null;
374     }
375 
376     private String populateChartOfAccount(String accountNumber) {
377         Map matchChartCode = new HashMap();
378         matchChartCode.put("accountNumber", accountNumber);
379         List<Account> accountList = (List<Account>) getBusinessObjectService().findMatching(Account.class, matchChartCode);
380         return accountList != null && accountList.size() > 0 ? accountList.get(0).getChartOfAccountsCode() : null;
381     }
382 
383     private HashMap addInvoiceItem(List<OlePurchaseOrderItem> olePurchaseOrderItems, OleInvoiceRecord invoiceRecord, OleInvoiceDocument invoiceDocument, PurchaseOrderDocument purchaseOrderDocument, HashMap itemMap) throws Exception {
384 
385         for (OlePurchaseOrderItem poItem : olePurchaseOrderItems) {
386             if (poItem.getItemTypeCode().equalsIgnoreCase("ITEM")) {
387                 OleInvoiceItem oleInvoiceItem = new OleInvoiceItem();
388                 oleInvoiceItem.setItemTypeCode(poItem.getItemTypeCode());
389                 oleInvoiceItem.setItemType(poItem.getItemType());
390                 oleInvoiceItem.setItemQuantity(new KualiDecimal(invoiceRecord.getQuantity()));
391                 oleInvoiceItem.setItemListPrice(new KualiDecimal(invoiceRecord.getListPrice()));
392                 oleInvoiceItem.setItemDescription(poItem.getItemDescription());      // invoiceRecord.getItemDescription()
393                 oleInvoiceItem.setItemDiscount(invoiceRecord.getLineItemAdditionalCharge() != null ? new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge()) : null);
394                 oleInvoiceItem.setItemDiscountType(invoiceRecord.getDiscountType());
395                 oleInvoiceItem.setItemUnitPrice(new BigDecimal(invoiceRecord.getUnitPrice()));
396                 oleInvoiceItem.setItemTitleId(poItem.getItemTitleId());
397                 if (invoiceRecord.getLineItemAdditionalCharge() != null) {
398                     oleInvoiceItem.setVendorItemIdentifier(poItem.getVendorItemPoNumber());
399                 }
400                 PurchaseOrderService purchaseOrderService = (PurchaseOrderService) SpringContext.getBean("purchaseOrderService");
401                 purchaseOrderDocument = purchaseOrderService.getPurchaseOrderByDocumentNumber(poItem.getDocumentNumber());
402                 oleInvoiceItem.setPurchaseOrderIdentifier(purchaseOrderDocument.getPurapDocumentIdentifier());
403                 oleInvoiceItem.setItemLineNumber(poItem.getItemLineNumber());
404                 oleInvoiceItem.setItemNoOfParts(poItem.getItemNoOfParts());
405                 oleInvoiceItem.setPoItemIdentifier(poItem.getItemIdentifier());
406                 oleInvoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier(purchaseOrderDocument.getAccountsPayablePurchasingDocumentLinkIdentifier());
407                 oleInvoiceItem.setOlePoOutstandingQuantity(new KualiInteger(poItem.getOutstandingQuantity().bigDecimalValue()));
408                 //call populate VendorInfo
409                 OleVendorAccountInfo oleVendorAccountInfo = populateBFN(invoiceRecord.getBfnNumber());
410                 List accountingLine = new ArrayList();
411                 if (oleVendorAccountInfo != null && oleVendorAccountInfo.isActive()) {
412 
413                     InvoiceAccount invoiceAccount = new InvoiceAccount();
414                     invoiceAccount.setAccountNumber(oleVendorAccountInfo.getAccountNumber());
415                     invoiceAccount.setFinancialObjectCode(oleVendorAccountInfo.getObjectCode());
416                     invoiceAccount.setAmount(new KualiDecimal(invoiceRecord.getUnitPrice()));
417                     invoiceAccount.setAccountLinePercent(new BigDecimal("100"));  // TODO: Need to get from edifact.
418                     invoiceAccount.setPurapItem(oleInvoiceItem);
419                     invoiceAccount.setItemIdentifier(oleInvoiceItem.getItemIdentifier());
420                     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.
421                     accountingLine.add(invoiceAccount);
422 
423                 } else {
424                     for (PurApAccountingLine poa : poItem.getSourceAccountingLines()) {
425                         InvoiceAccount invoiceAccount = new InvoiceAccount(oleInvoiceItem, (PurchaseOrderAccount) poa);
426                         invoiceAccount.setAccountNumber(!StringUtils.isBlank(invoiceRecord.getAccountNumber()) ? invoiceRecord.getAccountNumber() : invoiceAccount.getAccountNumber());
427                         invoiceAccount.setFinancialObjectCode(!StringUtils.isBlank(invoiceRecord.getObjectCode()) ? invoiceRecord.getObjectCode()  : invoiceAccount.getFinancialObjectCode());
428                         accountingLine.add(invoiceAccount);
429                     }
430                 }
431                 oleInvoiceItem.setSourceAccountingLines(accountingLine);
432                 oleInvoiceItem.setPostingYear(poItem.getPurchaseOrder().getPostingYear());
433                 SimpleDateFormat dateFromRawFile = new SimpleDateFormat(org.kuali.ole.OLEConstants.DATE_FORMAT);
434                 oleInvoiceItem.setSubscriptionFromDate(invoiceRecord.getSubscriptionPeriodFrom()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodFrom()).getTime()):null);
435                 oleInvoiceItem.setSubscriptionToDate(invoiceRecord.getSubscriptionPeriodTo()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodTo()).getTime()):null);
436                 if(!StringUtils.isBlank(invoiceDocument.getInvoiceCurrencyType())){
437                     invoiceDocument.setInvoiceCurrencyTypeId(new Long(invoiceDocument.getInvoiceCurrencyType()));
438                     String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
439                     if (StringUtils.isNotBlank(currencyType)) {
440                         if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
441                             setItemForeignDetails(oleInvoiceItem,invoiceDocument.getInvoiceCurrencyType(),invoiceRecord);
442                         }
443                     }
444                 }
445                 invoiceDocument.getItems().add(oleInvoiceItem);
446 
447             }
448         }
449 
450         itemMap.put("invoiceDocument", invoiceDocument);
451         itemMap.put("purchaseOrderDocument", purchaseOrderDocument);
452         return itemMap;
453     }
454 
455     private HashMap createInvoiceItem(int lineItemCount, OleInvoiceRecord invoiceRecord, OleInvoiceDocument invoiceDocument
456             , HashMap itemMap) throws Exception {
457 
458         OleInvoiceItem oleInvoiceItem = new OleInvoiceItem();
459         validateInvoiceRecordValues(invoiceRecord);
460         oleInvoiceItem.setItemQuantity(new KualiDecimal(invoiceRecord.getQuantity()));
461         oleInvoiceItem.setItemListPrice(new KualiDecimal(invoiceRecord.getListPrice()));
462         oleInvoiceItem.setItemDescription(invoiceRecord.getItemDescription());      // invoiceRecord.getItemDescription()
463         /*if (invoiceRecord.getAdditionalChargeCode() != null && invoiceRecord.getAdditionalChargeCode().equalsIgnoreCase("SVC")) {
464             oleInvoiceItem.setItemUnitPrice(new BigDecimal(invoiceRecord.getAdditionalCharge() != null ? invoiceRecord.getAdditionalCharge() : invoiceRecord.getAdditionalCharge()));
465             oleInvoiceItem.setItemTypeCode("SPHD");
466         } *//*else if (invoiceRecord.getLineItemAdditionalChargeCode() != null && invoiceRecord.getLineItemAdditionalChargeCode().equalsIgnoreCase("LD") && item.getItemTypeCode().equalsIgnoreCase("ITEM")) {
467             oleInvoiceItem.
468             oleInvoiceItem.setItemDiscountType("#"); // % or #
469             oleInvoiceItem.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
470         }*/
471         //else {
472         if (invoiceRecord.getUnitPrice() != null) {
473             oleInvoiceItem.setItemUnitPrice(new BigDecimal(invoiceRecord.getUnitPrice()));
474         }
475         oleInvoiceItem.setItemTypeCode("ITEM");
476         oleInvoiceItem.setItemDiscountType("%"); // % or #
477         oleInvoiceItem.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
478         //}
479         oleInvoiceItem.setItemTitleId(null);
480         if (invoiceRecord.getLineItemAdditionalCharge() != null) {
481             oleInvoiceItem.setVendorItemIdentifier(null);
482         }
483 
484         //PurchaseOrderService purchaseOrderService = (PurchaseOrderService) SpringContext.getBean("purchaseOrderService");
485         // purchaseOrderDocument = purchaseOrderService.getPurchaseOrderByDocumentNumber(poItem.getDocumentNumber());
486         oleInvoiceItem.setPurchaseOrderIdentifier(null);
487         oleInvoiceItem.setItemLineNumber(lineItemCount);
488         oleInvoiceItem.setItemNoOfParts(new KualiInteger("1"));
489         oleInvoiceItem.setPoItemIdentifier(null);
490         oleInvoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier((SpringContext.getBean(SequenceAccessorService.class).
491                 getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID")).intValue());
492         oleInvoiceItem.setOlePoOutstandingQuantity(KualiInteger.ZERO);
493         //call populate VendorInfo
494         OleVendorAccountInfo oleVendorAccountInfo = populateBFN(invoiceRecord.getBfnNumber());
495         List accountingLine = new ArrayList();
496         if (oleVendorAccountInfo != null && oleVendorAccountInfo.isActive()) {
497 
498             InvoiceAccount invoiceAccount = new InvoiceAccount();
499             invoiceAccount.setAccountNumber(oleVendorAccountInfo.getAccountNumber());
500             invoiceAccount.setFinancialObjectCode(oleVendorAccountInfo.getObjectCode());
501             invoiceAccount.setAmount(new KualiDecimal(invoiceRecord.getUnitPrice()));
502             invoiceAccount.setAccountLinePercent(new BigDecimal("100"));  // TODO: Need to get from edifact.
503             invoiceAccount.setPurapItem(oleInvoiceItem);
504             invoiceAccount.setItemIdentifier(oleInvoiceItem.getItemIdentifier());
505             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.
506             accountingLine.add(invoiceAccount);
507 
508         } else if (invoiceRecord.getAccountNumber() != null && invoiceRecord.getObjectCode() != null) {
509             InvoiceAccount invoiceAccount = new InvoiceAccount();
510             invoiceAccount.setAccountNumber(invoiceRecord.getAccountNumber());
511             invoiceAccount.setFinancialObjectCode(invoiceRecord.getObjectCode());
512             invoiceAccount.setAmount(new KualiDecimal(invoiceRecord.getUnitPrice()));
513             invoiceAccount.setAccountLinePercent(new BigDecimal("100"));  // TODO: Need to get from edifact.
514             invoiceAccount.setPurapItem(oleInvoiceItem);
515             invoiceAccount.setItemIdentifier(oleInvoiceItem.getItemIdentifier());
516             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.
517             accountingLine.add(invoiceAccount);
518 
519         }
520 
521         oleInvoiceItem.setSourceAccountingLines(accountingLine);
522         oleInvoiceItem.setPostingYear(SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate().getUniversityFiscalYear());
523         SimpleDateFormat dateFromRawFile = new SimpleDateFormat(org.kuali.ole.OLEConstants.DATE_FORMAT);
524         oleInvoiceItem.setSubscriptionFromDate(invoiceRecord.getSubscriptionPeriodFrom()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodFrom()).getTime()):null);
525         oleInvoiceItem.setSubscriptionToDate(invoiceRecord.getSubscriptionPeriodTo()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodTo()).getTime()):null);
526         if(!StringUtils.isBlank(invoiceDocument.getInvoiceCurrencyType())){
527             invoiceDocument.setInvoiceCurrencyTypeId(new Long(invoiceDocument.getInvoiceCurrencyType()));
528             String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
529             if (StringUtils.isNotBlank(currencyType)) {
530                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
531                     setItemForeignDetails(oleInvoiceItem,invoiceDocument.getInvoiceCurrencyType(),invoiceRecord);
532                 }
533             }
534         }
535         invoiceDocument.getItems().add(oleInvoiceItem);
536 
537         /* if (invoiceRecord.getAdditionalChargeCode() != null && invoiceRecord.getAdditionalChargeCode().equalsIgnoreCase("SVC") && item.getItemTypeCode().equalsIgnoreCase("SPHD")) {
538                     item.setItemUnitPrice(new BigDecimal(invoiceRecord.getAdditionalCharge() != null ? invoiceRecord.getAdditionalCharge() : invoiceRecord.getAdditionalCharge()));
539                     item.setPurchaseOrderIdentifier(purchaseOrderDocument != null && purchaseOrderDocument.getPurapDocumentIdentifier() != null ?
540                             purchaseOrderDocument.getPurapDocumentIdentifier() : null);
541                 } else if (invoiceRecord.getLineItemAdditionalChargeCode() != null && invoiceRecord.getLineItemAdditionalChargeCode().equalsIgnoreCase("LD") && item.getItemTypeCode().equalsIgnoreCase("ITEM")) {
542 
543                     if ((item.getItemDescription().contains(invoiceRecord.getISBN())
544                             || (invoiceRecord.getVendorItemIdentifier() != null ? invoiceRecord.getVendorItemIdentifier().equalsIgnoreCase(olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 ? item.getVendorItemIdentifier() : "") : false)
545                             || (invoiceRecord.getPurchaseOrderNumber() != null ? invoiceRecord.getPurchaseOrderNumber().equals(item.getPurchaseOrderDocument() != null ? item.getPurchaseOrderDocument().getPurapDocumentIdentifier(): null):false))) {
546 
547 
548                         item.setItemDiscountType("#"); // % or #
549                         item.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
550                     }
551                 }
552         */
553 
554         itemMap.put("invoiceDocument", invoiceDocument);
555         return itemMap;
556     }
557 
558     private HashMap createInvoiceItem(OleInvoiceRecord invoiceRecord, OleInvoiceDocument invoiceDocument
559             , HashMap itemMap) throws Exception {
560         OleInvoiceItem oleInvoiceItem = new OleInvoiceItem();
561         oleInvoiceItem.setItemQuantity(new KualiDecimal(invoiceRecord.getQuantity()));
562         oleInvoiceItem.setItemListPrice(new KualiDecimal(invoiceRecord.getListPrice()));
563         oleInvoiceItem.setItemUnitPrice(new BigDecimal(invoiceRecord.getUnitPrice()));
564         oleInvoiceItem.setItemTypeCode("ITEM");
565         oleInvoiceItem.setItemDiscountType("%");
566         oleInvoiceItem.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
567         oleInvoiceItem.setItemTitleId(invoiceRecord.getItemTitleIdForMRC());
568         oleInvoiceItem.setItemDescription(invoiceRecord.getItemDescription());
569         if (invoiceRecord.getLineItemAdditionalCharge() != null) {
570             oleInvoiceItem.setVendorItemIdentifier(null);
571         }
572         oleInvoiceItem.setPurchaseOrderIdentifier(null);
573         oleInvoiceItem.setItemNoOfParts(new KualiInteger("1"));
574         oleInvoiceItem.setPoItemIdentifier(null);
575         oleInvoiceItem.setAccountsPayablePurchasingDocumentLinkIdentifier((SpringContext.getBean(SequenceAccessorService.class).
576                 getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID")).intValue());
577         oleInvoiceItem.setOlePoOutstandingQuantity(KualiInteger.ZERO);
578         List accountingLine = new ArrayList();
579         if (invoiceRecord.getAccountNumber() != null && invoiceRecord.getObjectCode() != null) {
580             InvoiceAccount invoiceAccount = new InvoiceAccount();
581             invoiceAccount.setAccountNumber(invoiceRecord.getAccountNumber());
582             invoiceAccount.setFinancialObjectCode(invoiceRecord.getObjectCode());
583             invoiceAccount.setAmount(new KualiDecimal(invoiceRecord.getUnitPrice()));
584             invoiceAccount.setAccountLinePercent(new BigDecimal("100"));
585             invoiceAccount.setPurapItem(oleInvoiceItem);
586             invoiceAccount.setItemIdentifier(oleInvoiceItem.getItemIdentifier());
587             invoiceAccount.setChartOfAccountsCode(populateChartOfAccount(invoiceRecord.getAccountNumber()));
588             if(checkForValidObjectCode(invoiceRecord,invoiceAccount)){
589                 accountingLine.add(invoiceAccount);
590             }
591         }
592         oleInvoiceItem.setSourceAccountingLines(accountingLine);
593         oleInvoiceItem.setPostingYear(SpringContext.getBean(UniversityDateService.class).getCurrentUniversityDate().getUniversityFiscalYear());
594         SimpleDateFormat dateFromRawFile = new SimpleDateFormat(org.kuali.ole.OLEConstants.DATE_FORMAT);
595         oleInvoiceItem.setSubscriptionFromDate(invoiceRecord.getSubscriptionPeriodFrom()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodFrom()).getTime()):null);
596         oleInvoiceItem.setSubscriptionToDate(invoiceRecord.getSubscriptionPeriodTo()!= null ? new java.sql.Date(dateFromRawFile.parse(invoiceRecord.getSubscriptionPeriodTo()).getTime()):null);
597         if(!StringUtils.isBlank(invoiceDocument.getInvoiceCurrencyType())){
598             invoiceDocument.setInvoiceCurrencyTypeId(new Long(invoiceDocument.getInvoiceCurrencyType()));
599             String currencyType = getInvoiceService().getCurrencyType(invoiceDocument.getInvoiceCurrencyType());
600             if (StringUtils.isNotBlank(currencyType)) {
601                 if (!currencyType.equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)) {
602                     setItemForeignDetails(oleInvoiceItem,invoiceDocument.getInvoiceCurrencyType(),invoiceRecord);
603                 }
604             }
605         }
606         invoiceDocument.getItems().add(oleInvoiceItem);
607         itemMap.put("invoiceDocument", invoiceDocument);
608         return itemMap;
609     }
610 
611     private void setItemForeignDetails(OleInvoiceItem oleInvoiceItem,String invoiceCurrencyType, OleInvoiceRecord invoiceRecord){
612          KualiDecimal foreignListPrice = new KualiDecimal(invoiceRecord.getForeignListPrice());
613         oleInvoiceItem.setItemForeignListPrice(new KualiDecimal(invoiceRecord.getForeignListPrice()));
614         oleInvoiceItem.setItemForeignDiscount(oleInvoiceItem.getItemDiscount() == null ? new KualiDecimal(0.0) : oleInvoiceItem.getItemDiscount());
615         oleInvoiceItem.setItemForeignDiscountType(oleInvoiceItem.getItemDiscountType() != null ? oleInvoiceItem.getItemDiscountType() : "%");
616         if(oleInvoiceItem.getItemForeignDiscountType().equalsIgnoreCase("%")){
617             BigDecimal discount = ((new BigDecimal(String.valueOf(foreignListPrice)).multiply(new BigDecimal(oleInvoiceItem.getForeignDiscount())))).divide(new BigDecimal(100));
618             oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(new BigDecimal(String.valueOf(foreignListPrice)).subtract(discount)));
619         }
620         else {
621             oleInvoiceItem.setItemForeignUnitCost(new KualiDecimal(new BigDecimal(String.valueOf(foreignListPrice)).subtract(new BigDecimal(oleInvoiceItem.getForeignDiscount()))));
622         }
623         oleInvoiceItem.setItemExchangeRate(new KualiDecimal(getInvoiceService().getExchangeRate(invoiceCurrencyType).getExchangeRate()));
624         if(StringUtils.isNotBlank(invoiceRecord.getInvoiceCurrencyExchangeRate())){
625            oleInvoiceItem.setItemUnitCostUSD(new KualiDecimal(oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(new BigDecimal(invoiceRecord.getInvoiceCurrencyExchangeRate()), 4, BigDecimal.ROUND_HALF_UP)));
626         }else{
627            oleInvoiceItem.setItemUnitCostUSD(new KualiDecimal(oleInvoiceItem.getItemForeignUnitCost().bigDecimalValue().divide(oleInvoiceItem.getItemExchangeRate().bigDecimalValue(), 4, BigDecimal.ROUND_HALF_UP)));
628         }
629         oleInvoiceItem.setItemUnitPrice(oleInvoiceItem.getItemUnitCostUSD().bigDecimalValue());
630         oleInvoiceItem.setItemListPrice(oleInvoiceItem.getItemUnitCostUSD());
631     }
632 
633     private boolean checkForValidObjectCode(OleInvoiceRecord oleInvoiceRecord,InvoiceAccount invoiceAccount){
634         Map<String,String> chartCodeMap = new HashMap<>();
635         chartCodeMap.put("chartOfAccountsCode",invoiceAccount.getChartOfAccountsCode());
636         List<ObjectCode> objectCodeList = (List<ObjectCode>) getBusinessObjectService().findMatching(ObjectCode.class, chartCodeMap);
637         if(objectCodeList != null && objectCodeList.size() > 0){
638             for(int recCount = 0;recCount < objectCodeList.size();recCount++){
639                 if(oleInvoiceRecord.getObjectCode().equalsIgnoreCase(objectCodeList.get(recCount).getFinancialObjectCode())){
640                     return true;
641                 }
642             }
643         }
644         return false;
645     }
646 
647     private void validateInvoiceRecordValues(OleInvoiceRecord invoiceRecord) throws Exception {
648         boolean validQuantity = validateForNumber(invoiceRecord.getQuantity());
649         if(!validQuantity){
650             failureRecords.append(OLEConstants.INVALID_QTY + "  "+ invoiceRecord.getQuantity()+"\n" );
651         }
652         boolean validListPrice = validateDestinationFieldValues(invoiceRecord.getListPrice());
653         if(!validListPrice){
654             failureRecords.append(OLEConstants.INVALID_LIST_PRICE + "  " + invoiceRecord.getListPrice()+"\n");
655         }
656         boolean validVendorNumber = validateVendorNumber(invoiceRecord.getVendorNumber());
657         if(!validVendorNumber){
658             failureRecords.append(org.kuali.ole.OLEConstants.INVALID_VENDOR_NUMBER + "  "+ invoiceRecord.getVendorNumber() + "\n");
659         }
660         if(!StringUtils.isBlank(failureRecords.toString())){
661             createBatchErrorAttachmentFile(failureRecords.toString());
662         }
663     }
664 
665     @Override
666     public void prepareForWrite() throws Exception {
667         ConfigurationService kualiConfiguration = SpringContext.getBean(ConfigurationService.class);
668         GlobalVariables.setUserSession(new UserSession(processDef.getUser()));
669         OleInvoiceDocument invoiceDocument = null;
670         OleInvoiceRecord invoiceRecord = null;
671         List<OleInvoiceDocument> allInvoiceDocument = new ArrayList<>();
672         OleInvoiceRecordHandler oleInvoiceRecordHandler = new OleInvoiceRecordHandler();
673         Map<String, List<OleInvoiceRecord>> map = new HashMap();
674         try {
675             if (this.processDef.getUploadFileName().endsWith(".mrc")) {
676                 convertXMLToPojos(map, marcXMLContent);
677             } else {
678                 convertXMLToPojos(map);
679             }
680         } catch (Exception e) {
681             createBatchErrorAttachmentFile(failureRecords.append(e.getMessage()).toString());
682             LOG.error(e, e);
683             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
684             job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
685             throw e;
686         }
687         oleInvoiceRecordHandler.setOleInvoiceLineItemRecords(map);
688         int totalInvoiceFileCount = 0;
689         // int totalInvoiceProcessedCount = 0;
690         int successCount = 0;
691         for (Map.Entry invoiceRecordList : oleInvoiceRecordHandler.getOleInvoiceLineItemRecords().entrySet()) {
692              List<OleInvoiceRecord> oleInvoiceRecord = (List<OleInvoiceRecord>)invoiceRecordList.getValue();
693             totalInvoiceFileCount = oleInvoiceRecordHandler.getOleInvoiceLineItemRecords().size();
694 
695             Person currentUser = GlobalVariables.getUserSession().getPerson();
696 
697             try {
698                 invoiceDocument = initiateInvoiceDocument(invoiceDocument, currentUser);
699             } catch (Exception e) {
700                 LOG.error(e, e);
701                 failureRecords.append("Unable to create Invoice document");
702                 failureRecords.append("\n");
703                 createBatchErrorAttachmentFile(failureRecords.append(e.getMessage()).toString());
704                 //job.setStatusDesc(OLEConstants.OLEBatchProcess.JOB_STATUS_STOPPED);
705             }
706             //Map<Integer, List<OleInvoiceRecord>> oleInvoiceRecord = oleInvoiceRecordHandler.getOleInvoiceLineItemRecords();
707             //List<OleInvoiceRecord> oleInvoiceRecordList = oleInvoiceRecord.get(0);
708             SimpleDateFormat dateFromRawFile = new SimpleDateFormat("yyyyMMdd");
709             OleInvoiceService oleInvoiceService = getInvoiceService();
710            // if (oleInvoiceRecordList != null && !oleInvoiceRecordList.isEmpty()) {
711                 OleInvoiceRecord invoiceRecordHeader = oleInvoiceRecord.get(0);
712                 invoiceDocument.setInvoiceNumber(invoiceRecordHeader.getInvoiceNumber());
713                 //invoiceDocument.setVendorInvoiceAmount(new KualiDecimal(invoiceRecordHeader.getVendorInvoiceAmount()));
714                 invoiceDocument.setVendorInvoiceAmount(null);
715                 Date rawDate = null;
716                 try {
717                     rawDate = dateFromRawFile.parse(invoiceRecordHeader.getInvoiceDate());
718                 } catch (Exception e) {
719                     LOG.error(e, e);
720                     failureRecords.append("Invoice Date: " + invoiceRecordHeader.getInvoiceDate());
721                     failureRecords.append("\n");
722                     failureRecords.append("Cannot parse Invoice Date" + e);
723                     createBatchErrorAttachmentFile(failureRecords.toString());
724                     throw e;
725 
726                 }
727                 if (rawDate != null) {
728                     invoiceDocument.setInvoiceDate(new java.sql.Date(rawDate.getTime()));
729                 }
730             //}
731             int lineItemCount = 0;
732             for (int j = 0; j < oleInvoiceRecord.size(); j++) {
733                 invoiceRecord = oleInvoiceRecord.get(j);
734                     String[] vendorIds = invoiceRecord.getVendorNumber() != null ? invoiceRecord.getVendorNumber().split("-") : new String[0];
735                     if(!StringUtils.isBlank(invoiceRecord.getCurrencyTypeId())){
736                         setDocumentForeignDetails(invoiceDocument,invoiceRecord);
737                     }
738                     else {
739                         Map vendorDetailMap = new HashMap();
740                         vendorDetailMap.put("vendorHeaderGeneratedIdentifier", vendorIds.length > 0 ? vendorIds[0] : "");
741                         vendorDetailMap.put("vendorDetailAssignedIdentifier", vendorIds.length > 1 ? vendorIds[1] : "");
742                         VendorDetail vendorDetail = (VendorDetail) getBusinessObjectService().findByPrimaryKey(VendorDetail.class, vendorDetailMap);
743                         if(vendorDetail != null){
744                             invoiceRecord.setCurrencyTypeId(vendorDetail.getCurrencyTypeId().toString());
745                             setDocumentForeignDetails(invoiceDocument,invoiceRecord);
746                         }
747                     }
748                     List<OlePurchaseOrderItem> olePurchaseOrderItems = null;
749                     Map vendorItemIdentifier = new HashMap();
750                     vendorItemIdentifier.put("vendorItemPoNumber", invoiceRecord.getVendorItemIdentifier());
751                     vendorItemIdentifier.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorIds.length > 0 ? vendorIds[0] : "");
752                     vendorItemIdentifier.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorIds.length > 1 ? vendorIds[1] : "");
753                     List<OlePurchaseOrderItem> dummyPurchaseOrderItems = null;
754                     if (invoiceRecord.getVendorItemIdentifier() != null) {
755                         dummyPurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, vendorItemIdentifier);
756                         Collections.sort(dummyPurchaseOrderItems,new Comparator<OlePurchaseOrderItem>(){
757                             public int compare(OlePurchaseOrderItem dummyPurchaseOrderItems1,OlePurchaseOrderItem dummyPurchaseOrderItems2){
758                                 return dummyPurchaseOrderItems2.getDocumentNumber().compareTo(dummyPurchaseOrderItems1.getDocumentNumber());
759                             }
760                         });
761                         if (dummyPurchaseOrderItems != null && dummyPurchaseOrderItems.size() > 0) {
762                             String documentNumber = dummyPurchaseOrderItems.get(0).getDocumentNumber();
763                             olePurchaseOrderItems = new ArrayList<>();
764                             for(int itemCount = 0;itemCount < dummyPurchaseOrderItems.size();itemCount++){
765                                 if(documentNumber.equalsIgnoreCase(dummyPurchaseOrderItems.get(itemCount).getDocumentNumber())){
766                                     olePurchaseOrderItems.add(dummyPurchaseOrderItems.get(itemCount));
767                                 }
768                             }
769                         }
770                     }
771                     PurchaseOrderDocument purchaseOrderDocument = null;
772                     HashMap itemMap = new HashMap();
773                     if (olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) {
774 
775                         invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
776                         if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
777                             invoiceDocument.setPostingYear((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) ? olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() : null);
778                         }
779                         //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
780                         invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
781                         itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
782                         if (itemMap != null) {
783                             invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
784                             purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
785                         }
786                         //totalInvoiceProcessedCount = i+1;
787                     } else if (olePurchaseOrderItems == null || olePurchaseOrderItems.size() < 1) {
788                         if (invoiceRecord.getVendorNumber() != null && !invoiceRecord.getVendorNumber().isEmpty()) {
789                             if ((invoiceRecord.getISBN() != null && !invoiceRecord.getISBN().isEmpty() ||
790                                     (invoiceRecord.getISSN() != null && !invoiceRecord.getISSN().isEmpty()))) {
791                                 org.kuali.ole.docstore.common.search.SearchParams search_Params = new org.kuali.ole.docstore.common.search.SearchParams();
792                                 SearchResponse searchResponse = null;
793                                 // Retrieve bib id through solr query
794                                 //StringBuffer query = new StringBuffer("");
795                                 //List<HashMap<String, Object>> documentList1 = null;
796                                 //query.append("(ISBN_search:" + invoiceRecord.getISBN() + ")");
797                                 if  (invoiceRecord.getISBN() != null && !invoiceRecord.getISBN().isEmpty()) {
798                                     search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(),"common_identifier_search", invoiceRecord.getISBN()), ""));
799                                 }
800                                 if (invoiceRecord.getISSN() != null && !invoiceRecord.getISSN().isEmpty()) {
801                                     search_Params.getSearchConditions().add(search_Params.buildSearchCondition("", search_Params.buildSearchField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(),"common_identifier_search", invoiceRecord.getISSN()), ""));
802                                 }
803                                 search_Params.getSearchResultFields().add(search_Params.buildSearchResultField(org.kuali.ole.docstore.common.document.content.enums.DocType.BIB.getCode(), "id"));
804                                 String titleId = null;
805                                 searchResponse = getDocstoreClientLocator().getDocstoreClient().search(search_Params);
806                                 if (searchResponse.getSearchResults() != null && searchResponse.getSearchResults().size() > 0) {
807                                     titleId = searchResponse.getSearchResults().get(0).getSearchResultFields().get(0).getFieldValue() != null ? searchResponse.getSearchResults().get(0).getSearchResultFields().get(0).getFieldValue() : "";
808                                 }
809 
810 
811                                 //documentList1 = QueryServiceImpl.getInstance().retriveResults(query.toString());
812                                 //Map map1 = documentList1 != null && documentList1.size() > 0 ? documentList1.get(0) : null;
813 
814                                 //String titleId = map1 != null ? (String) map1.get("id") : null;
815 
816                                 Map itemTitleIdMap = new HashMap();
817                                 itemTitleIdMap.put("itemTitleId", titleId);
818                                 itemTitleIdMap.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorIds.length > 0 ? vendorIds[0] : "");
819                                 itemTitleIdMap.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorIds.length > 1 ? vendorIds[1] : "");
820                                 if (titleId != null) {
821                                     olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemTitleIdMap);
822 
823                                     invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
824                                     if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
825                                         invoiceDocument.setPostingYear(olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear());
826                                     }
827                                     //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
828                                     invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
829                                     itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
830                                     if (itemMap != null) {
831                                         invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
832                                         purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
833                                     }
834                                     // totalInvoiceProcessedCount = i+1;
835                                 } else if (olePurchaseOrderItems == null || olePurchaseOrderItems.size() < 1) {
836 
837                                     String[] vendorId = invoiceRecord.getVendorNumber() != null ? invoiceRecord.getVendorNumber().split("-") : new String[0];
838                                     Map itemTitleId = new HashMap();
839                                     itemTitleId.put("purchaseOrder.purapDocumentIdentifier", invoiceRecord.getPurchaseOrderNumber());
840                                     itemTitleId.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorId.length > 0 ? vendorId[0] : "");
841                                     itemTitleId.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorId.length > 1 ? vendorId[1] : "");
842                                     if (invoiceRecord.getPurchaseOrderNumber() != null) {
843                                         olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemTitleId);
844                                         if (olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) {
845                                             invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
846                                             if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
847                                                 invoiceDocument.setPostingYear(olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear());
848                                             }
849                                             //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
850                                             invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
851 
852                                             itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
853                                             if (itemMap != null) {
854                                                 invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
855                                                 purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
856                                             }
857                                             // totalInvoiceProcessedCount = i+1;
858                                         }
859                                     }
860                                 }
861                             }
862                             else if (invoiceRecord.getPurchaseOrderNumber() != null) {
863                                 String[] vendorId = invoiceRecord.getVendorNumber() != null ? invoiceRecord.getVendorNumber().split("-") : new String[0];
864                                 Map itemTitleId = new HashMap();
865                                 itemTitleId.put("purchaseOrder.purapDocumentIdentifier", invoiceRecord.getPurchaseOrderNumber());
866                                 itemTitleId.put("purchaseOrder.vendorHeaderGeneratedIdentifier", vendorId.length > 0 ? vendorId[0] : "");
867                                 itemTitleId.put("purchaseOrder.vendorDetailAssignedIdentifier", vendorId.length > 1 ? vendorId[1] : "");
868                                 if (invoiceRecord.getPurchaseOrderNumber() != null) {
869                                     olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService().findMatching(OlePurchaseOrderItem.class, itemTitleId);
870                                     if (olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0) {
871                                         invoiceRecord.setPurchaseOrderNumber((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null) ? olePurchaseOrderItems.get(0).getPurapDocumentIdentifier() : null);
872                                         if ((olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 && olePurchaseOrderItems.get(0) != null && olePurchaseOrderItems.get(0).getPurchaseOrder() != null && olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear() != null)) {
873                                             invoiceDocument.setPostingYear(olePurchaseOrderItems.get(0).getPurchaseOrder().getPostingYear());
874                                         }
875                                         //invoiceDocument.setProrateBy(org.kuali.ole.sys.OLEConstants.MANUAL_PRORATE);
876                                         invoiceDocument.setInvoicePayDate(SpringContext.getBean(InvoiceService.class).calculatePayDate(invoiceDocument.getInvoiceDate(), invoiceDocument.getVendorPaymentTerms()));
877 
878                                         itemMap = addInvoiceItem(olePurchaseOrderItems, invoiceRecord, invoiceDocument, purchaseOrderDocument, itemMap);
879                                         if (itemMap != null) {
880                                             invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
881                                             purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
882                                         }
883                                         // totalInvoiceProcessedCount = i+1;
884                                     }
885                                 }
886                             }
887                         }
888 
889 
890                     }
891                     if (purchaseOrderDocument != null) {
892                         for (OleInvoiceItem item : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
893                             if (invoiceRecord.getAdditionalChargeCode() != null && invoiceRecord.getAdditionalChargeCode().equalsIgnoreCase("SVC") && item.getItemTypeCode().equalsIgnoreCase("SPHD")) {
894                                 item.setItemUnitPrice(new BigDecimal(invoiceRecord.getAdditionalCharge() != null ? invoiceRecord.getAdditionalCharge() : invoiceRecord.getAdditionalCharge()));
895                                 item.setPurchaseOrderIdentifier(purchaseOrderDocument.getPurapDocumentIdentifier());
896                             } else if (invoiceRecord.getLineItemAdditionalChargeCode() != null && invoiceRecord.getLineItemAdditionalChargeCode().equalsIgnoreCase("LD") && item.getItemTypeCode().equalsIgnoreCase("ITEM")) {
897 
898                                 if ((item.getItemDescription().contains(invoiceRecord.getISBN())
899                                         || (invoiceRecord.getVendorItemIdentifier() != null ? invoiceRecord.getVendorItemIdentifier().equalsIgnoreCase(olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 ? item.getVendorItemIdentifier() : "") : false)
900                                         || (invoiceRecord.getPurchaseOrderNumber() != null ? invoiceRecord.getPurchaseOrderNumber().equals(item.getPurchaseOrderDocument() != null ? item.getPurchaseOrderDocument().getPurapDocumentIdentifier() : null) : false))) {
901 
902 
903                                     item.setItemDiscountType("%"); // % or #
904                                     item.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
905                                 }
906                             }
907                         }
908 
909                         String vendorNumber = purchaseOrderDocument.getVendorHeaderGeneratedIdentifier() + "-" + purchaseOrderDocument.getVendorDetailAssignedIdentifier();
910                         oleInvoiceService.populateVendorDetail(vendorNumber, invoiceDocument);
911                         invoiceDocument.setVendorCustomerNumber(invoiceRecord.getBillToCustomerID());
912                         if (invoiceDocument.getPaymentMethodId() != null) {
913                             invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
914                         } else {
915                             invoiceDocument.setPaymentMethodId(Integer.parseInt(OLEConstants.OleInvoiceImport.PAY_METHOD));
916                             invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
917                         }
918                         //   SpringContext.getBean(OleInvoiceService.class).calculateProrateItemSurcharge(invoiceDocument);
919                         SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(invoiceDocument);
920                         Long nextLinkIdentifier = SpringContext.getBean(SequenceAccessorService.class).getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID");
921                         invoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(nextLinkIdentifier.intValue());
922 
923 
924                         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))) {
925                             // set amounts on any empty
926                             invoiceDocument.updateExtendedPriceOnItems();
927 
928                             // calculation just for the tax area, only at tax review stage
929                             // by now, the general calculation shall have been done.
930                             if (invoiceDocument.getApplicationDocumentStatus().equals(PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
931                                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
932                             }
933 
934                             updatePrice(invoiceDocument);
935 
936                             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
937                             // Calculate Payment request before rules since the rule check totalAmount.
938                             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
939                             SpringContext.getBean(KualiRuleService.class).applyRules(
940                                     new AttributedCalculateAccountsPayableEvent(invoiceDocument));
941                         } else {
942                             // set amounts on any empty
943                             invoiceDocument.updateExtendedPriceOnItems();
944 
945                             // calculation just for the tax area, only at tax review stage
946                             // by now, the general calculation shall have been done.
947                             if (StringUtils.equals(invoiceDocument.getApplicationDocumentStatus(), PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
948                                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
949 
950                             }
951 
952                             updatePrice(invoiceDocument);
953 
954                             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
955                             //Calculate Payment request before rules since the rule check totalAmount.
956                             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
957                             SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument));
958                         }
959                         if (!SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedSaveDocumentEvent(invoiceDocument)) ||
960                                 !SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument))) {
961 
962 
963                             //}else {
964                             List invoiceIngestFailureReason = (List) dataCarrierService.getData("invoiceIngestFailureReason");
965                             if(invoiceIngestFailureReason != null && invoiceIngestFailureReason.size()>0){
966                                 for(int failCount = 0;failCount < invoiceIngestFailureReason.size();failCount++){
967                                     failureRecords.append(invoiceIngestFailureReason.get(failCount) + "\n");
968                                 }
969                             }
970                             LOG.info("Invoice Error Message------------------->");
971                             failureRecords.append("Unable to create Invoice document");
972                             failureRecords.append("\n");
973                             failureRecords.append("Invoice Number :" + invoiceRecord.getInvoiceNumber());
974                             failureRecords.append("\n");
975                             failureRecords.append("Invoice Date :" + invoiceDocument.getInvoiceDate());
976                             failureRecords.append("\n");
977                             if ((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")) != null) {
978                                 for (int error = 0; error < (GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).size(); error++) {
979                                     failureRecords.append("Error Message:" + kualiConfiguration.getPropertyValueAsString((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).get(error).getErrorKey()));
980                                     failureRecords.append("\n");
981                                 }
982                             }
983                             failureRecords.append("\n");
984                         }
985                     } else {
986                         if(marcXMLContent != null && StringUtils.isNotBlank(marcXMLContent.toString())){
987                             createInvoiceItem(invoiceRecord, invoiceDocument, itemMap);
988                         }
989                         else {
990                             createInvoiceItem(lineItemCount, invoiceRecord, invoiceDocument, itemMap);
991                         }
992                         invoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier((SpringContext.getBean(SequenceAccessorService.class).
993                                 getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID")).intValue());
994                         if (itemMap != null) {
995                             invoiceDocument = (OleInvoiceDocument) itemMap.get("invoiceDocument");
996                             purchaseOrderDocument = (PurchaseOrderDocument) itemMap.get("purchaseOrderDocument");
997                         }
998                         for (OleInvoiceItem item : (List<OleInvoiceItem>) invoiceDocument.getItems()) {
999                             if (invoiceRecord.getAdditionalChargeCode() != null && invoiceRecord.getAdditionalChargeCode().equalsIgnoreCase("SVC") && item.getItemTypeCode().equalsIgnoreCase("SPHD")) {
1000                                 item.setItemUnitPrice(new BigDecimal(invoiceRecord.getAdditionalCharge() != null ? invoiceRecord.getAdditionalCharge() : invoiceRecord.getAdditionalCharge()));
1001                                 item.setPurchaseOrderIdentifier(purchaseOrderDocument != null && purchaseOrderDocument.getPurapDocumentIdentifier() != null ?
1002                                         purchaseOrderDocument.getPurapDocumentIdentifier() : null);
1003                             } else if (invoiceRecord.getLineItemAdditionalChargeCode() != null && invoiceRecord.getLineItemAdditionalChargeCode().equalsIgnoreCase("LD") && item.getItemTypeCode().equalsIgnoreCase("ITEM")) {
1004 
1005                                 if ((item.getItemDescription().contains(invoiceRecord.getISBN())
1006                                         || (invoiceRecord.getVendorItemIdentifier() != null ? invoiceRecord.getVendorItemIdentifier().equalsIgnoreCase(olePurchaseOrderItems != null && olePurchaseOrderItems.size() > 0 ? item.getVendorItemIdentifier() : "") : false)
1007                                         || (invoiceRecord.getPurchaseOrderNumber() != null ? invoiceRecord.getPurchaseOrderNumber().equals(item.getPurchaseOrderDocument() != null ? item.getPurchaseOrderDocument().getPurapDocumentIdentifier(): null):false))) {
1008 
1009 
1010                                     item.setItemDiscountType("#"); // % or #
1011                                     item.setItemDiscount(new KualiDecimal(invoiceRecord.getLineItemAdditionalCharge() != null ? invoiceRecord.getLineItemAdditionalCharge() : invoiceRecord.getLineItemAdditionalCharge()));
1012                                 }
1013                             }
1014                         }
1015 
1016                         String vendorNumber = invoiceRecord.getVendorNumber();
1017                         oleInvoiceService.populateVendorDetail(vendorNumber, invoiceDocument);
1018                         invoiceDocument.setVendorCustomerNumber(invoiceRecord.getBillToCustomerID());
1019                         if (invoiceDocument.getPaymentMethodId() != null) {
1020                             invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
1021                         } else {
1022                             invoiceDocument.setPaymentMethodId(Integer.parseInt(OLEConstants.OleInvoiceImport.PAY_METHOD));
1023                             invoiceDocument.setPaymentMethodIdentifier(String.valueOf(invoiceDocument.getPaymentMethodId()));
1024                         }
1025                         //   SpringContext.getBean(OleInvoiceService.class).calculateProrateItemSurcharge(invoiceDocument);
1026                         SpringContext.getBean(PurapAccountingService.class).updateAccountAmounts(invoiceDocument);
1027                         Long nextLinkIdentifier = SpringContext.getBean(SequenceAccessorService.class).getNextAvailableSequenceNumber("AP_PUR_DOC_LNK_ID");
1028                         // invoiceDocument.setAccountsPayablePurchasingDocumentLinkIdentifier(nextLinkIdentifier.intValue());
1029 
1030 
1031                         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))) {
1032                             // set amounts on any empty
1033                             invoiceDocument.updateExtendedPriceOnItems();
1034 
1035                             // calculation just for the tax area, only at tax review stage
1036                             // by now, the general calculation shall have been done.
1037                             if (invoiceDocument.getApplicationDocumentStatus().equals(PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
1038                                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
1039                             }
1040 
1041                             updatePrice(invoiceDocument);
1042 
1043                             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
1044                             // Calculate Payment request before rules since the rule check totalAmount.
1045                             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
1046                             SpringContext.getBean(KualiRuleService.class).applyRules(
1047                                     new AttributedCalculateAccountsPayableEvent(invoiceDocument));
1048                         } else {
1049                             // set amounts on any empty
1050                             invoiceDocument.updateExtendedPriceOnItems();
1051 
1052                             // calculation just for the tax area, only at tax review stage
1053                             // by now, the general calculation shall have been done.
1054                             if (StringUtils.equals(invoiceDocument.getApplicationDocumentStatus(), PurapConstants.PaymentRequestStatuses.APPDOC_AWAITING_TAX_REVIEW)) {
1055                                 SpringContext.getBean(OleInvoiceService.class).calculateTaxArea(invoiceDocument);
1056 
1057                             }
1058 
1059                             updatePrice(invoiceDocument);
1060 
1061                             // notice we're ignoring whether the boolean, because these are just warnings they shouldn't halt anything
1062                             //Calculate Payment request before rules since the rule check totalAmount.
1063                             SpringContext.getBean(OleInvoiceService.class).calculateInvoice(invoiceDocument, true);
1064                             SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument));
1065                         }
1066 
1067 
1068                     }
1069                 }
1070             if (!"".equals(failureRecords.toString())) {
1071                 createBatchErrorAttachmentFile(failureRecords.toString());
1072             }
1073             allInvoiceDocument.add(invoiceDocument);
1074         }
1075         deleteBatchFile();
1076         if (allInvoiceDocument != null && !allInvoiceDocument.isEmpty()) {
1077             for (int process = 0; process < allInvoiceDocument.size(); process++) {
1078                 invoiceDocument = allInvoiceDocument.get(process);
1079                 if (invoiceDocument.getAccountsPayablePurchasingDocumentLinkIdentifier() != null) {
1080                     if (SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedSaveDocumentEvent(invoiceDocument)) &&
1081                             SpringContext.getBean(KualiRuleService.class).applyRules(new AttributedCalculateAccountsPayableEvent(invoiceDocument))) {
1082 
1083                         try {
1084                             OLEInvoiceIngestLoadReport oleInvoiceIngestLoadReport =new OLEInvoiceIngestLoadReport();
1085                             oleInvoiceIngestLoadReport.setFileName(job.getUploadFileName());
1086                             java.sql.Date sqlDate = new java.sql.Date(new Date(System.currentTimeMillis()).getTime());
1087                             oleInvoiceIngestLoadReport.setDateUploaded(sqlDate);
1088                             oleInvoiceIngestLoadReport.setVendor(invoiceDocument.getVendorNumber());
1089                             getBusinessObjectService().save(oleInvoiceIngestLoadReport);
1090                             oleInvoiceService.autoApprovePaymentRequest(invoiceDocument);
1091                             successCount = process + 1;
1092                         } catch (Exception e) {
1093                             LOG.info("Invoice Error Message------------------->");
1094                             failureRecords.append("Unable to create Invoice document");
1095                             failureRecords.append("\n");
1096                             failureRecords.append("Invoice Number :" + invoiceRecord.getInvoiceNumber());
1097                             failureRecords.append("\n");
1098                             failureRecords.append("Invoice Date :" + invoiceDocument.getInvoiceDate());
1099                             failureRecords.append("\n");
1100                             if ((GlobalVariables.getMessageMap() != null && GlobalVariables.getMessageMap().getErrorMessages() != null) &&
1101                                     ((GlobalVariables.getMessageMap().getErrorMessages().size() > 0 ) ||
1102                                     (GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")) != null)) {
1103                                 for (int error = 0; error < (GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).size(); error++) {
1104                                     failureRecords.append("Error Message:" + kualiConfiguration.getPropertyValueAsString((GlobalVariables.getMessageMap().getErrorMessages().get("GLOBAL_ERRORS")).get(error).getErrorKey()));
1105                                     failureRecords.append("\n");
1106                                 }
1107                             } else {
1108                                 failureRecords.append("Error Message:" + e.initCause(new Throwable()));
1109                             }
1110                             failureRecords.append("\n");
1111                             failureRecords.append("\n");
1112 
1113                         }
1114 
1115                         job.setTotalNoOfRecords(totalInvoiceFileCount + "");
1116                         job.setNoOfRecordsProcessed(totalInvoiceFileCount + "");
1117                         job.setNoOfSuccessRecords(String.valueOf(successCount));
1118                         job.setNoOfFailureRecords(String.valueOf(totalInvoiceFileCount - successCount));
1119                         job.setStatusDesc(OLEConstants.INVOICE_UPLOAD_SUCCESS);
1120                         job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1121                         deleteBatchFile();
1122                         if (!"".equals(failureRecords.toString())) {
1123                             createBatchErrorAttachmentFile(failureRecords.toString());
1124                         }
1125                     }
1126                     else {
1127                         if ((GlobalVariables.getMessageMap() != null &&
1128                                 GlobalVariables.getMessageMap().getErrorMessages() != null &&
1129                                 GlobalVariables.getMessageMap().hasErrors()) &&
1130                                 (GlobalVariables.getMessageMap().getErrorMessages().size() > 0 )) {
1131                                 Map<String, AutoPopulatingList<ErrorMessage>> errorMap = GlobalVariables.getMessageMap().getErrorMessages();
1132                                 for (Map.Entry<String, AutoPopulatingList<ErrorMessage>> entry : errorMap.entrySet()) {
1133                                     AutoPopulatingList<ErrorMessage> errors = entry.getValue();
1134                                     ErrorMessage error = errors.get(0);
1135                                     String[] params = error.getMessageParameters();
1136                                     String param = params[0];
1137                                     if (param.toUpperCase().contains("ITEM")) {
1138                                         param = "ITEM";
1139                                     }
1140                                     failureRecords.append("Error Message:" + kualiConfiguration.getPropertyValueAsString(param));
1141                                     failureRecords.append("\n");
1142                             }
1143                         }
1144                         job.setTotalNoOfRecords(totalInvoiceFileCount + "");
1145                         job.setNoOfRecordsProcessed(totalInvoiceFileCount + "");
1146                         job.setNoOfSuccessRecords(String.valueOf(successCount));
1147                         job.setNoOfFailureRecords(String.valueOf(totalInvoiceFileCount - successCount));
1148                         job.setStatusDesc(OLEConstants.INVOICE_UPLOAD_SUCCESS);
1149                         job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1150                         deleteBatchFile();
1151                         if (!"".equals(failureRecords.toString())) {
1152                             createBatchErrorAttachmentFile(failureRecords.toString());
1153                         }
1154                     }
1155                     job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1156                 }
1157                 job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1158             }
1159             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1160         }
1161         if (successCount == 0) {
1162             OLEBatchProcessJobDetailsController.setBatchProcessJobStatusMap(job.getJobId(),OLEConstants.OLEBatchProcess.JOB_STATUS_STOPPED);
1163             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_STOPPED);
1164         } else {
1165             OLEBatchProcessJobDetailsController.setBatchProcessJobStatusMap(job.getJobId(),OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1166             job.setStatus(OLEConstants.OLEBatchProcess.JOB_STATUS_COMPLETED);
1167         }
1168     }
1169 
1170     private void setDocumentForeignDetails(OleInvoiceDocument invoiceDocument,OleInvoiceRecord invoiceRecord){
1171         OleCurrencyType oleCurrencyType = getBusinessObjectService().findBySinglePrimaryKey(OleCurrencyType.class,invoiceRecord.getCurrencyTypeId());
1172         invoiceDocument.setInvoiceCurrencyType(oleCurrencyType.getCurrencyTypeId().toString());
1173         if(!oleCurrencyType.getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
1174             Map documentNumberMap = new HashMap();
1175             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, invoiceRecord.getCurrencyTypeId());
1176             List<OleExchangeRate> exchangeRateList = (List) getBusinessObjectService().findMatchingOrderBy(
1177                     OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
1178             Iterator iterator = exchangeRateList.iterator();
1179             if (iterator.hasNext()) {
1180                 invoiceDocument.setForeignVendorInvoiceAmount(new BigDecimal(0.00));
1181                 invoiceDocument.setInvoiceCurrencyTypeId(new Long(invoiceRecord.getCurrencyTypeId()));
1182                 invoiceDocument.setInvoiceCurrencyExchangeRate(invoiceRecord.getInvoiceCurrencyExchangeRate());
1183             }
1184         }
1185     }
1186 
1187     public boolean validateVendorNumber(String vendorNumber){
1188         LOG.info("----Inside validateVendorNumber()------------------------------");
1189         boolean isValidVendor = false;
1190         if(vendorNumber != null){
1191             String[] vendorDetail = vendorNumber.split("-");
1192             if(vendorDetail.length == 2){
1193                 String vendorHeaderGeneratedIdentifier = vendorDetail[0];
1194                 String vendorDetailAssignedIdentifier = vendorDetail[1];
1195                 try {
1196                     Map<String,Integer> vendorMap = new HashMap<>();
1197                     vendorMap.put(OLEConstants.VENDOR_HEADER_GENERATED_ID, Integer.parseInt(vendorHeaderGeneratedIdentifier));
1198                     vendorMap.put(OLEConstants.VENDOR_DETAILED_ASSIGNED_ID, Integer.parseInt(vendorDetailAssignedIdentifier));
1199                     List<VendorDetail> vendorDetailList = (List) getBusinessObjectService().findMatching(VendorDetail.class, vendorMap);
1200                     if(vendorDetail != null && vendorDetailList.size() > 0){
1201                         isValidVendor  = true;
1202                         return isValidVendor;
1203                     }
1204                 }
1205                 catch (NumberFormatException nfe) {
1206                     return isValidVendor;
1207                 }
1208             }
1209         }
1210         return isValidVendor;
1211     }
1212 
1213     public boolean validateForNumber(String fieldValue){
1214         try {
1215             Integer quantity = Integer.parseInt(fieldValue);
1216             if(quantity <= 0){
1217                 return false;
1218             }
1219         }
1220         catch(NumberFormatException nfe){
1221             return false;
1222         }
1223         return true;
1224     }
1225 
1226     public boolean validateDestinationFieldValues(String destinationFieldValue){
1227         try {
1228             Float fieldValue = Float.parseFloat(destinationFieldValue);
1229             if(fieldValue <= 0){
1230                 return false;
1231             }
1232         }
1233         catch(NumberFormatException nfe){
1234             return false;
1235         }
1236         return true;
1237     }
1238 
1239     @Override
1240     public void getNextBatch() {
1241         //To change body of implemented methods use File | Settings | File Templates.
1242     }
1243 
1244     @Override
1245     public void processBatch() {
1246         //To change body of implemented methods use File | Settings | File Templates.
1247     }
1248 
1249 }