Subversion Repositories SmartDukaan

Rev

Rev 12616 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.serving.controllers;

import in.shop2020.datalogger.EventType;
import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsService;
import in.shop2020.logistics.PickupStore;

import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.AddressType;
import in.shop2020.model.v1.user.Cart;
import in.shop2020.model.v1.user.Line;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserContextService;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.Utils;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.UserClient;
import in.shop2020.utils.DataLogger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.thrift.TException;
import org.apache.velocity.VelocityContext;

@SuppressWarnings("serial")
@InterceptorRefs({
    @InterceptorRef("myDefault"),
    @InterceptorRef("login")
})

@Results({
    @Result(name="redirect", type="redirectAction", 
                params = {"actionName" , "shipping", "st", "${selectedTab}"})
})
public class ShippingController extends BaseController{
        
        private static Logger log = Logger.getLogger(ShippingController.class);
    
        private long addressId = 0;
        private String errorMsg = "";
        
        private String name;
        private String line1;
        private String line2;
        private String city;
        private String state = "";
        private String pincode;
        private String phone;
        private String country;
        private String selectedTab = "myLocation";
        
        private String dob;
    private String guardianName;

    private boolean isAnyItemInsured = false;
    private boolean isAnyItemDataProtected = false;
        private static List<PickupStore> storeAddresses = new ArrayList<PickupStore>();
        private static final List<String> allZones = new ArrayList<String>();
            
    static {
        try {
            allZones.add("All");
            LogisticsService.Client logisticsClient = (new LogisticsClient()).getClient();
            storeAddresses = logisticsClient.getAllPickupStores();
            for (PickupStore store : storeAddresses) {
                if(!allZones.contains(store.getZone())) {
                    allZones.add(store.getZone());
                }
            }
        } catch (TException e) {
            e.printStackTrace();
        }
    }
        
        public ShippingController(){
                super();
        }
        
         // GET /shipping
         public String index() {
        long userId = userinfo.getUserId();
        long cartId = userinfo.getCartId();
        String itemIdString = "";
        try {
                        UserContextService.Client userClient = (new UserClient()).getClient();
                        userClient.checkOut(cartId);
                        Cart cart = userClient.getCart(cartId);
                        itemIdString = Utils.getItemIdStringInCart(cart);
                        for(Line line : cart.getLines()) {
                            if(line.getInsurer() > 0) {
                                setAnyItemInsured(true);
                            }
                            if(line.getDataProtectionInsurer() > 0) {
                                setAnyItemDataProtected(true);
                            }
                        }
                        long defaultAddressId = cart.getAddressId();
                        if (defaultAddressId == 0) {
                            defaultAddressId = userClient.getDefaultAddressId(userId);
                        }
                        log.info("The default address id of this user is: " + defaultAddressId);
                        if(defaultAddressId > 0)
                                userClient.addAddressToCart(cartId, defaultAddressId);
                        errorMsg = userClient.validateCart(cartId, sourceId).get(0);
                        
                } catch (Exception e) {
                        // This exception can be ignored for showing the shipping page. Not so
                        // innocent when this occurs at the time of checkout or when the
                        // user is proceeding to pay.
                        log.error("Unable to get all the data required for displaying the shipping page", e);
                }
        // in case this page is redirected from payment failure
                
                Collection<String> actionErrors = getActionErrors();
                if(actionErrors != null && !actionErrors.isEmpty()){
                        for (String str : actionErrors) {
                            errorMsg += "<BR/>" + str;
                        }
                }
//        DataLogger.logData(EventType.SHIPPINIG_ACCESS, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                Long.toString(cartId), itemIdString);
                
        return "index";
         }

        // POST /entity
        public String create(){
                UserClient userContextServiceClient = null;
                in.shop2020.model.v1.user.UserContextService.Client userClient = null;
                
        String action = this.request.getParameter("action");
                if(action == null){
                        return "failure";
                }
                
                try {
                        userContextServiceClient = new UserClient();
                        userClient = userContextServiceClient.getClient();
                        
                        if(action != null){
                                if(action.equals("add")){
                                        boolean invalidInput = false;
                                        if (!Utils.validatePin(this.pincode)) {
                                                addActionError("Invalid pincode.");
                                                invalidInput = true;
                                        }
                                        if (!Utils.validatePhone(this.phone)) {
                                                addActionError("Invalid phone number.");
                                                invalidInput = true;
                                        }
                                        if (this.line1.isEmpty()) {
                                                addActionError("Address line1 is empty.");
                                                invalidInput = true;
                                        }
                                        if (this.city.isEmpty()) {
                                                addActionError("City name is empty.");
                                                invalidInput = true;
                                        }
                                        if (this.state.isEmpty()) {
                                                addActionError("State name is empty.");
                                                invalidInput = true;
                                        }
                                        if (this.pincode.isEmpty()) {
                                                addActionError("Pincode is empty.");
                                                invalidInput = true;
                                        }
                                        
                                        if (!invalidInput) {
                                                Address address = new Address();
                                                address.setName(this.name);
                                                address.setLine1(this.line1);
                                                address.setLine2(this.line2);
                                                address.setCity(this.city);
                                                address.setState(this.state);
                                                address.setPin(this.pincode);
                                                address.setPhone(this.phone);
                                                address.setCountry(this.country);
                                                address.setEnabled(true);
                                                address.setType(AddressType.HOME);
                                                long addressId = userClient.addAddressForUser(userinfo.getUserId(), address, false);
                                                userClient.addAddressToCart(userinfo.getCartId(), addressId);
                                                addActionMessage("Address added successfully.");
                                                try {
                                                if (this.guardianName != null &&
                                this.dob != null && !this.guardianName.isEmpty() && !this.dob.isEmpty()) {
                                userClient.storeInsuranceSpecificDetails(addressId, dob, guardianName);
                            }
                                                } catch(Exception e) {
                                                    log.error("Error while adding insurance specific details for address : " + addressId + ", DOB : " + dob + " GuardianName : " + guardianName, e);
                                                }
//                        DataLogger.logData(EventType.SHIPPINIG_ADD_ADDRESS, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), address.getName(),
//                                        address.getCity(), address.getPhone(), address.getPin());
                                        }
                                        return "redirect";                              
                                }
                                
                                if(action.equals("change"))     {
                                        addressId = Long.parseLong(this.request.getParameter("addressid"));
                                        if(request.getParameter("selectedTab").equals("HotSpot")) {
                                            userClient.addStoreToCart(userinfo.getCartId(), addressId);
                                        } else {
                                            userClient.addAddressToCart(userinfo.getCartId(), addressId);
                                        }
                                        
                                        errorMsg = userClient.validateCart(userinfo.getCartId(), sourceId).get(0);
//                    DataLogger.logData(EventType.SHIPPINIG_ADD_CHANGE, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),
//                            Long.toString(userinfo.getCartId()), Long.toString(addressId));
                                        return "index";
                                }
                        }
                } catch (Exception e) {
                    log.error("Error while adding address to the cart", e);
                        return "failure";
                }
                return null;
        }
        
        public String cancelInsurance() {
            try {
            in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
            boolean result = userClient.cancelInsurance(userinfo.getCartId());
            if (result == false) {
                return "failure";
            }
        } catch (Exception e) {
            log.error("Unable to cancel insurance for cart : " + userinfo.getCartId(), e);
            return "failure";
        }
        return null;
        }
        
        public String storeInsuranceDetails() {
            try {
                in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
                boolean result = userClient.storeInsuranceSpecificDetails(addressId, dob, guardianName);
                if (result == false) {
                return "failure";
            }
            } catch (Exception e) {
                log.error("Unable to store dob and guradianName for addressId : " + addressId, e);
                return "failure";
            }
            return null;
        }

        public String getShippingHeaderSnippet() {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/shippingheader.vm";
                htmlString = pageLoader.getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getShippingDetailsSnippet() {
                long userId = userinfo.getUserId();
                long cartId = userinfo.getCartId();
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/shippingdetails.vm";
                List<Map<String,String>> items = null;
                double totalamount= 0.0;
                List<Address> addresses = null;
                long defaultAddressId = 0;
                long defaultStoreAddressId = 0;
                String phoneNumber = "";
        double totalInsurance = 0.0;
        double oneAssistAmount = 0.0;
        boolean isAnyItemInsured = false;
        boolean isAnyItemDataProtected = false;
        
                CatalogClient catalogServiceClient  = null;
                in.shop2020.model.v1.catalog.CatalogService.Client catalogClient = null;
                UserClient userContextServiceClient = null;
                in.shop2020.model.v1.user.UserContextService.Client userClient = null;
                
                FormattingUtils formattingUtils = new FormattingUtils();
                
                try {
                        catalogServiceClient = new CatalogClient();
                        catalogClient = catalogServiceClient.getClient();
                        userContextServiceClient = new UserClient();
                        userClient = userContextServiceClient.getClient();
                        
                        Cart cart = userClient.getCart(cartId);
                        List<Line> lineItems = cart.getLines();
                        if( ! lineItems.isEmpty())      {
                                items = new ArrayList<Map<String,String>>();
                                for (Line line : lineItems) {
                                        Map<String, String> itemdetail = new HashMap<String, String>();
                                        Item item = catalogClient.getItemForSource(line.getItemId(), sourceId);
                                        String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
                                    + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
                                    + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" );

                    String itemColor = "";
                    if(item.getColor() != null && !item.getColor().trim().equals("NA"))
                    itemColor = "Color - " + item.getColor();
                    
                    itemdetail.put("ITEM_NAME", itemName);
                    itemdetail.put("ITEM_COLOR", itemColor);
                                        itemdetail.put("ITEM_ID", line.getItemId()+"");
                                        itemdetail.put("CATALOG_ID", item.getCatalogItemId() + "");
                                        itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity())+"");
                                        itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
                                        itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(line.getActualPrice()));
                                        itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice((line.getActualPrice()*line.getQuantity())));
                                        itemdetail.put("SHIPPING_TIME", (line.getEstimate() == -1) ? "-1" : EstimateController.getDeliveryDateString(line.getEstimate(), DeliveryType.PREPAID));
                                        itemdetail.put("BEST_DEAL_TEXT", line.isSetDealText()? line.getDealText() : item.getBestDealText());
                                        itemdetail.put("INSURANCE_AMOUNT", line.getInsuranceAmount() + "");
                                        itemdetail.put("INSURER", line.getInsurer() + "");
                                        itemdetail.put("IS_DATA_PROTECTED", (line.getDataProtectionInsurer() == 0 ? false : true) + "");
                                        itemdetail.put("ONE_ASSIST_AMOUNT", line.getDataProtectionAmount() + "");
                                        items.add(itemdetail);
                                        totalInsurance += line.getInsuranceAmount();
                                        oneAssistAmount +=line.getDataProtectionAmount();
                                        
                                        if(line.getInsurer() > 0) {
                                            isAnyItemInsured = true;
                                        }
                                        if (line.getDataProtectionInsurer() > 0){
                                                isAnyItemDataProtected = true;
                                        }
                                }
                        }
                        totalamount = cart.getTotalPrice();
                        addresses = userClient.getAllAddressesForUser(userId);
                        User user = userClient.getUserById(userId);
                        phoneNumber = user.getMobileNumber();
                        
                        if(cart.isSetAddressId())       {
                                defaultAddressId = cart.getAddressId();
                        } else  {
                                defaultAddressId = userClient.getDefaultAddressId(userId);
                        }
                        
                        if(cart.isSetPickupStoreId())    {
                defaultStoreAddressId = cart.getPickupStoreId();
            }
                
                        /*
                         *  ============================= START =====================================
                         *  The following code snippet is for extra details that are required for insurance purpose,
                         *  like father's/husband's name and Date of birth. If any item is insured in cart then we check
                         *  whether the user has any shipping addresses stored. If he has no previous addresses we ask
                         *  for those details 'in-Form' i.e. along with the address form. If he does have previous addresses,
                         *  we ask the user service if he has already stored insurance details corresponding to that address.
                         *  If such info is not present we ask for such detail in a "stand-Alone" form.
                         */
                        
                        if(isAnyItemInsured) {
                            if(addresses.size() == 0) {
                                context.put("insuranceDetailsRequired", "inForm");
                            } else {
                                if (!userClient.isInsuranceDetailPresent(defaultAddressId)) {
                                    context.put("insuranceDetailsRequired", "standAlone");
                                } else {
                                    context.put("insuranceDetailsRequired", "");
                                }
                            }
                        }
                        /*
                         * ============================== END ===========================================
                         */
                        
                        String couponCode = cart.getCouponCode();
                context.put("couponcode", couponCode == null ? "" : couponCode);
                context.put("discountedamount", formattingUtils.formatPrice(cart.getDiscountedPrice()));
                context.put("discount", formattingUtils.formatPrice(cart.getDiscountedPrice() - cart.getTotalPrice()));
                
                } catch (Exception e)   {
                        log.error("Unable to get the shipping details", e);
                }
        
                context.put("phonenumber", phoneNumber);
                context.put("items", items);
                context.put("totalamount", formattingUtils.formatPrice(totalamount));
                context.put("totalInsurance", formattingUtils.formatPrice(totalInsurance));
                context.put("addresses", addresses);
                context.put("defaultAddressId", defaultAddressId+"");
                context.put("defaultStoreAddressId", defaultStoreAddressId+"");
                context.put("errorMsg", errorMsg);
                context.put("selectedTab", selectedTab);
                context.put("storeAddresses", storeAddresses);
                context.put("allZones", allZones);
                context.put("isAnyItemInsured", isAnyItemInsured + "");
                context.put("isAnyItemDataProtected", isAnyItemDataProtected + "");
                context.put("oneAssistAmount", formattingUtils.formatPrice(oneAssistAmount) + "");
                htmlString = pageLoader.getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public long getAddressId(){
                return this.addressId;
        }
        
        public String getErrorMsg(){
                return this.errorMsg;
        }
        
        public String getName() {
                return name;
        }

        public void setName(String name) {
                this.name = name;
        }

        public String getLine1() {
                return line1;
        }

        public void setLine1(String line1) {
                this.line1 = line1;
        }

        public String getLine2() {
                return line2;
        }

        public void setLine2(String line2) {
                this.line2 = line2;
        }

        public String getCity() {
                return city;
        }

        public void setCity(String city) {
                this.city = city;
        }

        public String getState() {
                return state;
        }

        public void setState(String state) {
                this.state = state;
        }

        public String getPincode() {
                return pincode;
        }

        public void setPincode(String pincode) {
                this.pincode = pincode;
        }

        public String getCountry() {
                return country;
        }

        public void setCountry(String country) {
                this.country = country;
        }
        
        public String getPhone() {
                return phone;
        }

        public void setPhone(String phone) {
                this.phone = phone;
        }

    public String getSelectedTab() {
        return selectedTab;
    }

    public void setSelectedTab(String selectedTab) {
        this.selectedTab = selectedTab;
    }
    
    public void setSt(String selectedTab) {
        this.selectedTab = selectedTab;
    }

    public static List<String> getAllZones() {
        return allZones;
    }

    public void setAnyItemInsured(boolean isAnyItemInsured) {
        this.isAnyItemInsured = isAnyItemInsured;
    }

    public boolean isAnyItemInsured() {
        return isAnyItemInsured;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getGuardianName() {
        return guardianName;
    }

    public void setGuardianName(String guardianName) {
        this.guardianName = guardianName;
    }

    public void setAddressId(long addressId) {
        this.addressId = addressId;
    }

        public void setAnyItemDataProtected(boolean isAnyItemDataProtected) {
                this.isAnyItemDataProtected = isAnyItemDataProtected;
        }

        public boolean isAnyItemDataProtected() {
                return isAnyItemDataProtected;
        }

}