Subversion Repositories SmartDukaan

Rev

Rev 5036 | Rev 12616 | 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.Cart;
import in.shop2020.model.v1.user.Sex;
import in.shop2020.model.v1.user.ShoppingCartException;
import in.shop2020.model.v1.user.TrackLogType;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserAffiliateException;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.model.v1.user.WidgetException;
import in.shop2020.serving.interceptors.TrackingInterceptor;
import in.shop2020.serving.utils.DesEncrypter;
import in.shop2020.serving.utils.Utils;
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;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

/**
 * 
 * @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 = "/";

        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(){
        String email, password;
        boolean isValid = true;
        email = this.request.getParameter("email"); 
        password = this.request.getParameter("txtPassword");
        
        if(!Utils.isValidEmail(email))  {
                addActionError("Please enter valid email address.");
                isValid = false;
        }
        if(password == null )   {
                addActionError("Please enter password.");
                isValid = false;
        }
        
        if(!isValid){
            DataLogger.logData(EventType.REGISTER_DATA_INCOMPLETE, getSessionId(), userinfo.getUserId(), email, "", email);
                return isValid;
        }
        
                User user = new User();
                user.setEmail(email);
                String encryptedPassword = desEncrypter.encrypt(password);
                user.setPassword(encryptedPassword);
                user.setCommunicationEmail(email);
                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);
                

                UserClient userContextServiceClient;
                try {
                        userContextServiceClient = new UserClient();
                
                        in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
                        try{
                                user = userClient.createUser(user);
                        }catch (UserContextException ux){
                                addActionError("User already exists with this email id.");
                                DataLogger.logData(EventType.REGISTER_FAILED_USER_EXISTS, getSessionId(), userinfo.getUserId(), email, "", email);
                                return false;                           
                        }
                        
                        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.setEmail(email);
                        userinfo.setLoggedIn(true);
                        userinfo.setPincode(pincode);
                        userinfo.setCartId(user.getActiveCartId());
                        Cart cart = userClient.getCart(userinfo.getCartId());
                        userinfo.setTotalItems(cart.getLinesSize());
                        userinfo.setTotalAmount(cart.getTotalPrice());
                        
                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, "", email);
        
                        return true;
                } catch (TTransportException e) {
                        log.error("Unable to register user." + e);
                } catch (UserContextException e) {
                        log.error("Unable to register user." + e);
                } catch (TException e) {
                        log.error("Unable to register user." + e);
                } catch (UserAffiliateException e) {
                        log.error("Unable to register user." + e);
                } catch (ShoppingCartException e) {
                        log.error("Unable to register user." + e);
                } catch (WidgetException e) {
                        log.error("Unable to register user." + e);
                }
                DataLogger.logData(EventType.REGISTER_FAILED_USER_EXISTS, getSessionId(), userinfo.getUserId(), email, "", email);
                return false;
                
    }

        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;
        }
}