Subversion Repositories SmartDukaan

Rev

Rev 3224 | Rev 4453 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/**
 * 
 */
package in.shop2020.serving.controllers;


import in.shop2020.datalogger.EventType;
import in.shop2020.model.v1.user.Sex;
import in.shop2020.model.v1.user.TrackLogType;
import in.shop2020.model.v1.user.User;
import in.shop2020.serving.interceptors.TrackingInterceptor;
import in.shop2020.serving.utils.DesEncrypter;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

/**
 * 
 * @author rajveer
 *
 */

@Results({
    @Result(name = "success", type = "redirectAction", params = {"actionName" , "home"}),
    @Result(name = "failure", type = "redirectAction", params = {"actionName" , "login"}),
    @Result(name = "redirect-to-login", type = "redirectAction", params = {"actionName" , "login"}),
    @Result(name = "redirect", location = "${redirectUrl}", type = "redirect")
})
public class RegisterController extends BaseController{
        
        private static final long serialVersionUID = 1L;
        private static Logger log = Logger.getLogger(Class.class);
        private DesEncrypter desEncrypter = new DesEncrypter("saholic");
        
        private String redirectUrl = null;

        public RegisterController(){
                super();
        }

    public String index() throws SecurityException, IOException {
        if(userinfo.isLoggedIn()){
                return "success";
        }
//      htmlSnippets.put("REGISTRATION_HEADER",pageLoader.getRegistrationHeaderHtml());
//      htmlSnippets.put("REGISTRATION_FORM",pageLoader.getRegistrationFormHtml());
        return "redirect-to-login";
    }

    public String create() throws SecurityException, Exception {
        
        if(registerUser())
                return "redirect";
        else
                return "failure";
    }
    
    public boolean registerUser() throws Exception{
        String email, password, userName, mobileNumber, communicationEmail, sex, dateOfBirth;
        boolean isValid = true;
        userName =  this.request.getParameter("nameOfUser");
        email = this.request.getParameter("email"); 
        password = this.request.getParameter("txtPassword");
        
        mobileNumber = this.request.getParameter("mobileNumber");
        communicationEmail = this.request.getParameter("communicationEmail");
        
        dateOfBirth = this.request.getParameter("dateOfBirth");
        sex =  this.request.getParameter("sex");
        
        if(userName == null ){
                addActionError("Please enter name of user.");
                isValid = false;
        }
        if(email == null ){
                addActionError("Please enter valid email.");
                isValid = false;
        }
        if(password == null ){
                addActionError("Please enter password.");
                isValid = false;
        }
        if(communicationEmail == null ){
                addActionError("Please enter Communication email.");
                isValid = false;
        }
        
        if(!isValid){
            DataLogger.logData(EventType.REGISTER_DATA_INCOMPLETE, getSessionId(), userinfo.getUserId(), email, userName, communicationEmail);
                return isValid;
        }
        
                UserClient userContextServiceClient = new UserClient();
                in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();

                if(userClient.userExists(email)){
                        addActionError("User already exists with this email id.");
                        DataLogger.logData(EventType.REGISTER_FAILED_USER_EXISTS, getSessionId(), userinfo.getUserId(), email, userName, communicationEmail);
                        return false;
                }

                User user = new User();
                user.setName(userName);
                user.setEmail(email);
                String encryptedPassword = desEncrypter.encrypt(password);
                user.setPassword(encryptedPassword);
                user.setCommunicationEmail(communicationEmail);
                user.setMobileNumber(mobileNumber);
                user.setDateOfBirth(dateOfBirth);
                Cookie sourceCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_COOKIE);
        if (sourceCookie != null) {
            DesEncrypter des = new DesEncrypter(TrackingInterceptor.ENCRIPTION_STRING);
            String sourceCookieVal = des.decrypt(sourceCookie.getValue());
            user.setSource(sourceCookieVal);
        }
        
        Cookie sourceTimeCookie = (Cookie) cookiesMap.get(TrackingInterceptor.SRC_TIME_COOKIE);
        long sourceTime = 0;
        if (sourceTimeCookie != null) {
            try {
                sourceTime = Long.parseLong(sourceTimeCookie.getValue());
            }
            catch (Exception e) {
                log.warn("Unable to parse session src time cookie.");
            }
            user.setSourceStartTime(sourceTime);
        }
                
                user.setSex(Sex.WONT_SAY);
                if (sex != null) {
                        try {
                                user.setSex(Sex.findByValue(Integer.parseInt(sex)));
                        } catch (NumberFormatException nfe) {
                                log.error("Unusual value for sex. Leaving it marked as won't say.");
                        }
                }


                user = userClient.createUser(user);
                long userId = user.getUserId();
                userClient.setUserAsLoggedIn(userId, (new Date()).getTime());
                String pincode = userClient.getDefaultPincode(user.getUserId());
                
                // TODO: setTotalItems shouldn't be a method on userinfo. This allows
                // for potentially updating the item count wrongly. The method setCartId
                // should update the item count as well. Also, there can be a method
                // called refreshItemCount() that automatically updates the number of
                // items currently in the cart.
                if(userinfo.getUserId() != -1){
                        userClient.mergeCart(userinfo.getCartId(), user.getActiveCartId());
                
                        List<Long> items = userClient.getBrowseHistoryItems(userinfo.getUserId());
                        if(items != null){
                                for(Long itemId: items){
                                        userClient.updateBrowseHistory(user.getUserId(), itemId);
                                }
                        }
                
                        items = userClient.getMyResearchItems(userinfo.getUserId());
                        if(items != null){
                                for(Long itemId: items){
                                        userClient.updateMyResearch(user.getUserId(), itemId);
                                }
                        }
                }
                
                userinfo.setUserId(userId);
                userinfo.setNameOfUser(userName);
                userinfo.setEmail(email);
                userinfo.setLoggedIn(true);
                userinfo.setPincode(pincode);
                userinfo.setCartId(user.getActiveCartId());
                int totalItems = userClient.getCart(userinfo.getCartId()).getLinesSize();
                userinfo.setTotalItems(totalItems);
        if (cookiesMap.containsKey(TrackingInterceptor.AFF_COOKIE)) {
            long affId = Long.parseLong(cookiesMap.get(TrackingInterceptor.AFF_COOKIE).getValue());
            userClient.addTrackLog(affId, userId, TrackLogType.NEW_REGISTRATION, "",email, (new Date()).getTime());
        }
        DataLogger.logData(EventType.REGISTER_SUCCESS, getSessionId(), userinfo.getUserId(), email, userName, communicationEmail);

                return true;
    }

        public String getRegistrationHeaderSnippet(){
                return htmlSnippets.get("REGISTRATION_HEADER");
        }
        
        public String getRegistrationFormSnippet(){
                return htmlSnippets.get("REGISTRATION_FORM");
        }
        public String getRedirectUrl() {
                return redirectUrl;
        }

        public void setRedirectUrl(String redirectUrl) {
                this.redirectUrl = redirectUrl;
        }
}