001package org.kuali.ole.service;
002
003import org.apache.commons.lang.StringUtils;
004import org.apache.commons.collections.CollectionUtils;
005import org.kuali.ole.OLEConstants;
006import org.kuali.ole.deliver.OleLoanDocumentsFromSolrBuilder;
007import org.kuali.ole.deliver.processor.LoanProcessor;
008import org.kuali.ole.deliver.bo.OleLoanDocument;
009import org.kuali.ole.deliver.bo.OleTemporaryCirculationHistory;
010import org.kuali.ole.deliver.api.OleDeliverRequestDefinition;
011import org.kuali.ole.deliver.bo.OleDeliverRequestBo;
012import org.kuali.ole.ingest.pojo.OlePatron;
013import org.kuali.ole.deliver.bo.OlePatronLoanDocument;
014import org.kuali.ole.deliver.bo.OlePatronLoanDocuments;
015import org.kuali.ole.deliver.bo.OleRenewalLoanDocument;
016import org.kuali.ole.deliver.api.*;
017import org.kuali.ole.deliver.bo.PatronBillPayment;
018import org.kuali.ole.deliver.bo.*;
019import org.kuali.ole.sys.context.SpringContext;
020import org.kuali.rice.core.api.criteria.CriteriaLookupService;
021import org.kuali.rice.core.api.criteria.GenericQueryResults;
022import org.kuali.rice.core.api.criteria.QueryByCriteria;
023import org.kuali.rice.core.api.resourceloader.GlobalResourceLoader;
024import org.kuali.rice.kim.api.identity.IdentityService;
025import org.kuali.rice.kim.api.identity.address.EntityAddress;
026import org.kuali.rice.kim.api.identity.email.EntityEmail;
027import org.kuali.rice.kim.api.identity.entity.Entity;
028import org.kuali.rice.kim.api.identity.name.EntityName;
029import org.kuali.rice.kim.api.identity.phone.EntityPhone;
030import org.kuali.rice.kim.api.identity.type.EntityTypeContactInfo;
031import org.kuali.rice.kim.api.services.KimApiServiceLocator;
032import org.kuali.rice.kim.impl.identity.address.EntityAddressBo;
033import org.kuali.rice.kim.impl.identity.affiliation.EntityAffiliationBo;
034import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
035import org.kuali.rice.kim.impl.identity.employment.EntityEmploymentBo;
036import org.kuali.rice.kim.impl.identity.entity.EntityBo;
037import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
038import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
039import org.kuali.rice.kim.impl.identity.type.EntityTypeContactInfoBo;
040import org.kuali.rice.krad.service.BusinessObjectService;
041import org.kuali.rice.krad.service.KRADServiceLocator;
042import org.kuali.rice.krad.util.ObjectUtils;
043
044import java.io.Serializable;
045import java.sql.Timestamp;
046import java.text.SimpleDateFormat;
047import java.util.*;
048
049/**
050 * OlePatronServiceImpl performs patron operation(create,update).
051 */
052public class OlePatronServiceImpl implements OlePatronService {
053    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePatronServiceImpl.class);
054    private BusinessObjectService businessObjectService;
055    private IdentityService identityService;
056    private CriteriaLookupService criteriaLookupService;
057    private LoanProcessor loanProcessor;
058    private OlePatronHelperService olePatronHelperService;
059    private OleLoanDocumentsFromSolrBuilder oleLoanDocumentsFromSolrBuilder;
060
061    protected  OlePatronHelperService getOlePatronHelperService(){
062        if(olePatronHelperService==null)
063            olePatronHelperService=new OlePatronHelperServiceImpl();
064        return olePatronHelperService;
065    }
066
067    /**
068     * This method initiate LoanProcessor.
069     * @return LoanProcessor
070     */
071    protected LoanProcessor getLoanProcessor() {
072        if(loanProcessor==null)
073            loanProcessor=new LoanProcessor();
074        return loanProcessor;
075    }
076
077    /**
078     * Gets the instance of BusinessObjectService
079     * @return businessObjectService(BusinessObjectService)
080     */
081    protected BusinessObjectService getBusinessObjectService() {
082        if (businessObjectService == null) {
083            businessObjectService = KRADServiceLocator.getBusinessObjectService();
084        }
085        return businessObjectService;
086    }
087    /**
088     * Gets the instance of IdentityService
089     * @return identityService(IdentityService)
090     */
091    protected IdentityService getIdentityService() {
092        if (identityService == null) {
093            identityService = (IdentityService) SpringContext.getBean("kimIdentityDelegateService");
094        }
095        return identityService;
096    }
097
098    /**
099     * Gets the instance of CriteriaLookupService
100     * @return criteriaLookupService(CriteriaLookupService)
101     */
102    protected CriteriaLookupService getCriteriaLookupService() {
103        if(criteriaLookupService == null) {
104            criteriaLookupService = GlobalResourceLoader.getService(OLEConstants.OlePatron.CRITERIA_LOOKUP_SERVICE);
105        }
106        return criteriaLookupService;
107    }
108    /**
109     * Based on patron Id it will return the patron object
110     * @param patronId
111     * @return OlePatronDefinition
112     */
113    @Override
114    public OlePatronDefinition getPatron(String patronId) {
115        LOG.debug("Inside the getPatron method");
116        Map<String, Object> criteria = new HashMap<String, Object>(4);
117        criteria.put(OLEConstants.OlePatron.PATRON_ID, patronId);
118        return OlePatronDocument.to(getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, criteria));
119    }
120    /**
121     * This method will create and persist the patron document
122     * @param olePatron
123     * @return savedOlePatronDefinition(OlePatronDefinition)
124     */
125    @Override
126    public OlePatronDefinition createPatron(OlePatronDefinition olePatron) {
127        LOG.debug(" Inside create patron ");
128        OlePatronDefinition savedOlePatronDefinition = new OlePatronDefinition();
129        try{
130            BusinessObjectService businessObjectService = KRADServiceLocator.getBusinessObjectService();
131            OlePatronDocument olePatronDocument = OlePatronDocument.from(olePatron);
132            String olePatronId = olePatronDocument.getOlePatronId();
133            if(StringUtils.isNotBlank(olePatronId)){
134                olePatronDocument.getEntity().setId(olePatronId);
135            }
136            EntityBo kimEntity = olePatronDocument.getEntity();
137            EntityBo entity2 = getBusinessObjectService().save(kimEntity);
138            List<OleAddressBo> oleAddressBoList = getOlePatronHelperService().retrieveOleAddressBo(entity2,olePatronDocument);
139            List<OlePhoneBo> olePhoneBoList = getOlePatronHelperService().retrieveOlePhoneBo(entity2, olePatronDocument);
140            List<OleEmailBo> oleEmailBoList = getOlePatronHelperService().retrieveOleEmailBo(entity2, olePatronDocument);
141            olePatronDocument.setOleAddresses(oleAddressBoList);
142            olePatronDocument.setOlePhones(olePhoneBoList);
143            olePatronDocument.setOleEmails(oleEmailBoList);
144            olePatronDocument.setOlePatronId(entity2.getId());
145            olePatronDocument.setEntity(kimEntity);
146            populateOperatorIdAndTimeStampForNotes(olePatronDocument, false);
147            OlePatronDocument savedPatronDocument = businessObjectService.save(olePatronDocument);
148            savedOlePatronDefinition = OlePatronDocument.to(savedPatronDocument);
149        }catch(Exception e){
150            e.printStackTrace();
151        }
152
153        return savedOlePatronDefinition;
154    }
155
156    private void populateOperatorIdAndTimeStampForNotes(OlePatronDocument olePatronDocument, boolean isUpdate) {
157        List<OlePatronNotes> notes = olePatronDocument.getNotes();
158        if(CollectionUtils.isNotEmpty(notes)){
159            if (!isUpdate) {
160                populateCurrentTimeStamp(notes);
161            }else{
162                Map<String,String> notesMap=new HashMap<String,String>();
163                notesMap.put("olePatronId", olePatronDocument.getOlePatronId());
164                List<OlePatronNotes>  olePatronNotesList = (List<OlePatronNotes>) KRADServiceLocator.getBusinessObjectService().findMatching(OlePatronNotes.class,notesMap);
165                if(CollectionUtils.isNotEmpty(olePatronNotesList)){
166                    Map<String,OlePatronNotes> patronNotesMap = new HashMap<>();
167                    for(OlePatronNotes olePatronNotes  : olePatronNotesList){
168                        patronNotesMap.put(olePatronNotes.getPatronNoteId(),olePatronNotes);
169                    }
170                    if(CollectionUtils.isNotEmpty(olePatronDocument.getNotes())){
171                        for(OlePatronNotes olePatronNotes : olePatronDocument.getNotes()){
172                            if(patronNotesMap.containsKey(olePatronNotes.getPatronNoteId())){
173                                OlePatronNotes patronDbNote = patronNotesMap.get(olePatronNotes.getPatronNoteId());
174                                if(!patronDbNote.getPatronNoteTypeId().equals(olePatronNotes.getPatronNoteTypeId()) ||
175                                        !patronDbNote.getPatronNoteText().equals(olePatronNotes.getPatronNoteText())){
176                                    olePatronNotes.setOperatorId(OLEConstants.PATRON_NOTE_DEFAULT_OPERATOR);
177                                    olePatronNotes.setNoteCreatedOrUpdatedDate(new Timestamp(System.currentTimeMillis()));
178                                }
179                            }
180                        }
181                    }
182                }else{
183                    populateCurrentTimeStamp(olePatronDocument.getNotes());
184                }
185            }
186        }
187    }
188
189    private void populateCurrentTimeStamp(List<OlePatronNotes> notes) {
190        for (Iterator<OlePatronNotes> iterator = notes.iterator(); iterator.hasNext(); ) {
191            OlePatronNotes olePatronNotes = iterator.next();
192            olePatronNotes.setOperatorId(OLEConstants.PATRON_NOTE_DEFAULT_OPERATOR);
193            olePatronNotes.setNoteCreatedOrUpdatedDate(new Timestamp(System.currentTimeMillis()));
194        }
195    }
196
197    /**
198     * This method will update the patron object which is already persist
199     * @param olePatronDefinition
200     * @return OlePatronDefinition
201     */
202    @Override
203    public OlePatronDefinition updatePatron(OlePatronDefinition olePatronDefinition) {
204        LOG.debug("Inside the updatePatron method");
205        boolean doc = false;
206        String documentNumber = "";
207        OlePatronDocument updatedPatronDocument = null;
208
209        try {
210            if (olePatronDefinition.getOlePatronId() != null) {
211                OlePatronDocument newPatronBo = OlePatronDocument.from(olePatronDefinition);
212                Map<String, Object> criteria = new HashMap<String, Object>(4);
213                criteria.put(OLEConstants.OlePatron.PATRON_ID,olePatronDefinition.getOlePatronId());
214                OlePatronDocument olePatronBo = getBusinessObjectService().findByPrimaryKey(OlePatronDocument.class, criteria);
215                if (olePatronBo != null) {
216                    HashMap<String, String> map = new HashMap<String, String>();
217                    map.put(OLEConstants.BORROWER_TYPE_ID, newPatronBo.getBorrowerType());
218                    List<OleBorrowerType> borrowerTypes = (List<OleBorrowerType>) getBusinessObjectService().findMatching(OleBorrowerType.class, map);
219                    if (borrowerTypes.size() > 0) {
220                        newPatronBo.setOleBorrowerType(borrowerTypes.get(0));
221                    }
222                    EntityBo kimEntity = (EntityBo)ObjectUtils.deepCopy((Serializable)olePatronBo.getEntity());
223                    newPatronBo.getEntity().setId(kimEntity.getId());
224                    List<EntityTypeContactInfoBo> entityTypeContactInfoBoList = (List<EntityTypeContactInfoBo>)ObjectUtils.deepCopy((Serializable) kimEntity.getEntityTypeContactInfos());
225                    newPatronBo.getEntity().getNames().get(0).setId(kimEntity.getNames().get(0).getId());
226                    kimEntity.getNames().get(0).setFirstName(newPatronBo.getName().getFirstName());
227                    kimEntity.getNames().get(0).setMiddleName(newPatronBo.getName().getMiddleName());
228                    kimEntity.getNames().get(0).setLastName(newPatronBo.getName().getLastName());
229                    kimEntity.getNames().get(0).setNamePrefix(newPatronBo.getName().getNamePrefix());
230                    kimEntity.getNames().get(0).setNameSuffix(newPatronBo.getName().getNameSuffix());
231                    entityTypeContactInfoBoList.get(0).setAddresses((List<EntityAddressBo>)
232                            ObjectUtils.deepCopy((Serializable)newPatronBo.getEntity().getEntityTypeContactInfos().get(0).getAddresses()));
233                    entityTypeContactInfoBoList.get(0).setEmailAddresses((List<EntityEmailBo>)
234                            ObjectUtils.deepCopy((Serializable) newPatronBo.getEntity().getEntityTypeContactInfos().get(0).getEmailAddresses()));
235                    entityTypeContactInfoBoList.get(0).setPhoneNumbers((List<EntityPhoneBo>)
236                            ObjectUtils.deepCopy((Serializable) newPatronBo.getEntity().getEntityTypeContactInfos().get(0).getPhoneNumbers()));
237                    kimEntity.setEntityTypeContactInfos(entityTypeContactInfoBoList);
238                    newPatronBo.setEntity(kimEntity);
239/*                    List<EntityAddressBo> addressBoList = olePatronBo.getEntity().getEntityTypeContactInfos().get(0).getAddresses();
240                    if(addressBoList.size() > 0) {
241                        for(int i=0;i<addressBoList.size();i++){
242                            EntityAddressBo entityAddressBo = addressBoList.get(i);
243                            Map<String, Object> addressMap = new HashMap<String, Object>();
244                            addressMap.put(OLEConstants.OlePatron.ENTITY_BO_ID,entityAddressBo.getId());
245                            //List<OleAddressBo> oleAddressBo = (List<OleAddressBo>) KRADServiceLocator.getBusinessObjectService().findMatching(OleAddressBo.class,criteria);
246                            OleAddressBo oleAddressBo =  KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleAddressBo.class,addressMap);
247                            if(entityAddressBo != null) {
248                                KRADServiceLocator.getBusinessObjectService().delete(oleAddressBo);
249                                //KRADServiceLocator.getBusinessObjectService().delete(entityAddressBo);
250                            }
251                        }
252                    }*/
253                    List<EntityPhoneBo> phoneBoList = olePatronBo.getEntity().getEntityTypeContactInfos().get(0).getPhoneNumbers();
254                    if(phoneBoList.size() > 0) {
255                        KRADServiceLocator.getBusinessObjectService().delete(phoneBoList);
256                    }
257                    List<EntityEmailBo> emailBoList = olePatronBo.getEntity().getEntityTypeContactInfos().get(0).getEmailAddresses();
258                    if(emailBoList.size() > 0) {
259                        KRADServiceLocator.getBusinessObjectService().delete(emailBoList);
260                    }
261                    List<OlePatronNotes> patronNotesList = olePatronBo.getNotes();
262                    if(patronNotesList.size() > 0) {
263                        KRADServiceLocator.getBusinessObjectService().delete(patronNotesList);
264                    }
265                    List<OlePatronLostBarcode> lostBarcodeList = olePatronBo.getLostBarcodes();
266                    if(lostBarcodeList.size() > 0) {
267                        KRADServiceLocator.getBusinessObjectService().delete(lostBarcodeList);
268                    }
269                    List<EntityEmploymentBo> employmentBoList = olePatronBo.getEntity().getEmploymentInformation();
270                    if(employmentBoList.size() > 0) {
271                        KRADServiceLocator.getBusinessObjectService().delete(employmentBoList);
272                    }
273                    List<EntityAffiliationBo> affiliationBoList = olePatronBo.getEntity().getAffiliations();
274                    if(affiliationBoList.size() > 0) {
275                        KRADServiceLocator.getBusinessObjectService().delete(affiliationBoList);
276                    }
277                    List<OleProxyPatronDocument> proxyPatronDocuments = olePatronBo.getOleProxyPatronDocuments();
278                    if(proxyPatronDocuments.size() > 0) {
279                        KRADServiceLocator.getBusinessObjectService().delete(proxyPatronDocuments);
280                    }
281                    List<OlePatronLocalIdentificationBo> patronLocalIdentificationBos = olePatronBo.getOlePatronLocalIds();
282                    if(patronLocalIdentificationBos.size() > 0) {
283                        KRADServiceLocator.getBusinessObjectService().delete(patronLocalIdentificationBos);
284                    }
285
286                    EntityBo entity = getBusinessObjectService().save(kimEntity);
287                    newPatronBo.setEntity(kimEntity);
288                    //List<OleAddressBo> oleAddressBos = new ArrayList<OleAddressBo>();
289                    List<OleEntityAddressBo> oleEntityAddressBos = newPatronBo.getOleEntityAddressBo();
290                    newPatronBo.setEntity(kimEntity);
291                    List<EntityAddressBo> entityAddresses = kimEntity.getEntityTypeContactInfos().get(0).getAddresses();
292                    for(int i=0;i<entityAddresses.size();i++){
293                        if (i < oleEntityAddressBos.size()) {
294                            oleEntityAddressBos.get(i).setEntityAddressBo(entityAddresses.get(i));
295                        }
296                    }
297
298                    List<OleEntityPhoneBo> oleEntityPhoneBos= newPatronBo.getOleEntityPhoneBo();
299                    List<EntityPhoneBo> entityPhones = kimEntity.getEntityTypeContactInfos().get(0).getPhoneNumbers();
300                    for(int i=0;i<entityPhones.size();i++){
301                        if (i < oleEntityPhoneBos.size()) {
302                            oleEntityPhoneBos.get(i).setEntityPhoneBo(entityPhones.get(i));
303                        }
304                    }
305
306                    List<OleEntityEmailBo> oleEntityEmailBos = newPatronBo.getOleEntityEmailBo();
307                    List<EntityEmailBo> entityEmails = kimEntity.getEntityTypeContactInfos().get(0).getEmailAddresses();
308                    for(int i=0;i<entityEmails.size();i++){
309                        if (i < oleEntityEmailBos.size()) {
310                            oleEntityEmailBos.get(i).setEntityEmailBo(entityEmails.get(i));
311                        }
312                    }
313/*                    if(oleEntityAddressBos.size() > 0) {
314                        for(int i=0;i<oleEntityAddressBos.size();i++){
315                            OleAddressBo addressBo = oleEntityAddressBos.get(i).getOleAddressBo();
316                            EntityAddressBo entityAddressBo = oleEntityAddressBos.get(i).getEntityAddressBo();
317                                Map<String, Object> addMap = new HashMap<String, Object>();
318                                addMap.put(OLEConstants.OlePatron.ENTITY_BO_ID,entityAddressBo.getId());
319                                OleAddressBo oleAddressBo =  KRADServiceLocator.getBusinessObjectService().findByPrimaryKey(OleAddressBo.class,addMap);
320                                if(oleAddressBo==null){
321                                    oleAddressBo = new OleAddressBo();
322                                }
323                                oleAddressBo.setId(entityAddressBo.getId());
324                                oleAddressBo.setOlePatronId(kimEntity.getId());
325                                oleAddressBo.setOleAddressId(KRADServiceLocator.getSequenceAccessorService().getNextAvailableSequenceNumber("OLE_DLVR_ADD_S").toString());
326                                oleAddressBo.setAddressValidFrom(addressBo.getAddressValidFrom());
327                                oleAddressBo.setAddressValidTo(addressBo.getAddressValidTo());
328                                oleAddressBo.setAddressVerified(addressBo.isAddressVerified());
329                                oleAddressBo.setAddressSource(addressBo.getAddressSource());
330                                oleAddressBos.add(oleAddressBo);
331
332                            }
333                        newPatronBo.setOleAddresses(oleAddressBos);
334                        }*/
335                    updatedPatronDocument =  getBusinessObjectService().save(newPatronBo);
336                }
337            }
338        } catch (Exception ex) {
339            LOG.error(ex.getMessage());
340        }
341        LOG.debug("Leaving the updatePatron method");
342        return OlePatronDocument.to(updatedPatronDocument);
343    }
344
345    /**
346     * If the EntityNameBo is not null,it will add to the EntityBo object
347     * @param name
348     * @param entity
349     */
350    private void addName(EntityNameBo name, EntityBo entity) {
351        LOG.debug("Inside the addName method");
352        List<EntityNameBo> entityName = entity.getNames();
353        if (name != null) {
354            //name.setEntityId(entity.getId());
355            entityName.add(name);
356            entity.setNames(entityName);
357        }
358    }
359
360    /**
361     * Add the EntityName object to the Entity object
362     * @param name
363     * @param entity
364     */
365    @Override
366    public void addNameToEntity(EntityName name, Entity entity) {
367        LOG.debug("Inside the addNameToEntity method");
368        EntityBo entityBo = EntityBo.from(entity);
369        EntityNameBo nameBo = EntityNameBo.from(name);
370        addName(nameBo, entityBo);
371    }
372    /**
373     * Add the EntityEmail object to the EntityTypeContactInfo object
374     * @param emails
375     * @param entityTypeContactInfo
376     */
377    @Override
378    public void addEmailToEntity(List<EntityEmail> emails, EntityTypeContactInfo entityTypeContactInfo) {
379        LOG.debug("Inside the addEmailToEntity method");
380        List<EntityEmailBo> emailBos = new ArrayList<EntityEmailBo>();
381        for (EntityEmail email : emails) {
382            emailBos.add(EntityEmailBo.from(email));
383        }
384        addEmail(emailBos, EntityTypeContactInfoBo.from(entityTypeContactInfo));
385    }
386
387    /**
388     * If the EntityEmailBo is not null,it will add to the EntityTypeContactInfoBo object
389     * @param emails
390     * @param entityTypeContactInfoBo
391     */
392    private void addEmail(List<EntityEmailBo> emails, EntityTypeContactInfoBo entityTypeContactInfoBo) {
393        LOG.debug("Inside the addEmail method");
394        if (emails != null) {
395            entityTypeContactInfoBo.setEmailAddresses(emails);
396        }
397    }
398    /**
399     * If the EntityAddressBo is not null,it will add to the EntityTypeContactInfoBo object
400     * @param entityAddress
401     * @param entityTypeContactInfoBo
402     */
403    private void addAddress(List<EntityAddressBo> entityAddress, EntityTypeContactInfoBo entityTypeContactInfoBo) {
404        LOG.debug("Inside the addAddress method");
405        if (entityAddress != null) {
406            entityTypeContactInfoBo.setAddresses(entityAddress);
407        }
408    }
409    /**
410     * Add the EntityAddress object to the EntityTypeContactInfo object
411     * @param oleEntityAddress
412     * @param entityTypeContactInfo
413     */
414    @Override
415    public void addAddressToEntity(List<OleEntityAddressDefinition> oleEntityAddress, EntityTypeContactInfo entityTypeContactInfo) {
416        List<EntityAddressBo> addrBos = new ArrayList<EntityAddressBo>();
417        List<OleEntityAddressBo> oleAddrBos = new ArrayList<OleEntityAddressBo>();
418        for (OleEntityAddressDefinition oleAddr : oleEntityAddress) {
419            EntityAddressBo address = EntityAddressBo.from(oleAddr.getEntityAddressBo());
420            OleAddressBo oleAddress = OleAddressBo.from(oleAddr.getOleAddressBo());
421
422            oleAddrBos.add(OleEntityAddressBo.from(oleAddr));
423            addrBos.add(address);
424        }
425        addAddress(addrBos, EntityTypeContactInfoBo.from(entityTypeContactInfo));
426    }
427    /**
428     * If the EntityPhoneBo is not null,it will add to the EntityTypeContactInfoBo object
429     * @param entityPhone
430     * @param entityTypeContactInfoBo
431     */
432    public void addPhone(List<EntityPhoneBo> entityPhone, EntityTypeContactInfoBo entityTypeContactInfoBo) {
433        LOG.debug("Inside the addPhoneToEntity method");
434        if (entityPhone != null) {
435            entityTypeContactInfoBo.setPhoneNumbers(entityPhone);
436        }
437    }
438    /**
439     * Add the EntityPhone object to the EntityTypeContactInfo object
440     * @param entityPhone
441     * @param entityTypeContactInfo
442     */
443    @Override
444    public void addPhoneToEntity(List<EntityPhone> entityPhone, EntityTypeContactInfo entityTypeContactInfo) {
445        LOG.debug("Inside the addPhoneToEntity method");
446        List<EntityPhoneBo> phoneBos = new ArrayList<EntityPhoneBo>();
447        for (EntityPhone phone : entityPhone) {
448            phoneBos.add(EntityPhoneBo.from(phone));
449        }
450        addPhone(phoneBos, EntityTypeContactInfoBo.from(entityTypeContactInfo));
451    }
452
453    /**
454     * Returns EntityBo based on entityId
455     * @param entityId
456     * @return entityImpl(EntityBo)
457     */
458    private EntityBo getEntityBo(String entityId) {
459        LOG.debug("Inside the getEntityBo method");
460        EntityBo entityImpl = getBusinessObjectService().findBySinglePrimaryKey(EntityBo.class, entityId);
461        if (entityImpl != null && entityImpl.getEntityTypeContactInfos() != null) {
462            for (EntityTypeContactInfoBo et : entityImpl.getEntityTypeContactInfos()) {
463                et.refresh();
464            }
465        }
466        return entityImpl;
467    }
468
469    /**
470     * This method will set the active indicator of the patron object as false
471     * @param patronId
472     * @return OlePatronDefinition
473     */
474    @Override
475    public OlePatronDefinition inactivatePatron(String patronId) {
476        LOG.debug("Inside the inactivatePatron method");
477        OlePatronDocument patronDocument = OlePatronDocument.from(getPatron(patronId));
478        patronDocument.setActiveIndicator(false);
479        return (OlePatronDocument.to(patronDocument));
480    }
481
482    /**
483     * This method will update the EntityName object
484     * @param name
485     * @return EntityName
486     */
487    @Override
488    public EntityName updateName(EntityName name) {
489        LOG.debug("Inside the updateName method");
490        EntityNameBo entityName = EntityNameBo.from(getIdentityService().updateName(name));
491        return EntityNameBo.to(entityName);
492    }
493    /**
494     * This method will set the active indicator of the EntityNameBo object as false
495     * @param nameId
496     * @return
497     */
498    @Override
499    public boolean inactivateName(String nameId) {
500        LOG.debug("Inside the inactivateName method");
501        EntityNameBo entityName = EntityNameBo.from(getIdentityService().inactivateName(nameId));
502        if (entityName != null) {
503            return true;
504        }
505        return false;
506    }
507
508    /**
509     * This method will update the EntityEmail object
510     * @param entityEmail
511     * @return
512     */
513    @Override
514    public boolean updateEmail(EntityEmail entityEmail) {
515        LOG.debug("Inside the updateEmail method");
516        EntityEmailBo email = EntityEmailBo.from(getIdentityService().updateEmail(entityEmail));
517        if (email != null) {
518            return true;
519        }
520        return false;
521    }
522    /**
523     * This method will set the active indicator of the EntityEmailBo object as false
524     * @param emailId
525     * @return
526     */
527    @Override
528    public boolean inactivateEmail(String emailId) {
529        LOG.debug("Inside the inactivateEmail method");
530        EntityEmailBo entityEmail = EntityEmailBo.from(getIdentityService().inactivateEmail(emailId));
531        if (entityEmail != null) {
532            return true;
533        }
534        return false;
535    }
536    /**
537     * This method will update the EntityAddress object
538     * @param entityAddress
539     * @return boolean
540     */
541    @Override
542    public boolean updateAddress(EntityAddress entityAddress) {
543        LOG.debug("Inside the updateAddress method");
544        EntityAddressBo address = EntityAddressBo.from(getIdentityService().updateAddress(entityAddress));
545        if (address != null) {
546            return true;
547        }
548        return false;
549    }
550    /**
551     * This method will set the active indicator of the EntityAddressBo object as false
552     * @param addressId
553     * @return true,if entityAddress is not equal to null otherwise returns false
554     */
555    @Override
556    public boolean inactivateAddress(String addressId) {
557        LOG.debug("Inside the inactivateAddress method");
558        EntityAddressBo entityAddress = EntityAddressBo.from(getIdentityService().inactivateAddress(addressId));
559        if (entityAddress != null) {
560            return true;
561        }
562        return false;
563    }
564
565    /**
566     * This method will update the EntityPhone object
567     * @param entityPhone
568     * @return true,if phone is not equal to null otherwise returns false
569     */
570    @Override
571    public boolean updatePhone(EntityPhone entityPhone) {
572        LOG.debug("Inside the updatePhone method");
573        EntityPhoneBo phone = EntityPhoneBo.from(getIdentityService().updatePhone(entityPhone));
574        if (phone != null) {
575            return true;
576        }
577        return false;
578    }
579
580    /**
581     * This method will set the active indicator of the EntityPhoneBo object as false
582     * @param phoneId
583     * @return true,if entityPhone is not equal to null otherwise returns false
584     */
585    @Override
586    public boolean inactivatePhone(String phoneId) {
587        LOG.debug("Inside the inactivatePhone method");
588        EntityPhoneBo entityPhone = EntityPhoneBo.from(getIdentityService().inactivatePhone(phoneId));
589        if (entityPhone != null) {
590            return true;
591        }
592        return false;
593    }
594    /**
595     * This method will Persist the OlePatronNotes object
596     * @param patronNote
597     * @return boolean
598     */
599    @Override
600    public boolean addNoteToPatron(OlePatronNotesDefinition patronNote) {
601        LOG.debug("Inside the addNoteToPatron method");
602        OlePatronNotes patronNoteBo = OlePatronNotes.from(patronNote);
603        if (patronNoteBo.getOlePatronId() != null && patronNoteBo.getOlePatronNoteType() != null) {
604            getBusinessObjectService().save(patronNoteBo);
605            return true;
606        }
607        return false;
608    }
609    /**
610     * This method will Update the OlePatronNotes object
611     * @param patronNote
612     * @return boolean
613     */
614    @Override
615    public boolean updateNote(OlePatronNotesDefinition patronNote) {
616        LOG.debug("Inside the updateNote method");
617        OlePatronNotes patronNoteBo = OlePatronNotes.from(patronNote);
618        if (patronNoteBo.getOlePatronId() != null && patronNoteBo.getPatronNoteId() != null) {
619            Map<String, Object> criteria = new HashMap<String, Object>();
620            criteria.put(OLEConstants.OlePatron.PATRON_NOTE_ID, patronNote.getPatronNoteId());
621            if (getBusinessObjectService().findByPrimaryKey(OlePatronNotes.class, criteria) != null) {
622                getBusinessObjectService().save(patronNoteBo);
623                return true;
624            }
625        }
626        return false;
627    }
628
629    /**
630     * Set the active indicator of the OlePatronNotes object as false
631     * @param patronNoteId
632     * @return boolean
633     */
634    @Override
635    public boolean inactivateNote(String patronNoteId) {
636        LOG.debug("Inside the inactivateNote method");
637        if (patronNoteId != null) {
638            Map<String, Object> criteria = new HashMap<String, Object>();
639            criteria.put(OLEConstants.OlePatron.PATRON_NOTE_ID, patronNoteId);
640            OlePatronNotes patronNotes = getBusinessObjectService().findByPrimaryKey(OlePatronNotes.class, criteria);
641            patronNotes.setActive(false);
642            getBusinessObjectService().save(patronNotes);
643            return true;
644        }
645        return false;
646    }
647
648    /**
649     * This method will return all the patron documents
650     * @return OlePatronQueryResults
651     */
652    @Override
653    public OlePatronQueryResults getPatrons() {
654        LOG.debug("Inside the findPatron method");
655        GenericQueryResults<OlePatronDocument> results = getCriteriaLookupService().lookup(OlePatronDocument.class, QueryByCriteria.Builder.create().build());
656        OlePatronQueryResults.Builder builder = OlePatronQueryResults.Builder.create();
657        builder.setMoreResultsAvailable(results.isMoreResultsAvailable());
658        builder.setTotalRowCount(results.getTotalRowCount());
659
660        final List<OlePatronDefinition.Builder> ims = new ArrayList<OlePatronDefinition.Builder>();
661        for (OlePatronDocument bo : results.getResults()) {
662            ims.add(OlePatronDefinition.Builder.create(bo));
663        }
664
665        builder.setResults(ims);
666        return builder.build();
667
668    }
669    /**
670     * This method will return patron objects based on search criteria
671     * @param queryCriteria
672     * @return OlePatronQueryResults
673     */
674    @Override
675    public OlePatronQueryResults findPatron(QueryByCriteria queryCriteria) {
676        LOG.debug("Inside the findPatron method");
677        GenericQueryResults<OlePatronDocument> results = getCriteriaLookupService().lookup(OlePatronDocument.class, QueryByCriteria.Builder.create().build());
678        OlePatronQueryResults.Builder builder = OlePatronQueryResults.Builder.create();
679        builder.setMoreResultsAvailable(results.isMoreResultsAvailable());
680        builder.setTotalRowCount(results.getTotalRowCount());
681
682        final List<OlePatronDefinition.Builder> ims = new ArrayList<OlePatronDefinition.Builder>();
683        for (OlePatronDocument bo : results.getResults()) {
684            ims.add(OlePatronDefinition.Builder.create(bo));
685        }
686
687        builder.setResults(ims);
688        return builder.build();
689    }
690
691    /**
692     * This method will return Patron loan items list  information
693     * @param patronBarcode
694     * @return OleLoanDocument
695     */
696    @Override
697    public OlePatronLoanDocuments getPatronLoanedItems(String patronBarcode) {
698
699
700        List<OleLoanDocument> oleLoanDocumentList=new ArrayList<OleLoanDocument>();
701        List<OlePatronLoanDocument> olePatronLoanItemList=new ArrayList<OlePatronLoanDocument>();
702        try{
703            oleLoanDocumentList= getOleLoanDocumentsFromSolrBuilder().getPatronLoanedItemBySolr(patronBarcode, null);
704            OlePatronLoanDocuments olePatronLoanDocuments=convertPatronLoanDocuments(oleLoanDocumentList);
705            return olePatronLoanDocuments;
706        }
707        catch(Exception e){
708            LOG.error("Exception while getting patron loaned items----->  "+e);
709        }
710
711        return  null;
712    }
713
714    private OleLoanDocumentsFromSolrBuilder getOleLoanDocumentsFromSolrBuilder() {
715        if (null == oleLoanDocumentsFromSolrBuilder) {
716            oleLoanDocumentsFromSolrBuilder = new OleLoanDocumentsFromSolrBuilder();
717        }
718        return oleLoanDocumentsFromSolrBuilder;
719    }
720
721    public void setOleLoanDocumentsFromSolrBuilder(OleLoanDocumentsFromSolrBuilder oleLoanDocumentsFromSolrBuilder) {
722        this.oleLoanDocumentsFromSolrBuilder = oleLoanDocumentsFromSolrBuilder;
723    }
724
725    public List<OleDeliverRequestDefinition> getPatronRequestItems(String patronId) {
726
727
728        List<OleDeliverRequestBo> oleDeliverRequestBos =new ArrayList<OleDeliverRequestBo>();
729        List<OleDeliverRequestDefinition> oleDeliverRequestDefinitions =new ArrayList<OleDeliverRequestDefinition>();
730        try{
731            oleDeliverRequestBos = getLoanProcessor().getPatronRequestRecords(patronId);
732            OleDeliverRequestDefinition oleDeliverRequestDefinition = new OleDeliverRequestDefinition();
733            for(OleDeliverRequestBo oleDeliverRequestBo : oleDeliverRequestBos) {
734             oleDeliverRequestDefinition = OleDeliverRequestBo.to(oleDeliverRequestBo);
735                oleDeliverRequestDefinitions.add(oleDeliverRequestDefinition);
736            }
737            return oleDeliverRequestDefinitions;
738        }
739        catch(Exception e){
740            LOG.error("Exception while getting patron requested items----->  "+e);
741        }
742
743        return  null;
744    }
745
746
747
748    public OlePatronLoanDocuments performRenewalItems(OlePatronLoanDocuments olePatronLoanDocuments){
749
750        List<OleLoanDocument> oleLoanDocumentList=new ArrayList<OleLoanDocument>(0);
751        List<OleRenewalLoanDocument>  oleRenewalLoanDocumentList=convertRenewalLoanDocuments(olePatronLoanDocuments);
752        try{
753
754            for(int i=0;i<oleRenewalLoanDocumentList.size();i++){
755                OleRenewalLoanDocument oleRenewalLoanDocument=oleRenewalLoanDocumentList.get(i);
756                OleLoanDocument oleLoanDocument=getLoanProcessor().getPatronRenewalItem(oleRenewalLoanDocument.getItemBarcode());
757                if(!getLoanProcessor().checkPendingRequestforItem(oleLoanDocument.getItemId())){
758                        oleLoanDocument.setRenewalItemFlag(true);
759                        oleLoanDocument = getLoanProcessor().addLoan(oleLoanDocument.getPatronBarcode(),oleLoanDocument.getItemId(),oleLoanDocument,null);
760                }
761                else
762                  oleLoanDocument.setErrorMessage(OLEConstants.PENDING_RQST_RENEWAL_ITM_INFO+"( Title: "+oleLoanDocument.getTitle()+" , Author: "+oleLoanDocument.getAuthor()+" , Item : "+oleLoanDocument.getItemId()+" )");
763                oleLoanDocumentList.add(oleLoanDocument);
764            }
765            olePatronLoanDocuments=convertPatronLoanDocuments(oleLoanDocumentList);
766            return olePatronLoanDocuments;
767        }
768        catch(Exception e){
769            LOG.error("Exception while performing renewal---> "+e);
770        }
771        return null;
772    }
773
774
775    private OlePatronLoanDocuments convertPatronLoanDocuments(List<OleLoanDocument> oleLoanDocumentList) {
776
777
778        List<OlePatronLoanDocument> olePatronLoanItemList=new ArrayList<OlePatronLoanDocument>();
779
780        for(int i=0;i<oleLoanDocumentList.size();i++)  {
781            OleLoanDocument oleLoanDocument=oleLoanDocumentList.get(i);
782            OleRenewalLoanDocument oleRenewalLoanDocument=new OleRenewalLoanDocument();
783            oleRenewalLoanDocument.setAuthor(oleLoanDocument.getAuthor());
784            oleRenewalLoanDocument.setTitle(oleLoanDocument.getTitle());
785            oleRenewalLoanDocument.setCallNumber(oleLoanDocument.getItemCallNumber());
786            oleRenewalLoanDocument.setDueDate(oleLoanDocument.getLoanDueDate());
787            oleRenewalLoanDocument.setItemBarcode(oleLoanDocument.getItemId());
788            oleRenewalLoanDocument.setLocation(oleLoanDocument.getLocation());
789
790            if(oleLoanDocument.getErrorMessage() == null){
791                oleRenewalLoanDocument.setMessageInfo(OLEConstants.RENEWAL_ITM_SUCCESS_INFO);
792            }else
793            {
794                String errMsg="";
795                if(oleLoanDocument.getErrorMessage().contains("(OR)"))
796                   errMsg=oleLoanDocument.getErrorMessage().substring(0,oleLoanDocument.getErrorMessage().lastIndexOf("(OR)"));
797                else
798                   errMsg= oleLoanDocument.getErrorMessage();
799                oleRenewalLoanDocument.setMessageInfo(errMsg);
800            }
801            OlePatronLoanDocument olePatronLoanDocument=OlePatronLoanDocuments.to(oleRenewalLoanDocument);
802            olePatronLoanItemList.add(olePatronLoanDocument);
803        }
804        OlePatronLoanDocuments olePatronLoanDocuments=getOlePatronLoanDocuments(olePatronLoanItemList);
805        return olePatronLoanDocuments;
806
807    }
808
809
810    private List<OleRenewalLoanDocument>  convertRenewalLoanDocuments(OlePatronLoanDocuments olePatronLoanDocuments){
811
812        List<OleRenewalLoanDocument> oleRenewalLoanDocumentList=new ArrayList<OleRenewalLoanDocument>();
813        for(int i=0;i<olePatronLoanDocuments.getOlePatronLoanDocuments().size();i++){
814            OlePatronLoanDocument olePatronLoanDocument=(OlePatronLoanDocument)olePatronLoanDocuments.getOlePatronLoanDocuments().get(i);
815            OleRenewalLoanDocument oleRenewalLoanDocument=new OleRenewalLoanDocument();
816            oleRenewalLoanDocument.setItemBarcode(olePatronLoanDocument.getItemBarcode());
817            oleRenewalLoanDocument.setCallNumber(olePatronLoanDocument.getCallNumber());
818            oleRenewalLoanDocument.setDueDate(olePatronLoanDocument.getDueDate());
819            oleRenewalLoanDocument.setLocation(olePatronLoanDocument.getLocation());
820            oleRenewalLoanDocument.setTitle(olePatronLoanDocument.getTitle());
821            oleRenewalLoanDocument.setAuthor(olePatronLoanDocument.getAuthor());
822            oleRenewalLoanDocumentList.add(oleRenewalLoanDocument);
823        }
824        return oleRenewalLoanDocumentList;
825    }
826
827    private  OlePatronLoanDocuments convertOlePatronLoanDocuments(List<OleRenewalLoanDocument> oleRenewalLoanDocumentList){
828        List<OlePatronLoanDocument> olePatronLoanItemList=new ArrayList<OlePatronLoanDocument>();
829        for(int i=0;i<oleRenewalLoanDocumentList.size();i++){
830            OleRenewalLoanDocument oleRenewalLoanDocument= oleRenewalLoanDocumentList.get(i);
831            OlePatronLoanDocument olePatronLoanDocument=OlePatronLoanDocuments.to(oleRenewalLoanDocument);
832            olePatronLoanItemList.add(olePatronLoanDocument);
833        }
834        OlePatronLoanDocuments olePatronLoanDocuments=getOlePatronLoanDocuments(olePatronLoanItemList);
835        return olePatronLoanDocuments;
836    }
837
838    private OlePatronLoanDocuments  getOlePatronLoanDocuments(List<OlePatronLoanDocument> olePatronLoanItemList) {
839        OleRenewalLoanDocument oleRenewalLoanDocument=new OleRenewalLoanDocument();
840        if(olePatronLoanItemList.size()!=0) {
841            oleRenewalLoanDocument.setOlePatronLoanDocuments(olePatronLoanItemList);
842            OlePatronLoanDocuments olePatronLoanDocuments=OlePatronLoanDocuments.Builder.create(oleRenewalLoanDocument).build();
843            return olePatronLoanDocuments;
844        }
845
846        return null;
847
848    }
849
850
851
852    public void deletePatronBatchProgram() {
853        LOG.debug("Inside deletePatronDocument (Batch Delete Program)");
854        OlePatronDocument olePatronDocument = new OlePatronDocument();
855        SimpleDateFormat fmt = new SimpleDateFormat(OLEConstants.OlePatron.PATRON_MAINTENANCE_DATE_FORMAT);
856        OlePatron olePatron;
857        List<OlePatronDocument> patronImpls = (List<OlePatronDocument>) getBusinessObjectService().findAll(OlePatronDocument.class);
858        for (Iterator<OlePatronDocument> patronIterator = patronImpls.iterator(); patronIterator.hasNext(); ) {
859            olePatronDocument = patronIterator.next();
860            if ((olePatronDocument.getExpirationDate() != null && fmt.format(new Date(System.currentTimeMillis())).compareTo(fmt.format(olePatronDocument.getExpirationDate())) > 0) || (olePatronDocument.getExpirationDate() == null)) {
861                List<OleLoanDocument> oleLoanDocuments = olePatronDocument.getOleLoanDocuments();
862                List<OleTemporaryCirculationHistory> oleTemporaryCirculationHistories = olePatronDocument.getOleTemporaryCirculationHistoryRecords();
863                List<OleDeliverRequestBo> oleDeliverRequestBos = olePatronDocument.getOleDeliverRequestBos();
864                Map billMap = new HashMap();
865                billMap.put(OLEConstants.OlePatron.PAY_BILL_PATRON_ID, olePatronDocument.getOlePatronId());
866                List<PatronBillPayment> patronBillPayments = (List<PatronBillPayment>) KRADServiceLocator.getBusinessObjectService().findMatching(PatronBillPayment.class, billMap);
867                if ((oleLoanDocuments.size() == 0 && oleTemporaryCirculationHistories.size() == 0 && oleDeliverRequestBos.size() == 0 && patronBillPayments.size() == 0)) {
868                    olePatronDocument.setActiveIndicator(false);
869                    KRADServiceLocator.getBusinessObjectService().save(olePatronDocument);
870                }
871            }
872        }
873    }
874
875}