001package org.kuali.ole.deliver.lookup;
002
003import org.apache.commons.lang.StringUtils;
004import org.kuali.ole.OLEConstants;
005import org.kuali.ole.OleLookupableImpl;
006import org.kuali.ole.deliver.bo.OLEPatronEntityViewBo;
007import org.kuali.ole.deliver.bo.OlePatronDocument;
008import org.kuali.ole.deliver.bo.PatronBillPayment;
009import org.kuali.ole.service.OlePatronHelperService;
010import org.kuali.ole.service.OlePatronHelperServiceImpl;
011import org.kuali.rice.core.api.util.RiceKeyConstants;
012import org.kuali.rice.kim.impl.identity.email.EntityEmailBo;
013import org.kuali.rice.kim.impl.identity.name.EntityNameBo;
014import org.kuali.rice.kim.impl.identity.phone.EntityPhoneBo;
015import org.kuali.rice.krad.lookup.LookupUtils;
016import org.kuali.rice.krad.lookup.LookupableImpl;
017import org.kuali.rice.krad.service.KRADServiceLocator;
018import org.kuali.rice.krad.uif.UifConstants;
019import org.kuali.rice.krad.uif.UifParameters;
020import org.kuali.rice.krad.uif.field.InputField;
021import org.kuali.rice.krad.uif.util.ComponentUtils;
022import org.kuali.rice.krad.uif.view.LookupView;
023import org.kuali.rice.krad.util.GlobalVariables;
024import org.kuali.rice.krad.util.KRADConstants;
025import org.kuali.rice.krad.util.KRADUtils;
026import org.kuali.rice.krad.util.UrlFactory;
027import org.kuali.rice.krad.web.form.LookupForm;
028
029import java.util.*;
030
031/**
032 * OlePatronLookupableImpl makes validation  and populate the search criteria and return the search results
033 */
034public class OlePatronEnitityLookupableImpl extends OleLookupableImpl {
035    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePatronEnitityLookupableImpl.class);
036    List<?> searchResults;
037    OlePatronHelperService olePatronHelperService = new OlePatronHelperServiceImpl();
038    public static int count = 0;
039
040    /**
041     * This method will populate the search criteria and return the search results
042     *
043     * @param form
044     * @param searchCriteria
045     * @param bounded
046     * @return displayList(Collection)
047     */
048    @Override
049    public Collection<?> performSearch(LookupForm form, Map<String, String> searchCriteria, boolean bounded) {
050        LOG.debug("Inside performSearch()");
051        List<OLEPatronEntityViewBo> olePatronDocuments=new ArrayList<OLEPatronEntityViewBo>();
052        List<OLEPatronEntityViewBo> finalResult=new ArrayList<OLEPatronEntityViewBo>();
053        List<String> olePatronIdList=new ArrayList<String>();
054        Map<String,String> searchEntityMap=new HashMap<String,String>();
055        Map<String,String> searchEntityPhoneMap=new HashMap<String,String>();
056        Map<String,String> searchEntityEmailMap=new HashMap<String,String>();
057        LookupUtils.preprocessDateFields(searchCriteria);
058        String firstName = searchCriteria.get(OLEConstants.OlePatron.PATRON_FIRST_NAME);
059        String middleName = searchCriteria.get("middleName");
060        String lastName = searchCriteria.get(OLEConstants.OlePatron.PATRON_LAST_NAME);
061        String email = searchCriteria.get("emailAddress");
062        String phoneNumber = searchCriteria.get("phoneNumber");
063        String patronType = searchCriteria.get("patronType");
064        if(StringUtils.isNotEmpty(searchCriteria.get("patronBarcode"))){
065            searchCriteria.remove("active");
066        }
067        if(StringUtils.isNotEmpty(firstName)){
068            searchEntityMap.put("firstName",firstName);
069        }
070        if(StringUtils.isNotEmpty(lastName)){
071            searchEntityMap.put("lastName",lastName);
072        }
073        if(StringUtils.isNotEmpty(middleName)){
074            searchEntityMap.put("middleName",middleName);
075        }
076        if(StringUtils.isNotEmpty(phoneNumber)){
077            searchEntityPhoneMap.put("phoneNumber",phoneNumber);
078        }
079        if(StringUtils.isNotEmpty(email)){
080            searchEntityEmailMap.put("emailAddress",email);
081        }
082
083        if (StringUtils.isNotBlank(phoneNumber)) {
084            if (!validatePhoneNumber(phoneNumber)) {
085                GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS, OLEConstants.INVALID_PHONE_NUMBER_FORMAT);
086                return new ArrayList<Object>();
087            }
088            phoneNumber = buildPhoneNumber(phoneNumber);
089        }
090        //finalResult = (List<OLEPatronEntityViewBo>) super.performSearch(form,searchCriteria,true);
091        Collection<?> displayList;
092
093        // TODO: force uppercase will be done in binding at some point
094        displayList = getSearchResults(form, LookupUtils.forceUppercase(getDataObjectClass(), searchCriteria),
095                !bounded);
096
097        // TODO delyea - is this the best way to set that the entire set has a returnable row?
098        for (Object object : displayList) {
099           /* if(object instanceof OLEPatronEntityViewBo){
100                OLEPatronEntityViewBo patronEntityViewBo = (OLEPatronEntityViewBo) object;
101                patronEntityViewBo.setCreateBillUrl(getPatronBillUrl(patronEntityViewBo.getPatronId(),patronEntityViewBo.getFirstName(),patronEntityViewBo.getLastName()));
102                if(patronEntityViewBo.getBillCount()>0){
103                    patronEntityViewBo.setPatronBillFileName("Patron Bill");
104                    patronEntityViewBo.setViewBillUrl("patronbill?viewId=BillView&amp;methodToCall=start&amp;patronId=" + patronEntityViewBo.getPatronId());
105                }
106            }*/
107            if (isResultReturnable(object)) {
108                form.setAtLeastOneRowReturnable(true);
109            }
110        }
111
112        finalResult = (List<OLEPatronEntityViewBo>) displayList;
113        searchResults=finalResult;
114        return finalResult;
115    }
116
117
118
119    /**
120     * This method will validate the criteria fields
121     *
122     * @param lookupView
123     * @param form
124     * @return criteriaFieldMap(Map)
125     */
126    @Override
127    protected Map<String, InputField> getCriteriaFieldsForValidation(LookupView lookupView, LookupForm form) {
128        LOG.debug("Inside getCriteriaFieldsForValidation()");
129        Map<String, InputField> criteriaFieldMap = new HashMap<String, InputField>();
130
131        List<InputField> fields = ComponentUtils.getComponentsOfTypeDeep(lookupView.getCriteriaFields(),
132                InputField.class);
133
134        for (InputField field : fields) {
135            criteriaFieldMap.put(field.getPropertyName(), field);
136        }
137
138        return criteriaFieldMap;
139    }
140
141    /**
142     * This method is to override the maintenance mapping
143     *
144     * @param lookupForm
145     * @param dataObject
146     * @param methodToCall
147     * @param pkNames
148     * @return mapping Url
149     */
150    @Override
151    protected String getActionUrlHref(LookupForm lookupForm, Object dataObject, String methodToCall,
152                                      List<String> pkNames) {
153        LOG.debug("Inside getActionUrlHref()");
154        LookupView lookupView = (LookupView) lookupForm.getView();
155
156        Properties props = new Properties();
157        props.put(KRADConstants.DISPATCH_REQUEST_PARAMETER, methodToCall);
158        Map<String, String> primaryKeyValues = KRADUtils.getPropertyKeyValuesFromDataObject(pkNames, dataObject);
159        for (String primaryKey : primaryKeyValues.keySet()) {
160            String primaryKeyValue = primaryKeyValues.get(primaryKey);
161
162            props.put(primaryKey, primaryKeyValue);
163        }
164
165        if (StringUtils.isNotBlank(lookupForm.getReturnLocation())) {
166            props.put(KRADConstants.RETURN_LOCATION_PARAMETER, lookupForm.getReturnLocation());
167        }
168
169        props.put(UifParameters.DATA_OBJECT_CLASS_NAME, OlePatronDocument.class.getName());
170        props.put(UifParameters.VIEW_TYPE_NAME, UifConstants.ViewType.MAINTENANCE.name());
171
172        String maintenanceMapping = OLEConstants.OlePatron.PATRON_MAINTENANCE_ACTION_LINK;
173
174        return UrlFactory.parameterizeUrl(maintenanceMapping, props);
175    }
176
177    /**
178     * This method will return the url for create bill link in patron record.
179     *
180     * @return link url
181     */
182
183    public String getPatronBillUrl(String patronId, String firstName, String lastName) {
184        String url = "patronBillMaintenance?viewTypeName=MAINTENANCE&returnLocation=%2Fportal.do&methodToCall=start&dataObjectClassName=org.kuali.ole.deliver.bo.PatronBillPayment&patronId=" + patronId + "&firstName=" + firstName + "&lastName=" + lastName;
185        return url;
186    }
187
188    public boolean isWildCardMatches(String word, String wildCardString) {
189        if (LOG.isInfoEnabled()) {
190            LOG.info("Applying WildCard Search");
191        }
192        boolean isSuccess = true;
193        if (wildCardString != null && (!wildCardString.equalsIgnoreCase("")) && wildCardString.contains("*")) {
194            if (wildCardString.equalsIgnoreCase("*")) {
195                isSuccess = true;
196            } else {
197                wildCardString = wildCardString.replace('*', ',');
198                String[] wCardString = wildCardString.split(",");
199                if (wCardString != null && wCardString.length > 0) {
200                    for (String str : wCardString) {
201                        if (word.toLowerCase().contains(str.toLowerCase())) {
202                            isSuccess = isSuccess && true;
203                        } else {
204                            isSuccess = isSuccess && false;
205                        }
206                    }
207                } else {
208                    isSuccess = false;
209                    if (word.equalsIgnoreCase(wildCardString)) {
210                        isSuccess = true;
211                    }
212                }
213            }
214            return isSuccess;
215        } else {
216            if (wildCardString.equalsIgnoreCase(word)) {
217                return true;
218            } else {
219                return false;
220            }
221        }
222    }
223
224    private boolean validatePhoneNumber(String phoneNo) {
225        if (LOG.isInfoEnabled()) {
226            LOG.info("Validating the Phone Number  Format - ##########, (###)###-#### , ###-###-#### , ### ###-#### , ### ### ####");
227        }
228        if (phoneNo.matches("\\d{10}")) return true;
229        else if (phoneNo.matches("\\d{3}[-]\\d{3}[-]\\d{4}")) return true;
230        else if (phoneNo.matches("\\d{3}[\\s]\\d{3}[-]\\d{4}")) return true;
231        else if (phoneNo.matches("\\d{3}[\\s]\\d{3}[\\s]\\d{4}")) return true;
232        else if (phoneNo.matches("\\(\\d{3}\\)[\\s]\\d{3}[-]\\d{4}")) return true;
233        else return false;
234
235    }
236    private String buildPhoneNumber(String phoneNumber){
237        StringBuilder userPhoneNumber = new StringBuilder();
238        for (int i = 0; i < phoneNumber.length(); i++) {
239            if (Character.isDigit(phoneNumber.charAt(i))) {
240                userPhoneNumber.append(phoneNumber.charAt(i));
241            }
242        }
243        return userPhoneNumber.toString();
244    }
245
246}