View Javadoc
1   /*
2    * Copyright 2011 The Kuali Foundation.
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.ole.select.service.impl;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.kuali.ole.DataCarrierService;
20  import org.kuali.ole.OLEConstants;
21  import org.kuali.ole.OleOrderRecords;
22  import org.kuali.ole.batch.bo.OLEBatchProcessJobDetailsBo;
23  import org.kuali.ole.batch.bo.OLEBatchProcessProfileBo;
24  import org.kuali.ole.batch.bo.OrderImportHelperBo;
25  import org.kuali.ole.docstore.common.client.DocstoreClientLocator;
26  import org.kuali.ole.docstore.common.document.Holdings;
27  import org.kuali.ole.docstore.common.document.ids.HoldingsId;
28  import org.kuali.ole.module.purap.PurapConstants;
29  import org.kuali.ole.module.purap.PurapPropertyConstants;
30  import org.kuali.ole.module.purap.businessobject.*;
31  import org.kuali.ole.module.purap.document.RequisitionDocument;
32  import org.kuali.ole.module.purap.document.service.OlePurapService;
33  import org.kuali.ole.module.purap.document.service.RequisitionService;
34  import org.kuali.ole.pojo.OleOrderRecord;
35  import org.kuali.ole.pojo.OleTxRecord;
36  import org.kuali.ole.select.OleSelectConstant;
37  import org.kuali.ole.select.OleSelectNotificationConstant;
38  import org.kuali.ole.select.batch.service.RequisitionCreateDocumentService;
39  import org.kuali.ole.select.batch.service.impl.RequisitionCreateDocumentServiceImpl;
40  import org.kuali.ole.select.bo.OLEDonor;
41  import org.kuali.ole.select.bo.OLELinkPurapDonor;
42  import org.kuali.ole.select.businessobject.*;
43  import org.kuali.ole.select.document.OleRequisitionDocument;
44  import org.kuali.ole.select.document.service.OleRequestSourceService;
45  import org.kuali.ole.select.document.service.OleRequestorService;
46  import org.kuali.ole.select.document.service.OleSelectDocumentService;
47  import org.kuali.ole.select.service.BibInfoService;
48  import org.kuali.ole.select.service.OleReqPOCreateDocumentService;
49  import org.kuali.ole.sys.OLEConstants.FinancialDocumentTypeCodes;
50  import org.kuali.ole.sys.businessobject.Building;
51  import org.kuali.ole.sys.businessobject.Room;
52  import org.kuali.ole.sys.context.SpringContext;
53  import org.kuali.ole.vnd.VendorConstants;
54  import org.kuali.ole.vnd.VendorPropertyConstants;
55  import org.kuali.ole.vnd.businessobject.OleExchangeRate;
56  import org.kuali.ole.vnd.businessobject.VendorAddress;
57  import org.kuali.ole.vnd.businessobject.VendorContract;
58  import org.kuali.ole.vnd.businessobject.VendorDetail;
59  import org.kuali.ole.vnd.document.service.VendorService;
60  import org.kuali.rice.core.api.config.property.ConfigurationService;
61  import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
62  import org.kuali.rice.core.api.util.type.KualiDecimal;
63  import org.kuali.rice.core.api.util.type.KualiInteger;
64  import org.kuali.rice.kew.api.exception.WorkflowException;
65  import org.kuali.rice.krad.UserSession;
66  import org.kuali.rice.krad.service.BusinessObjectService;
67  import org.kuali.rice.krad.service.DocumentService;
68  import org.kuali.rice.krad.util.GlobalVariables;
69  import org.kuali.rice.krad.util.MessageMap;
70  import org.kuali.rice.krad.util.ObjectUtils;
71  import java.math.BigDecimal;
72  import java.math.RoundingMode;
73  import java.text.SimpleDateFormat;
74  import java.util.*;
75  
76  public class OleReqPOCreateDocumentServiceImpl extends RequisitionCreateDocumentServiceImpl implements OleReqPOCreateDocumentService {
77      private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OleReqPOCreateDocumentServiceImpl.class);
78  
79      protected RequisitionCreateDocumentService requisitionCreateDocumentService;
80      protected OleRequestorService oleRequestorService;
81      protected VendorService vendorService;
82      protected OleRequestSourceService oleRequestSourceService;
83      protected OlePurapService olePurapService;
84      protected BusinessObjectService businessObjectService;
85      protected DocumentService documentService;
86      protected BibInfoService bibInfoService;
87      protected ConfigurationService kualiConfigurationService;
88      private DocstoreClientLocator docstoreClientLocator;
89      private OlePatronDocumentList olePatronDocumentList;
90      private OleSelectDocumentService oleSelectDocumentService;
91      private boolean currencyTypeIndicator = true;
92  
93      public OleSelectDocumentService getOleSelectDocumentService() {
94          if (oleSelectDocumentService == null) {
95              oleSelectDocumentService = SpringContext.getBean(OleSelectDocumentService.class);
96          }
97          return oleSelectDocumentService;
98      }
99  
100     public void setOleSelectDocumentService(OleSelectDocumentService oleSelectDocumentService) {
101         this.oleSelectDocumentService = oleSelectDocumentService;
102     }
103 
104     public OlePatronDocumentList getOlePatronDocumentList() {
105         if (olePatronDocumentList == null) {
106             olePatronDocumentList = SpringContext.getBean(OlePatronDocumentList.class);
107         }
108         return olePatronDocumentList;
109     }
110 
111     public BusinessObjectService getBusinessObjectService() {
112         if (businessObjectService == null) {
113             businessObjectService = SpringContext.getBean(BusinessObjectService.class);
114         }
115         return businessObjectService;
116     }
117 
118     public DocstoreClientLocator getDocstoreClientLocator() {
119 
120         if (docstoreClientLocator == null) {
121             docstoreClientLocator = SpringContext.getBean(DocstoreClientLocator.class);
122 
123         }
124         return docstoreClientLocator;
125     }
126 
127     /**
128      * Set the values for the Requisition Document and save.
129      *
130      * @param oleOrderRecords OleOrderRecords
131      */
132     public void saveRequisitionDocument(OleOrderRecords oleOrderRecords, OLEBatchProcessJobDetailsBo job) throws Exception {
133         OrderImportHelperBo orderImportHelperBo = job.getOrderImportHelperBo();
134         String isValidBFN = "";
135         vendorService = getVendorService();
136         oleRequestorService = getOleRequestorService();
137         requisitionCreateDocumentService = getRequisitionCreateDocumentService();
138         oleRequestSourceService = getOleRequestSourceService();
139         olePurapService = getOlePurapService();
140         setUserFromStaffUpload(oleOrderRecords);
141         //DataCarrierService dataCarrierService = GlobalResourceLoader.getService(org.kuali.ole.OLEConstants.DATA_CARRIER_SERVICE);
142         //oleBatchProcessProfileBo = (OLEBatchProcessProfileBo) dataCarrierService.getData(org.kuali.ole.OLEConstants.BATCH_PROFILE_BO);
143         OLEBatchProcessProfileBo oleBatchProcessProfileBo = orderImportHelperBo.getOleBatchProcessProfileBo();
144         String requisitionsForTitle = null;
145         if(oleBatchProcessProfileBo != null){
146             requisitionsForTitle = oleBatchProcessProfileBo.getRequisitionsforTitle();
147         }
148         if (oleBatchProcessProfileBo != null && requisitionsForTitle.equalsIgnoreCase(OLEConstants.ONE_REQUISITION_PER_TITLE)) {
149             orderImportHelperBo.setReqList(new ArrayList(0));
150             List<OleOrderRecord> oleOrderRecordList = oleOrderRecords.getRecords();
151             for (int recCount = 0;recCount < oleOrderRecordList.size();recCount++) {
152                 OleOrderRecord oleOrderRecord = oleOrderRecordList.get(recCount);
153                 oleOrderRecord.getMessageMap().put(OLEConstants.IS_APO_RULE, false);
154                 String isValidRecord = ((oleOrderRecord.getMessageMap().get(OLEConstants.IS_VALID_RECORD))).toString();
155                 if (OLEConstants.TRUE.equalsIgnoreCase(isValidRecord)) {
156                     isValidBFN = ((oleOrderRecord.getMessageMap().get(OLEConstants.IS_VALID_BFN))).toString();
157                     if (isValidBFN.equalsIgnoreCase(OLEConstants.TRUE)) {
158                         if ( oleOrderRecord.getOleTxRecord() != null && oleOrderRecord.getOleBibRecord() != null) {
159                             OleRequisitionDocument requisitionDocument = null;
160                             try {
161                                 requisitionDocument = createRequisitionDocument();
162                                 requisitionDocument.setRequisitionSourceCode(oleOrderRecord.getOleTxRecord().getRequisitionSource());
163                                 if (oleOrderRecordList != null && oleOrderRecordList.size() > 0) {
164                                     if (oleOrderRecord.getOleTxRecord().getOrderType() != null) {
165                                         Map purchaseOrderTypeMap = new HashMap();
166                                         purchaseOrderTypeMap.put(OLEConstants.PO_TYPE, oleOrderRecord.getOleTxRecord().getOrderType());
167                                         List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List)getBusinessObjectService().findMatching(PurchaseOrderType.class, purchaseOrderTypeMap);
168                                         if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
169                                             requisitionDocument.setPurchaseOrderTypeId(purchaseOrderTypeDocumentList.get(0).getPurchaseOrderTypeId());
170                                         }
171                                     }
172                                     else {
173                                         requisitionDocument.setPurchaseOrderTypeId(OLEConstants.DEFAULT_ORDER_TYPE_VALUE);
174                                     }
175                                     setDocumentValues(requisitionDocument, oleOrderRecord,job,recCount);
176                                 }
177                                 requisitionDocument.setItems(generateItemList(oleOrderRecord, job,requisitionDocument));
178                                 RequisitionService requisitionService = SpringContext.getBean(RequisitionService.class);
179                               //  requisitionDocument.getDocumentHeader().getWorkflowDocument();
180                                 boolean apoRuleFlag = requisitionService.isAutomaticPurchaseOrderAllowed(requisitionDocument);
181                                 if (!apoRuleFlag) {
182                                     oleOrderRecord.getMessageMap().put(OLEConstants.IS_APO_RULE, true);
183                                 }
184                                 if(LOG.isDebugEnabled()){
185                                     LOG.debug("before calling saveRequisitionDocuments");
186                                 }
187                                 requisitionDocument.setApplicationDocumentStatus(PurapConstants.RequisitionStatuses.APPDOC_IN_PROCESS);
188                                 requisitionCreateDocumentService.saveRequisitionDocuments(requisitionDocument);
189                                 //dataCarrierService.addData(OLEConstants.ORDER_IMPORT_SUCCESS_COUNT,(int) dataCarrierService.getData(OLEConstants.ORDER_IMPORT_SUCCESS_COUNT)+1);
190                                 orderImportHelperBo.setOrderImportSuccessCount(orderImportHelperBo.getOrderImportSuccessCount()+1);
191                                 if(!oleBatchProcessProfileBo.getMarcOnly()){
192                                     orderImportHelperBo.setCreateBibCount(orderImportHelperBo.getOrderImportSuccessCount());
193                                 }
194                                 orderImportHelperBo.getReqList().add(requisitionDocument.getPurapDocumentIdentifier());
195                             }
196                             catch (Exception ex) {
197                                 LOG.error("####Rollback####" + ex);
198                                 orderImportHelperBo.setOrderImportFailureCount(orderImportHelperBo.getOrderImportFailureCount()+1);
199                                 oleOrderRecord.addMessageToMap(OLEConstants.IS_VALID_RECORD,false);
200                                 GlobalVariables.setMessageMap(new MessageMap());
201                                 /*dataCarrierService.addData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT,(int) dataCarrierService.getData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT)+1);
202                                 Iterator<OleRequisitionItem> iterator = requisitionDocument.getItems().iterator();
203                                 while (iterator.hasNext()) {
204                                     OleRequisitionItem item = iterator.next();
205                                     getDocstoreClientLocator().getDocstoreClient().deleteBib(item.getBibUUID());
206                                 }
207                                 throw ex;*/
208                             }
209                         }
210                     }
211                 }
212             }
213         }
214         else if(oleBatchProcessProfileBo != null && requisitionsForTitle.equalsIgnoreCase(OLEConstants.ONE_REQUISITION_WITH_ALL_TITLES)){
215             orderImportHelperBo.setReqList(new ArrayList(0));
216             List<OleOrderRecord> oleOrderRecordList = oleOrderRecords.getRecords();
217             OleRequisitionDocument requisitionDocument = null;
218             List<OleOrderRecord> validRecords = new ArrayList<OleOrderRecord>();
219             for (OleOrderRecord oleOrderRecord : oleOrderRecordList) {
220                 oleOrderRecord.getMessageMap().put(OLEConstants.IS_APO_RULE, false);
221                 String isValidRecord = ((oleOrderRecord.getMessageMap().get(OLEConstants.IS_VALID_RECORD))).toString();
222                 if (OLEConstants.TRUE.equalsIgnoreCase(isValidRecord)) {
223                     isValidBFN = ((oleOrderRecord.getMessageMap().get(OLEConstants.IS_VALID_BFN))).toString();
224                     if (isValidBFN.equalsIgnoreCase(OLEConstants.TRUE)) {
225                         if (oleOrderRecord.getOleTxRecord() != null && oleOrderRecord.getOleBibRecord() != null) {
226                             validRecords.add(oleOrderRecord);
227                         }
228                     }
229                 }
230             }
231             try {
232                 if(oleOrderRecordList.size() == validRecords.size()){
233                     requisitionDocument = createRequisitionDocument();
234                     requisitionDocument.setRequisitionSourceCode(oleOrderRecordList.get(0).getOleTxRecord().getRequisitionSource());
235                     if (oleOrderRecordList != null && oleOrderRecordList.size() > 0) {
236                         if (oleOrderRecordList.get(0).getOleTxRecord().getOrderType() != null) {
237                             Map purchaseOrderTypeMap = new HashMap();
238                             purchaseOrderTypeMap.put(OLEConstants.PO_TYPE, oleOrderRecordList.get(0).getOleTxRecord().getOrderType());
239                             org.kuali.rice.krad.service.BusinessObjectService
240                                     businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
241                             List<PurchaseOrderType> purchaseOrderTypeDocumentList = (List) businessObjectService.findMatching(PurchaseOrderType.class, purchaseOrderTypeMap);
242                             if (purchaseOrderTypeDocumentList != null && purchaseOrderTypeDocumentList.size() > 0) {
243                                 requisitionDocument.setPurchaseOrderTypeId(purchaseOrderTypeDocumentList.get(0).getPurchaseOrderTypeId());
244                             }
245                         }
246                         else {
247                             requisitionDocument.setPurchaseOrderTypeId(OLEConstants.DEFAULT_ORDER_TYPE_VALUE);
248                         }
249                         setDocumentValues(requisitionDocument, oleOrderRecordList.get(0),job,0);
250                     }
251                     requisitionDocument.setItems(generateMultipleItemsForOneRequisition(oleOrderRecordList, job,requisitionDocument));
252                     requisitionDocument.getDocumentHeader().getWorkflowDocument();
253                     requisitionDocument.setApplicationDocumentStatus(PurapConstants.RequisitionStatuses.APPDOC_IN_PROCESS);
254                     getRequisitionCreateDocumentService().saveRequisitionDocuments(requisitionDocument);
255                     //dataCarrierService.addData(OLEConstants.ORDER_IMPORT_SUCCESS_COUNT,(int) dataCarrierService.getData(OLEConstants.ORDER_IMPORT_SUCCESS_COUNT)+validRecords.size());
256                     orderImportHelperBo.setOrderImportSuccessCount(orderImportHelperBo.getOrderImportSuccessCount()+validRecords.size());
257                     orderImportHelperBo.getReqList().add(requisitionDocument.getPurapDocumentIdentifier());
258                 }
259                 else {
260                     if(validRecords != null && validRecords.size() > 0){
261                         List<String> uuidList = new ArrayList<>();
262                         for(int recCount = 0;recCount<validRecords.size();recCount++) {
263                             uuidList.add(validRecords.get(recCount).getOleBibRecord().getBibUUID());
264                         }
265                         //dataCarrierService.addData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT,(int) dataCarrierService.getData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT)+uuidList.size());
266                         orderImportHelperBo.setOrderImportFailureCount(orderImportHelperBo.getOrderImportFailureCount()+uuidList.size());
267                         /*getDocstoreClientLocator().getDocstoreClient().deleteBibs(uuidList);*/
268                     }
269                 }
270             }
271             catch(Exception ex){
272                 LOG.error("####Rollback####" + ex);
273                 //dataCarrierService.addData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT,(int) dataCarrierService.getData(OLEConstants.ORDER_IMPORT_FAILURE_COUNT)+uuidList.size());
274                 List<String> uuidList = new ArrayList<>();
275                 for(int recCount = 0;recCount<oleOrderRecordList.size();recCount++) {
276                     uuidList.add(oleOrderRecordList.get(recCount).getOleBibRecord().getBibUUID());
277                 }
278                 orderImportHelperBo.setOrderImportFailureCount(orderImportHelperBo.getOrderImportFailureCount()+uuidList.size());
279                 /*getDocstoreClientLocator().getDocstoreClient().deleteBibs(uuidList);*/
280             }
281         }
282     }
283 
284 
285     /**
286      * To create the Requisition document object
287      *
288      * @return OleRequisitionDocument
289      */
290     protected OleRequisitionDocument createRequisitionDocument() throws WorkflowException {
291         String user;
292         if (GlobalVariables.getUserSession() == null) {
293             user = getConfigurationService().getPropertyValueAsString(getOleSelectDocumentService().getSelectParameterValue(OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR));
294             if(LOG.isDebugEnabled()){
295                 LOG.debug("createRequisitionDocument - user from session"+user);
296             }
297             GlobalVariables.setUserSession(new UserSession(user));
298         }
299 
300         return (OleRequisitionDocument) SpringContext.getBean(DocumentService.class).getNewDocument(FinancialDocumentTypeCodes.REQUISITION);
301     }
302 
303     private void setUserFromStaffUpload(OleOrderRecords oleOrderRecords) {
304         List<OleOrderRecord> oleOrderRecordList = oleOrderRecords.getRecords();
305         String user = null;
306         if (oleOrderRecordList.size() > 0) {
307             user = GlobalVariables.getUserSession().getPrincipalName();
308             if (user == null) {
309                 user = getConfigurationService().getPropertyValueAsString(
310                         getOleSelectDocumentService().getSelectParameterValue(OleSelectNotificationConstant.ACCOUNT_DOCUMENT_INTIATOR));
311             }
312             GlobalVariables.setUserSession(new UserSession(user));
313         }
314     }
315 
316     /**
317      * To create the requisition document
318      *
319      * @param requisitionDocument OleRequisitionDocument
320      * @param oleOrderRecord      OleOrderRecord
321      * @return RequisitionDocument
322      */
323     protected RequisitionDocument setDocumentValues(OleRequisitionDocument requisitionDocument, OleOrderRecord oleOrderRecord,OLEBatchProcessJobDetailsBo job,int recPosition) throws Exception {
324         // ******************Document Overview Section******************
325         requisitionDocument.setStatusCode(PurapConstants.RequisitionStatuses.APPDOC_IN_PROCESS);
326         /**
327          * Commented vendorPoNumber based on JIRA-2842
328          */
329         //requisitionDocument.setVendorPoNumber(oleOrderRecord.getOleTxRecord().getVendorNumber());
330         requisitionDocument.setVendorPoNumber(oleOrderRecord.getOleTxRecord().getVendorItemIdentifier());
331         // ******************Financial Document Detail Section******************
332         // ******************Requisition Detail Section******************
333         requisitionDocument.setChartOfAccountsCode(oleOrderRecord.getOleTxRecord().getChartCode());
334         requisitionDocument.setOrganizationCode(oleOrderRecord.getOleTxRecord().getOrgCode());
335         requisitionDocument.setDocumentFundingSourceCode(oleOrderRecord.getOleTxRecord().getFundingSource());
336         requisitionDocument.setUseTaxIndicator(true);//oleOrderRecord.getOleTxRecord().getUseTaxIndicator()
337         // ******************Delivery Section******************
338         setDeliveryDetails(requisitionDocument, oleOrderRecord);
339         requisitionDocument.setDeliveryCampusCode(oleOrderRecord.getOleTxRecord().getDeliveryCampusCode());
340         // ******************Vendor Section******************
341         setVendorDetails(requisitionDocument, oleOrderRecord);
342         // ******************Items Section******************
343         // ******************Capital Assets Section******************
344         // ******************Payment INfo Section******************
345         setRecurringPaymentInfo(requisitionDocument,oleOrderRecord);
346         // ******************Additional Institutional Info Section******************
347         requisitionDocument.getDocumentHeader().setDocumentDescription(getDocumentDescription(requisitionDocument, oleOrderRecord,job,recPosition));
348         requisitionDocument.setPurchaseOrderTransmissionMethodCode(getTransmissionMethodCode(oleOrderRecord.getOleTxRecord().getMethodOfPOTransmission()));//FAX
349         requisitionDocument.setPurchaseOrderCostSourceCode(oleOrderRecord.getOleTxRecord().getCostSource());//CON
350         requisitionDocument.setRequestorPersonName(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_NAME));
351         requisitionDocument.setRequestorPersonPhoneNumber(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_PHONE_NUMBER));
352         requisitionDocument.setRequestorPersonEmailAddress(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.REQUESTOR_PERSON_EMAIL_ADDRESS));
353         requisitionDocument.setOrganizationAutomaticPurchaseOrderLimit(new KualiDecimal(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.VENDOR_CONTRACT_DEFAULT_APO_LIMIT)));
354         requisitionDocument.setPurchaseOrderAutomaticIndicator(Boolean.parseBoolean(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.PURCHASE_ORDER_AUTOMATIC_INDICATIOR)));
355         requisitionDocument.setReceivingDocumentRequiredIndicator(oleOrderRecord.getOleTxRecord().isReceivingRequired());
356         requisitionDocument.setPaymentRequestPositiveApprovalIndicator(oleOrderRecord.getOleTxRecord().isPayReqPositiveApprovalReq());
357         requisitionDocument.setRequisitionSourceCode(oleOrderRecord.getOleTxRecord().getRequisitionSource());
358         return requisitionDocument;
359 
360     }
361 
362     private void setItemNotes(OleRequisitionItem item,OleTxRecord oleTxRecord){
363         if(StringUtils.isNotBlank(oleTxRecord.getMiscellaneousNote())){
364             setNoteTypeValues(item,oleTxRecord.getMiscellaneousNote(),oleTxRecord.getMiscellaneousNotes());
365         }
366         if(StringUtils.isNotBlank(oleTxRecord.getReceiptNote())){
367             setNoteTypeValues(item,oleTxRecord.getReceiptNote(),oleTxRecord.getReceiptNotes());
368         }
369         if(StringUtils.isNotBlank(oleTxRecord.getRequestorNote())){
370             setNoteTypeValues(item,oleTxRecord.getRequestorNote(),oleTxRecord.getRequestorNotes());
371         }
372         if(StringUtils.isNotBlank(oleTxRecord.getSelectorNote())){
373             setNoteTypeValues(item,oleTxRecord.getSelectorNote(),oleTxRecord.getSelectorNotes());
374         }
375         if(StringUtils.isNotBlank(oleTxRecord.getSplProcessInstrNote())){
376             setNoteTypeValues(item,oleTxRecord.getSplProcessInstrNote(),oleTxRecord.getSplProcessInstrNotes());
377         }
378         if(StringUtils.isNotBlank(oleTxRecord.getVendorInstrNote())){
379             setNoteTypeValues(item,oleTxRecord.getVendorInstrNote(),oleTxRecord.getVendorInstrNotes());
380         }
381     }
382 
383     private String getTransmissionMethodCode(String transmissionMethodDescription){
384         Map<String,String> transmissionCodeMap = new HashMap<>();
385         transmissionCodeMap.put(OLEConstants.OLEBatchProcess.PO_TRANSMISSION_METHOD_DESC,transmissionMethodDescription);
386         List<PurchaseOrderTransmissionMethod> transmissionMethodList = (List<PurchaseOrderTransmissionMethod>) getBusinessObjectService().findMatching(PurchaseOrderTransmissionMethod.class,transmissionCodeMap);
387         if(transmissionMethodList != null && transmissionMethodList.size() >0){
388             return transmissionMethodList.get(0).getPurchaseOrderTransmissionMethodCode();
389         }
390         return null;
391     }
392 
393     private void setNoteTypeValues(OleRequisitionItem item,String noteType,List<String> noteValues){
394         Map notes = new HashMap();
395         notes.put(OLEConstants.NOTE_TYP, noteType);
396         List<OleNoteType> noteTypeList = (List) getBusinessObjectService().findMatching(org.kuali.ole.select.businessobject.OleNoteType.class, notes);
397         if(noteTypeList != null && noteTypeList.size() >0){
398             for(int noteCount = 0;noteCount < noteValues.size();noteCount++){
399                 OleRequisitionNotes note = new OleRequisitionNotes();
400                 note.setNoteTypeId(noteTypeList.get(0).getNoteTypeId());
401                 note.setNote(noteValues.get(noteCount));
402                 item.getNotes().add(note);
403             }
404         }
405     }
406 
407     /**
408      * To set the delivery details for the Requisition Document
409      *
410      * @param requisitionDocument OleRequisitionDocument
411      * @param oleOrderRecord      OleOrderRecord
412      * @return requisitionDocument OleRequisitionDocument
413      */
414     private void setDeliveryDetails(OleRequisitionDocument requisitionDocument, OleOrderRecord oleOrderRecord) {
415         if (LOG.isDebugEnabled())
416             LOG.debug("bibInfoBean.getDeliveryBuildingCode----------->" + oleOrderRecord.getOleTxRecord().getBuildingCode());
417 
418         if (oleOrderRecord.getOleTxRecord().getDeliveryCampusCode() != null && oleOrderRecord.getOleTxRecord().getBuildingCode() != null && oleOrderRecord.getOleTxRecord().getDeliveryBuildingRoomNumber() != null) {
419             Map<String,String> deliveryMap = new HashMap<>();
420             deliveryMap.put(OLEConstants.OLEBatchProcess.BUILDING_CODE, oleOrderRecord.getOleTxRecord().getBuildingCode());
421             deliveryMap.put(OLEConstants.OLEBatchProcess.CAMPUS_CODE, oleOrderRecord.getOleTxRecord().getDeliveryCampusCode());
422             deliveryMap.put(OLEConstants.BUILDING_ROOM_NUMBER, oleOrderRecord.getOleTxRecord().getDeliveryBuildingRoomNumber());
423             Room room = getBusinessObjectService().findByPrimaryKey(Room.class, deliveryMap);
424             Building building = getVendorService().getBuildingDetails(oleOrderRecord.getOleTxRecord().getDeliveryCampusCode(), oleOrderRecord.getOleTxRecord().getBuildingCode());
425             if (building != null && room != null) {
426                 requisitionDocument.setDeliveryBuildingCode(building.getBuildingCode());
427                 requisitionDocument.setDeliveryCampusCode(building.getCampusCode());
428                 requisitionDocument.setDeliveryBuildingLine1Address(building.getBuildingStreetAddress());
429                 requisitionDocument.setDeliveryBuildingName(building.getBuildingName());
430                 requisitionDocument.setDeliveryCityName(building.getBuildingAddressCityName());
431                 requisitionDocument.setDeliveryStateCode(building.getBuildingAddressStateCode());
432                 requisitionDocument.setDeliveryPostalCode(building.getBuildingAddressZipCode());
433                 requisitionDocument.setDeliveryCountryCode(building.getBuildingAddressCountryCode());
434                 requisitionDocument.setDeliveryBuildingRoomNumber(room.getBuildingRoomNumber());
435                 requisitionDocument.setDeliveryToName(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.DELIVERY_TO_NAME));
436 
437 
438                 requisitionDocument.setBillingCountryCode(building.getBuildingCode());
439                 requisitionDocument.setBillingLine1Address(building.getBuildingStreetAddress());
440                 requisitionDocument.setBillingName(building.getBuildingName());
441                 requisitionDocument.setBillingCityName(building.getBuildingAddressCityName());
442                 requisitionDocument.setBillingStateCode(building.getBuildingAddressStateCode());
443                 requisitionDocument.setBillingPostalCode(building.getBuildingAddressZipCode());
444                 requisitionDocument.setBillingCountryCode(building.getBuildingAddressCountryCode());
445                 requisitionDocument.setBillingPhoneNumber(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.BILL_PHN_NBR));
446 
447             }
448         }
449     }
450 
451     private void setRecurringPaymentInfo(OleRequisitionDocument requisitionDocument, OleOrderRecord oleOrderRecord)throws Exception{
452         if(oleOrderRecord.getOleTxRecord().getRecurringPaymentType() != null){
453             requisitionDocument.setRecurringPaymentTypeCode(oleOrderRecord.getOleTxRecord().getRecurringPaymentType());
454             SimpleDateFormat sdf1 = new SimpleDateFormat(org.kuali.ole.OLEConstants.DATE_FORMAT);
455             java.util.Date beginDate = sdf1.parse(oleOrderRecord.getOleTxRecord().getRecurringPaymentBeginDate());
456             java.util.Date endDate = sdf1.parse(oleOrderRecord.getOleTxRecord().getRecurringPaymentEndDate());
457             requisitionDocument.setPurchaseOrderBeginDate(new java.sql.Date(beginDate.getTime()));
458             requisitionDocument.setPurchaseOrderEndDate(new java.sql.Date(endDate.getTime()));
459         }
460     }
461 
462     /**
463      * To set the vendor details for the Requisition Document
464      *
465      * @param requisitionDocument OleRequisitionDocument
466      * @return requisitionDocument OleRequisitionDocument
467      */
468     private void setVendorDetails(OleRequisitionDocument requisitionDocument, OleOrderRecord oleOrderRecord) {
469         if (oleOrderRecord.getOleTxRecord().getVendorNumber() != null) {
470             VendorDetail vendorDetail = getVendorService().getVendorDetail(oleOrderRecord.getOleTxRecord().getVendorNumber());
471 
472             requisitionDocument.setVendorCustomerNumber(oleOrderRecord.getOleTxRecord().getVendorInfoCustomer());
473             requisitionDocument.setVendorNumber(oleOrderRecord.getOleTxRecord().getVendorNumber());
474             requisitionDocument.setVendorNumber(vendorDetail.getVendorNumber());
475             requisitionDocument.setVendorName(vendorDetail.getVendorName());
476             requisitionDocument.setVendorHeaderGeneratedIdentifier(vendorDetail.getVendorHeaderGeneratedIdentifier());
477             requisitionDocument.setVendorDetailAssignedIdentifier(vendorDetail.getVendorDetailAssignedIdentifier());
478             requisitionDocument.setVendorDetail(vendorDetail);
479             String deliveryCampus = oleOrderRecord.getOleTxRecord().getDeliveryCampusCode();
480             Integer headerId = null;
481             Integer detailId = null;
482             int dashInd = vendorDetail.getVendorNumber().indexOf('-');
483             // make sure there's at least one char before and after '-'
484             if (dashInd > 0 && dashInd < vendorDetail.getVendorNumber().length() - 1) {
485                 headerId = new Integer(vendorDetail.getVendorNumber().substring(0, dashInd));
486                 detailId = new Integer(vendorDetail.getVendorNumber().substring(dashInd + 1));
487             }
488             VendorAddress vendorAddress = getVendorService().getVendorDefaultAddress(headerId, detailId, VendorConstants.AddressTypes.PURCHASE_ORDER, deliveryCampus);
489             setVendorAddress(vendorAddress, requisitionDocument);
490 
491             List<VendorContract> vendorContracts = vendorDetail.getVendorContracts();
492             for (Iterator<VendorContract> vendorContract = vendorContracts.iterator(); vendorContract.hasNext(); ) {
493                 requisitionDocument.setVendorContractGeneratedIdentifier((vendorContract.next()).getVendorContractGeneratedIdentifier());
494             }
495         }
496 
497     }
498 
499     /**
500      * To generate single Item list for the Requisition Document
501      *
502      * @param oleOrderRecord OleOrderRecord
503      * @return ArrayList
504      */
505     private List<RequisitionItem> generateItemList(OleOrderRecord oleOrderRecord, OLEBatchProcessJobDetailsBo job,OleRequisitionDocument requisitionDocument) throws Exception {
506         List<RequisitionItem> items = new ArrayList<RequisitionItem>();
507         int itemLineNumber = 1;
508         items.add(createRequisitionItem(oleOrderRecord, itemLineNumber, job,requisitionDocument));
509         return items;
510     }
511     /*private List<Note> generateBoNotesList(BibInfoBean bibInfoBean) {
512         List<Note> notes = new ArrayList<Note>();
513         notes.add(createNotes(bibInfoBean));
514         return notes;
515     }*/
516 
517     /**
518      * To generate multiple Item list for the Requisition Document
519      *
520      * @param oleOrderRecordList List<OleOrderRecord>
521      * @return ArrayList
522      */
523     private List<RequisitionItem> generateMultipleItemsForOneRequisition(List<OleOrderRecord> oleOrderRecordList, OLEBatchProcessJobDetailsBo job,OleRequisitionDocument requisitionDocument) throws Exception {
524         List<RequisitionItem> items = new ArrayList<RequisitionItem>();
525         int itemLineNumber = 0;
526         // set items to document
527         for (OleOrderRecord oleOrderRecord : oleOrderRecordList) {
528             itemLineNumber++;
529             items.add(createRequisitionItem(oleOrderRecord, itemLineNumber, job,requisitionDocument));
530         }
531         return items;
532     }
533 
534     /**
535      * To create the requisition item for the Requisition Document.
536      *
537      * @param oleOrderRecord OleOrderRecord
538      * @return RequisitionItem
539      */
540     @SuppressWarnings("deprecation")
541     protected RequisitionItem createRequisitionItem(OleOrderRecord oleOrderRecord, int itemLineNumber, OLEBatchProcessJobDetailsBo job,OleRequisitionDocument requisitionDocument) throws Exception {
542         OleRequisitionItem item = new OleRequisitionItem();
543         item.setOleOrderRecord(oleOrderRecord);
544         //item.setBibInfoBean(bibInfoBean);
545         item.setItemLineNumber(itemLineNumber);
546         item.setItemUnitOfMeasureCode(getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.UOM));
547         item.setItemQuantity(new KualiDecimal(oleOrderRecord.getOleTxRecord().getQuantity()));
548         if(oleOrderRecord.getOleTxRecord().getItemNoOfParts()!= null){
549             item.setItemNoOfParts(new KualiInteger(oleOrderRecord.getOleTxRecord().getItemNoOfParts()));
550         }
551         //item.setItemDescription((String) ((List) oleOrderRecord.getOleBibRecord().getBibAssociatedFieldsValueMap().get("ISBN_search")).get(0));
552         setItemDescription(oleOrderRecord,item);
553         item.setItemUnitPrice(new BigDecimal(oleOrderRecord.getOleTxRecord().getListPrice()));
554         item.setItemTypeCode(oleOrderRecord.getOleTxRecord().getItemType());
555         item.setItemListPrice(new KualiDecimal(oleOrderRecord.getOleTxRecord().getListPrice()));
556         item.setItemLocation(oleOrderRecord.getOleTxRecord().getDefaultLocation());
557         if(!StringUtils.isBlank(oleOrderRecord.getOleTxRecord().getFormatTypeId())){
558             item.setFormatTypeId(Integer.parseInt(oleOrderRecord.getOleTxRecord().getFormatTypeId()));
559         }
560         if(oleOrderRecord.getOleTxRecord().getRequestSourceType() != null){
561             item.setRequestSourceTypeId(getRequestSourceTypeId(oleOrderRecord.getOleTxRecord().getRequestSourceType()));
562         }
563         if (oleOrderRecord.getOleTxRecord().getOleDonors()!=null && oleOrderRecord.getOleTxRecord().getOleDonors().size()>0) {
564             List<OLELinkPurapDonor> oleLinkPurapDonorList = new ArrayList<>();
565             for (String donor : oleOrderRecord.getOleTxRecord().getOleDonors()) {
566                 Map map = new HashMap();
567                 map.put(OLEConstants.DONOR_CODE, donor);
568                 OLEDonor oleDonor = getBusinessObjectService().findByPrimaryKey(OLEDonor.class, map);
569                 OLELinkPurapDonor oleLinkPurapDonor = new OLELinkPurapDonor();
570                 oleLinkPurapDonor.setDonorCode(donor);
571                 if (oleDonor != null) {
572                     oleLinkPurapDonor.setDonorId(oleDonor.getDonorId());
573                 }
574                 oleLinkPurapDonorList.add(oleLinkPurapDonor);
575             }
576             item.setOleDonors(oleLinkPurapDonorList);
577         }
578         if (ObjectUtils.isNotNull(oleOrderRecord.getOleBibRecord().getBibUUID())) {
579             item.setItemTitleId(oleOrderRecord.getOleBibRecord().getBibUUID());
580             //item.setLinkToOrderOption(OLEConstants.NB_PRINT);
581         }
582         item.setBibTree(oleOrderRecord.getBibTree());
583         item.setLinkToOrderOption(oleOrderRecord.getLinkToOrderOption());
584         if (item.getLinkToOrderOption() != null) {
585             if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT_ELECTRONIC) || item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_PRINT_ELECTRONIC)) {
586                 if (oleOrderRecord.getBibTree() != null) {
587                     boolean printHolding = false;
588                     boolean electronicHolding = false;
589                     List<HoldingsId> electronicHoldingsIdList = new ArrayList<>();
590                     List<HoldingsId> holdingsIds = oleOrderRecord.getBibTree().getHoldingsIds();
591                     if (holdingsIds != null && holdingsIds.size() > 0) {
592                         for (HoldingsId holdingsId : holdingsIds) {
593                             if (holdingsId != null) {
594                                 Holdings holdings = getDocstoreClientLocator().getDocstoreClient().retrieveHoldings(holdingsId.getId());
595                                 if (holdings != null && holdings.getHoldingsType() != null && holdings.getHoldingsType().equals(OLEConstants.OleHoldings.ELECTRONIC)) {
596                                     electronicHolding = true;
597                                     electronicHoldingsIdList.add(holdingsId);
598                                 } else if (holdings != null && holdings.getHoldingsType() != null && holdings.getHoldingsType().equals(OLEConstants.PRINT)) {
599                                     printHolding = true;
600                                 }
601                             }
602                         }
603                     }
604                     if (!printHolding && electronicHolding) {
605                         if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT_ELECTRONIC)){
606                             item.setLinkToOrderOption(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_ELECTRONIC);
607                         }else if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_PRINT_ELECTRONIC)){
608                             item.setLinkToOrderOption(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_ELECTRONIC);
609                         }
610                     } else {
611                         if (electronicHoldingsIdList.size()>0 && oleOrderRecord.getBibTree().getHoldingsIds()!=null){
612                             oleOrderRecord.getBibTree().getHoldingsIds().removeAll(electronicHoldingsIdList);
613                         }
614                         if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT_ELECTRONIC)){
615                             item.setLinkToOrderOption(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT);
616                         }else if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_PRINT_ELECTRONIC)){
617                             item.setLinkToOrderOption(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI);
618                         }
619                     }
620                 }
621             }
622             if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_PRINT) || item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI)) {
623                 if (oleOrderRecord.getBibTree() != null) {
624                     List<HoldingsId> holdingsIds = oleOrderRecord.getBibTree().getHoldingsIds();
625                     if (holdingsIds != null && holdingsIds.size() > 0) {
626                         int itemCount = 0;
627                         for (HoldingsId holdingsId : holdingsIds) {
628                             if (holdingsId != null) {
629                                 if (holdingsId.getItems() != null && holdingsId.getItems().size() == 0) {
630                                     KualiInteger noOfItems = KualiInteger.ZERO;
631                                     KualiInteger noOfCopies = new KualiInteger(item.getItemQuantity().intValue());
632                                     noOfItems = item.getItemNoOfParts().multiply(noOfCopies);
633                                     for (int count = 0; count < noOfItems.intValue(); count++) {
634                                         holdingsId.getItems().add(null);
635                                     }
636                                 }
637                             }
638                             if (holdingsId.getItems() != null && holdingsId.getItems().size() > 0) {
639                                 itemCount += holdingsId.getItems().size();
640                             }
641                         }
642                         item.setItemQuantity(new KualiDecimal(itemCount));
643                         item.setItemNoOfParts(new KualiInteger(1));
644                     }
645                 }
646             } else if (item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_ONLY_ELECTRONIC) || item.getLinkToOrderOption().equals(OLEConstants.ORDER_RECORD_IMPORT_MARC_EDI_ELECTRONIC)) {
647                 item.setItemQuantity(new KualiDecimal(1));
648                 item.setItemNoOfParts(new KualiInteger(1));
649             }
650         }
651         //if (item.getItemType() == null) {
652         org.kuali.ole.module.purap.businessobject.ItemType itemType = getBusinessObjectService().findBySinglePrimaryKey(org.kuali.ole.module.purap.businessobject.ItemType.class, "ITEM");
653         item.setItemType(itemType);
654         // }
655 
656         RequisitionAccount requisitionAccount = new RequisitionAccount();
657         /**
658          * Below code commented based on JIRA-2617.
659          */
660         //requisitionAccount.setChartOfAccountsCode(oleOrderRecord.getOleTxRecord().getChartCode());
661         requisitionAccount.setChartOfAccountsCode(oleOrderRecord.getOleTxRecord().getItemChartCode());
662         requisitionAccount.setAccountNumber(oleOrderRecord.getOleTxRecord().getAccountNumber());
663         requisitionAccount.setFinancialObjectCode(oleOrderRecord.getOleTxRecord().getObjectCode());
664         requisitionAccount.setDebitCreditCode(OLEConstants.GL_DEBIT_CODE);
665         if (oleOrderRecord.getOleTxRecord().getListPrice() != null) {
666             requisitionAccount.setAmount(new KualiDecimal(oleOrderRecord.getOleTxRecord().getListPrice()));
667         }
668         if (oleOrderRecord.getOleTxRecord().getPercent() != null) {
669             requisitionAccount.setAccountLinePercent(new BigDecimal(oleOrderRecord.getOleTxRecord().getPercent()));
670         }
671         if (oleOrderRecord.getOleTxRecord().getAccountNumber() != null) {
672             List<PurApAccountingLine> sourceAccountingLines = item.getSourceAccountingLines();
673             if (sourceAccountingLines.size() == 0) {
674                 sourceAccountingLines = new ArrayList<PurApAccountingLine>(0);
675             }
676             sourceAccountingLines.add((PurApAccountingLine) requisitionAccount);
677             item.setSourceAccountingLines(sourceAccountingLines);
678         }
679 
680         /*OleRequestor oleRequestor = checkRequestorExist(oleOrderRecord);
681         if(oleRequestor == null) {
682             oleRequestor =  new OleRequestor();
683             oleRequestor = saveRequestor(oleOrderRecord, oleRequestor);
684         }
685 
686         item.setOleRequestor(oleRequestor);
687 
688         item.setRequestorId(oleRequestor.getRequestorId());
689          //item.setRequestSourceTypeId(oleRequestSourceService.getRequestSourceTypeId(bibInfoBean.getRequestSource()));
690         item.setRequestorFirstName(oleRequestor.getRequestorFirstName());
691 
692         item.setRequestorLastName(oleRequestor.getRequestorLastName());*/
693         //item.setRequestSourceUrl(oleOrderRecord.getOleTxRecord().getRequestSourceUrl());
694 
695         //getOleRequestorService().saveRequestor(oleRequestor);
696 
697         String requestorType = null;
698 
699         if (requestorType == null || "".equals(requestorType)) {
700 
701             requestorType = OleSelectConstant.REQUESTOR_TYPE_STAFF;
702         }
703 
704         int requestorTypeId = getRequestorTypeId(requestorType);
705         item.setRequestorTypeId(requestorTypeId);
706         if (oleOrderRecord.getOleTxRecord().getRequisitionSource().equals(OleSelectConstant.REQUISITON_SRC_TYPE_WEBFORM)) {//&& !oleOrderRecord.getOleTxRecord().getRequestersNotes().trim().equals("")) {
707             OleRequisitionNotes note = new OleRequisitionNotes();
708             Map notes = new HashMap();
709             String noteType = OleSelectConstant.REQUESTOR_NOTES_PRE_ORDER_SERVICE;
710             notes.put(OLEConstants.NOTE_TYP, noteType);
711             List<OleNoteType> noteTypeList = (List) getBusinessObjectService().findMatching(org.kuali.ole.select.businessobject.OleNoteType.class, notes);
712             note.setNoteTypeId(noteTypeList.get(0).getNoteTypeId());
713             //note.setNote(oleOrderRecord.getOleTxRecord().getRequestersNotes());
714             item.getNotes().add(note);
715         }
716         setItemDescription(oleOrderRecord, item);
717         populateValuesFromProfileAttributesAndDataMapping(item, job,requisitionDocument);
718         setForeignCurrencyDetails(item,requisitionDocument);
719         setItemNotes(item,oleOrderRecord.getOleTxRecord());
720         item.setVendorItemPoNumber(oleOrderRecord.getOleTxRecord().getVendorItemIdentifier());
721         return item;
722     }
723 
724     private Integer getRequestSourceTypeId(String requestSourceType){
725         Map<String,String> requestSourceMap = new HashMap<>();
726         requestSourceMap.put(OLEConstants.OLEBatchProcess.REQUEST_SRC,requestSourceType);
727         List<OleRequestSourceType> requestSourceList = (List) getBusinessObjectService().findMatching(OleRequestSourceType.class, requestSourceMap);
728         if(requestSourceList != null && requestSourceList.size() > 0){
729             return requestSourceList.get(0).getRequestSourceTypeId();
730         }
731         return null;
732     }
733 
734     private void setForeignCurrencyDetails(OleRequisitionItem item,OleRequisitionDocument requisitionDocument){
735         if (requisitionDocument.getVendorDetail().getCurrencyType()!=null){
736             if(requisitionDocument.getVendorDetail().getCurrencyType().getCurrencyType().equalsIgnoreCase(OleSelectConstant.CURRENCY_TYPE_NAME)){
737                 currencyTypeIndicator=true;
738             }
739             else{
740                 currencyTypeIndicator=false;
741             }
742         }
743         if(!currencyTypeIndicator){
744             item.setItemForeignListPrice(item.getItemListPrice());
745             item.setItemForeignDiscountType(item.getItemDiscountType());
746             item.setItemForeignDiscount(item.getItemDiscount());
747             item.setItemListPrice(new KualiDecimal(0.00));
748             getOlePurapService().calculateForeignCurrency(item);
749             Long currencyTypeId = requisitionDocument.getVendorDetail().getCurrencyType().getCurrencyTypeId();
750             Map documentNumberMap = new HashMap();
751             documentNumberMap.put(OleSelectConstant.CURRENCY_TYPE_ID, currencyTypeId);
752             BusinessObjectService businessObjectService = SpringContext.getBean(BusinessObjectService.class);
753             List<OleExchangeRate> exchangeRateList = (List) businessObjectService.findMatchingOrderBy(OleExchangeRate.class, documentNumberMap, OleSelectConstant.EXCHANGE_RATE_DATE, false);
754             Iterator iterator = exchangeRateList.iterator();
755             if (iterator.hasNext()) {
756                 OleExchangeRate tempOleExchangeRate = (OleExchangeRate) iterator.next();
757                 item.setItemExchangeRate(new KualiDecimal(tempOleExchangeRate.getExchangeRate()));
758             }
759             if (item.getItemExchangeRate() != null && item.getItemForeignUnitCost() != null) {
760                 item.setItemUnitCostUSD(new KualiDecimal(item.getItemForeignUnitCost().bigDecimalValue().divide(item.getItemExchangeRate().bigDecimalValue(), 4, RoundingMode.HALF_UP)));
761                 item.setItemUnitPrice(item.getItemUnitCostUSD().bigDecimalValue());
762                 item.setItemListPrice(item.getItemUnitCostUSD());
763             }
764         }
765     }
766 
767     private void populateValuesFromProfileAttributesAndDataMapping(OleRequisitionItem singleItem, OLEBatchProcessJobDetailsBo job,OleRequisitionDocument requisitionDocument){
768         OrderImportHelperBo orderImportHelperBo = job.getOrderImportHelperBo();
769         //DataCarrierService dataCarrierService = GlobalResourceLoader.getService(org.kuali.ole.OLEConstants.DATA_CARRIER_SERVICE);
770         //OleTxRecord oleTxRecord = (OleTxRecord)dataCarrierService.getData(org.kuali.ole.OLEConstants.OLE_TX_RECORD);
771         OleTxRecord oleTxRecord = orderImportHelperBo.getOleTxRecord();
772         if(oleTxRecord != null){
773             if(oleTxRecord.getRequestorName() != null){
774                 String fullName = oleTxRecord.getRequestorName();
775                 String[] requestorNames = fullName.split(", ");
776                 if(requestorNames.length == 2){
777                     String lastName = requestorNames[0];
778                     String firstName = requestorNames[1];
779                     Map<String,String> requestorNameMap = new HashMap<>();
780                     requestorNameMap.put(OLEConstants.FIRST_NM,firstName);
781                     requestorNameMap.put(OLEConstants.LAST_NM,lastName);
782                     List<OLERequestorPatronDocument> olePatronDocumentList = new ArrayList<OLERequestorPatronDocument>();
783                     olePatronDocumentList = getOleSelectDocumentService().getPatronDocumentListFromWebService();
784                     HashMap<String, List<OLERequestorPatronDocument>> patronListMap = new HashMap<String, List<OLERequestorPatronDocument>>();
785                     patronListMap.put(requisitionDocument.getDocumentNumber(), olePatronDocumentList);
786                     getOlePatronDocumentList().setPatronListMap(patronListMap);
787                     if(olePatronDocumentList != null && olePatronDocumentList.size()>0){
788                         for(int recCount = 0;recCount < olePatronDocumentList.size();recCount++) {
789                             if(olePatronDocumentList.get(recCount).getFirstName().equalsIgnoreCase(firstName) && olePatronDocumentList.get(recCount).getLastName().equalsIgnoreCase(lastName)){
790                                 String patronId = olePatronDocumentList.get(recCount).getOlePatronId();
791                                 singleItem.setRequestorId(patronId);
792                                 singleItem.setRequestorFirstName(fullName);
793                                 break;
794                             }
795                         }
796                     }
797                 }
798             }
799             singleItem.setItemDiscount(new KualiDecimal(oleTxRecord.getDiscount()));
800             singleItem.setItemDiscountType(oleTxRecord.getDiscountType());
801             if(singleItem.getItemDiscount() != null && singleItem.getItemDiscountType() == null){
802                 singleItem.setItemDiscountType(OLEConstants.PERCENTAGE);
803             }
804             singleItem.setItemUnitPrice(getOlePurapService().calculateDiscount(singleItem).setScale(2, BigDecimal.ROUND_HALF_UP));
805             /*if(requisitionDocument.getVendorDetail().getVendorHeader().getVendorForeignIndicator()) {
806                 singleItem.setItemForeignDiscountType("#");
807                 if(!singleItem.getItemListPrice().equals(new KualiDecimal(0.0))){
808                     singleItem.setItemForeignListPrice(singleItem.getItemListPrice());
809                 }
810                 if(!singleItem.getItemDiscount().equals(new KualiDecimal(0.0))){
811                     singleItem.setItemForeignDiscount(singleItem.getItemDiscount());
812                 }
813                 getOlePurapService().calculateForeignCurrency(singleItem);
814                 KualiDecimal itemTotalPrice = singleItem.getItemForeignUnitCost();
815                 requisitionDocument.setTotalDollarAmount(requisitionDocument.getTotalDollarAmount().add(itemTotalPrice));
816                 singleItem.setItemListPrice(new KualiDecimal(0.0));
817                 singleItem.setItemUnitPrice(new BigDecimal(0.0));
818                 singleItem.setItemDiscount(new KualiDecimal(0.0));
819                 singleItem.setItemDiscountType(null);
820             }*/
821             singleItem.setItemStatus(oleTxRecord.getItemStatus());
822 
823         }
824     }
825 
826     private void setItemDescription(OleOrderRecord oleOrderRecord, OleRequisitionItem item) throws Exception {
827 
828         String title = oleOrderRecord.getOleBibRecord().getBib().getTitle() != null ? oleOrderRecord.getOleBibRecord().getBib().getTitle()+ "," : "";
829         String author = oleOrderRecord.getOleBibRecord().getBib().getAuthor() != null ? oleOrderRecord.getOleBibRecord().getBib().getAuthor()+ "," : "";
830         String publisher = oleOrderRecord.getOleBibRecord().getBib().getPublisher() != null ? oleOrderRecord.getOleBibRecord().getBib().getPublisher()+ "," : "";
831         String isbn = oleOrderRecord.getOleBibRecord().getBib().getIsbn() != null ? oleOrderRecord.getOleBibRecord().getBib().getIsbn() + ",": "";
832         String description = title + author
833                 + publisher + isbn;
834         item.setItemDescription(description.substring(0, (description.lastIndexOf(","))));
835         item.setItemTitle(oleOrderRecord.getOleBibRecord().getBib().getTitle());
836         item.setItemAuthor(oleOrderRecord.getOleBibRecord().getBib().getAuthor());
837         item.setBibUUID(oleOrderRecord.getOleBibRecord().getBibUUID());
838 
839     }
840 
841     public int getRequestorTypeId(String requestorType) {
842         int requestorTypeId;
843         Map requestorTypeMap = new HashMap();
844         requestorTypeMap.put(OLEConstants.RQST_TYPE, requestorType);
845         BusinessObjectService businessObjectService = SpringContext.getBean(org.kuali.rice.krad.service.BusinessObjectService.class);
846         List<OleRequestorType> requestorTypeIdList = (List) businessObjectService.findMatching(OleRequestorType.class, requestorTypeMap);
847         Iterator itr = requestorTypeIdList.iterator();
848         requestorTypeId = requestorTypeIdList.iterator().next().getRequestorTypeId();
849         return requestorTypeId;
850     }
851 
852     /**
853      * This method will check whether Requestor exist ,if exist returns existing record if not save the requester.
854      *
855      * @param oleOrderRecord
856      * @return OleRequestor
857      */
858     protected OleRequestor checkRequestorExist(OleOrderRecord oleOrderRecord) {
859 
860         String requestorFirstName = getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.FIRST_NAME);
861         String requestorLastName = getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.LAST_NAME);
862         String firstName;
863         String lastName;
864         Map requestorName = new HashMap();
865         requestorName.put(OLEConstants.REQUESTOR_FIRST_NM, requestorFirstName);
866         requestorName.put(OLEConstants.REQUESTOR_LAST_NM, requestorLastName);
867         List<OleRequestor> requestorList = (List) getBusinessObjectService().findMatching(OleRequestor.class, requestorName);
868         if (requestorList.size() < 1) {
869             return null;
870         } else {
871             for (int i = 0; i < requestorList.size(); i++) {
872                 firstName = requestorList.get(i).getRequestorFirstName().toString();
873                 lastName = requestorList.get(i).getRequestorLastName().toString();
874                 if (requestorFirstName.equalsIgnoreCase(firstName) && requestorLastName.equalsIgnoreCase(lastName)) {
875                     return requestorList.get(i);
876                 }
877             }
878             return null;
879         }
880     }
881 
882     /**
883      * This method will set the values on OleRequestor and save.
884      *
885      * @return OleRequestor
886      */
887     protected OleRequestor saveRequestor(OleOrderRecord oleOrderRecord, OleRequestor oleRequestor) {
888         oleRequestor.setRequestorFirstName(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.FIRST_NAME));
889         oleRequestor.setRequestorLastName(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.LAST_NAME));
890         oleRequestor.setRequestorAddress1(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.ADDRESS1));
891         oleRequestor.setRequestorAddress2(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.ADDRESS2));
892         oleRequestor.setRequestorCityName(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.CITY));
893         oleRequestor.setRequestorStateCode(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.STATE_CODE));
894         oleRequestor.setRequestorPostalCode(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.POSTAL_CODE));
895         oleRequestor.setRequestorCountryCode(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.COUNTRY_CODE));
896         oleRequestor.setRequestorPhoneNumber(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.PHONE_NUMBER));
897         oleRequestor.setRequestorEmail(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.EMAIL));
898         oleRequestor.setRequestorSms(getConfigurationService().getPropertyValueAsString(PurapPropertyConstants.SMS));
899         oleRequestor.setRequestorTypeId(Integer.toString(getRequestorTypeId(OleSelectConstant.REQUESTOR_TYPE_BATCHINGEST)));
900         getOleRequestorService().saveRequestor(oleRequestor);
901         return oleRequestor;
902     }
903 
904 
905     /**
906      * Set the Vendor address of the given ID.
907      *
908      * @param vendorAddress       VendorAddress
909      * @param requisitionDocument RequisitionDocument
910      */
911     protected void setVendorAddress(VendorAddress vendorAddress, RequisitionDocument requisitionDocument) {
912 
913         if (vendorAddress != null) {
914             requisitionDocument.setVendorAddressGeneratedIdentifier(vendorAddress.getVendorAddressGeneratedIdentifier());
915             requisitionDocument.setVendorAddressInternationalProvinceName(vendorAddress.getVendorAddressInternationalProvinceName());
916             requisitionDocument.setVendorLine1Address(vendorAddress.getVendorLine1Address());
917             requisitionDocument.setVendorLine2Address(vendorAddress.getVendorLine2Address());
918             requisitionDocument.setVendorCityName(vendorAddress.getVendorCityName());
919             requisitionDocument.setVendorStateCode(vendorAddress.getVendorStateCode());
920             requisitionDocument.setVendorPostalCode(vendorAddress.getVendorZipCode());
921             requisitionDocument.setVendorCountryCode(vendorAddress.getVendorCountryCode());
922         }
923 
924     }
925 
926 
927     public String getDocumentDescription(OleRequisitionDocument requisitionDocument, OleOrderRecord oleOrderRecord,OLEBatchProcessJobDetailsBo job,int recPosition) {
928         String description =  getOlePurapService().getParameter(org.kuali.ole.sys.OLEConstants.ORDER_IMPORT_REQ_DESC);
929         Map<String,String> descMap = new HashMap<>();
930         if(requisitionDocument.getVendorDetail().getVendorAliases() != null && requisitionDocument.getVendorDetail().getVendorAliases().size() > 0 && requisitionDocument.getVendorDetail().getVendorAliases().get(0).getVendorAliasName() != null){
931             descMap.put(org.kuali.ole.sys.OLEConstants.VENDOR_NAME,requisitionDocument.getVendorDetail().getVendorAliases().get(0).getVendorAliasName());
932         }
933         descMap.put(org.kuali.ole.sys.OLEConstants.ORDER_TYP,oleOrderRecord.getOleTxRecord().getOrderType());
934         descMap.put(org.kuali.ole.sys.OLEConstants.VND_ITM_ID,oleOrderRecord.getOleTxRecord().getVendorItemIdentifier() != null && !oleOrderRecord.getOleTxRecord().getVendorItemIdentifier().isEmpty() ? oleOrderRecord.getOleTxRecord().getVendorItemIdentifier() + "_" : "");
935         description = getOlePurapService().setDocumentDescription(description,descMap);
936         if (!description.equals("") && description != null) {
937             description = description.substring(0, description.lastIndexOf("_"));
938         }
939         if(description.startsWith("_")){
940             description = description.substring(1);
941         }
942         if(description.length() > 255) {
943             if(job.getOrderImportHelperBo().getOleBatchProcessProfileBo().getRequisitionsforTitle().equalsIgnoreCase(OLEConstants.ONE_REQUISITION_PER_TITLE)) {
944                 job.getOrderImportHelperBo().getFailureReason().add(OLEConstants.OLEBatchProcess.REC_POSITION + (recPosition + 1) + " " + OLEConstants.OLEBatchProcess.DESC_MAX_LENG);
945             } else {
946                 job.getOrderImportHelperBo().getFailureReason().add(OLEConstants.OLEBatchProcess.DESC_MAX_LENG);
947             }
948         }
949         return description;
950     }
951 
952     public RequisitionCreateDocumentService getRequisitionCreateDocumentService() {
953         if (requisitionCreateDocumentService == null) {
954             requisitionCreateDocumentService = SpringContext.getBean(RequisitionCreateDocumentService.class);
955         }
956         return requisitionCreateDocumentService;
957     }
958 
959     public void setRequisitionCreateDocumentService(RequisitionCreateDocumentService requisitionCreateDocumentService) {
960         this.requisitionCreateDocumentService = requisitionCreateDocumentService;
961     }
962 
963     public OleRequestorService getOleRequestorService() {
964         if (oleRequestorService == null) {
965             oleRequestorService = SpringContext.getBean(OleRequestorService.class);
966         }
967         return oleRequestorService;
968     }
969 
970     public void setOleRequestorService(OleRequestorService oleRequestorService) {
971         this.oleRequestorService = oleRequestorService;
972     }
973 
974     public VendorService getVendorService() {
975         if (vendorService == null) {
976             vendorService = SpringContext.getBean(VendorService.class);
977         }
978         return vendorService;
979     }
980 
981     public void setVendorService(VendorService vendorService) {
982         this.vendorService = vendorService;
983     }
984 
985     public OleRequestSourceService getOleRequestSourceService() {
986         if (oleRequestSourceService == null) {
987             oleRequestSourceService = SpringContext.getBean(OleRequestSourceService.class);
988         }
989         return oleRequestSourceService;
990     }
991 
992     public void setOleRequestSourceService(OleRequestSourceService oleRequestSourceService) {
993         this.oleRequestSourceService = oleRequestSourceService;
994     }
995 
996     public OlePurapService getOlePurapService() {
997         if (olePurapService == null) {
998             olePurapService = SpringContext.getBean(OlePurapService.class);
999         }
1000         return olePurapService;
1001     }
1002 
1003     public void setOlePurapService(OlePurapService olePurapService) {
1004         this.olePurapService = olePurapService;
1005     }
1006 
1007     public BibInfoService getBibInfoService() {
1008         if (bibInfoService == null) {
1009             bibInfoService = SpringContext.getBean(BibInfoService.class);
1010         }
1011         return bibInfoService;
1012     }
1013 
1014     public void setBibInfoService(BibInfoService bibInfoService) {
1015         this.bibInfoService = bibInfoService;
1016     }
1017 
1018     public void setBusinessObjectService(BusinessObjectService businessObjectService) {
1019         this.businessObjectService = businessObjectService;
1020     }
1021 
1022     public ConfigurationService getConfigurationService() {
1023         if (kualiConfigurationService == null) {
1024             kualiConfigurationService = SpringContext.getBean(ConfigurationService.class);
1025         }
1026         return kualiConfigurationService;
1027     }
1028 
1029     public void setConfigurationService(ConfigurationService kualiConfigurationService) {
1030         this.kualiConfigurationService = kualiConfigurationService;
1031     }
1032 
1033 }