Subversion Repositories SmartDukaan

Rev

Rev 3209 | Rev 3830 | 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.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.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.velocity.VelocityContext;

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

@Results({
    @Result(name="redirect", type="redirectAction", 
                params = {"actionName" , "shipping"})
})
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;
        
        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);
                        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);
                        
                } 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 (!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.");
                        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"));
                                        userClient.addAddressToCart(userinfo.getCartId(), addressId);
                                        
                                        errorMsg = userClient.validateCart(userinfo.getCartId());
                    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 getShippingHeaderSnippet() {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/shippingheader.vm";
                htmlString = pageLoader.getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getShippingDetailsSnippet() {

                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;
                String fullName = "";
                String phoneNumber = "";

                CatalogClient catalogServiceClient  = null;
                in.shop2020.model.v1.catalog.InventoryService.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.getItem(line.getItemId());
                                        String itemName = ((item.getBrand() != null) ? item.getBrand() + " " : "")
                                                                                + ((item.getModelName() != null) ? item.getModelName() + " " : "") 
                                                                                + (( item.getModelNumber() != null ) ? item.getModelNumber() + " " : "" )
                                                                                + (( (item.getColor() != null && !item.getColor().trim().equals("NA"))) ? "("+item.getColor()+")" : "" );
                                        
                                        itemdetail.put("ITEM_NAME", itemName);
                                        itemdetail.put("ITEM_ID", line.getItemId()+"");
                                        itemdetail.put("ITEM_QUANTITY", ((int)line.getQuantity())+"");
                                        itemdetail.put("MRP", formattingUtils.formatPrice(item.getMrp()));
                                        itemdetail.put("SELLING_PRICE", formattingUtils.formatPrice(item.getSellingPrice()));
                                        itemdetail.put("TOTAL_PRICE", formattingUtils.formatPrice((item.getSellingPrice()*line.getQuantity())));
                                        itemdetail.put("SHIPPING_TIME", line.getEstimate()+"");
                                        items.add(itemdetail);
                                }
                        }
                        totalamount = cart.getTotalPrice();
                        addresses = userClient.getAllAddressesForUser(cart.getUserId());
                        User user = userClient.getUserById(cart.getUserId());
                        
                        fullName = user.getName();
                        phoneNumber = user.getMobileNumber();

                        if(cart.isSetAddressId())       {
                                defaultAddressId = cart.getAddressId();
                        } else  {
                                defaultAddressId = userClient.getDefaultAddressId(cart.getUserId());
                        }
                
                        String couponCode = cart.getCouponCode();
                context.put("couponcode", couponCode == null ? "" : couponCode);
                context.put("discountedamount", formattingUtils.formatPrice(cart.getDiscountedPrice()));
                
                } catch (Exception e)   {
                        log.error("Unable to get the shipping details", e);
                }
                System.out.println(fullName + " | " + phoneNumber);
        
                context.put("fullname", fullName);
                context.put("phonenumber", phoneNumber);
                
                context.put("items", items);
                context.put("totalamount", formattingUtils.formatPrice(totalamount));
                context.put("addresses", addresses);
                context.put("defaultAddressId", defaultAddressId+"");
                context.put("errorMsg", errorMsg);
                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;
        }
}