Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.services;

import in.shop2020.logistics.PickupStore;
import in.shop2020.logistics.Provider;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.OrderStatus;
import in.shop2020.model.v1.order.OrderStatusGroups;
import in.shop2020.model.v1.user.Address;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.serving.utils.FormattingUtils;
import in.shop2020.serving.utils.Utils;
import in.shop2020.thrift.clients.LogisticsClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;


public class PageLoaderHandler {

    private static Logger logger = Logger.getLogger(PageLoaderHandler.class);
    
        public String getSlideGuideHtml(long productId) {
                StringBuilder htmlString = new StringBuilder();
                String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "SlideGuide.html";
                File f = new File(filename);
                
                
                FileInputStream fis = null;
                try {
                        fis = new FileInputStream(f);
                        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                        String line;
                        while((line = br.readLine()) != null){
                                htmlString.append(line+"\n");
                        }
                } catch (FileNotFoundException e) {
                        logger.error("Unable to find the slide guide for " + productId, e);
                } catch (IOException e) {
                    logger.error("Unable to read the slide guide for " + productId, e);
                }
                finally {
                        if(fis != null) {
                                try {
                                        fis.close();
                                } catch (IOException e) {
                                    logger.warn("Unable to close the slide guide for " + productId, e);
                                }
                        }
                }
                
                return htmlString.toString();
        }

        public String getProductSummaryHtml(long productId) {
                StringBuilder htmlString = new StringBuilder();
                String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "ProductDetail.html";
                File f = new File(filename);
                
                
                FileInputStream fis = null;
                try {
                        fis = new FileInputStream(f);
                        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                        String line;
                        while((line = br.readLine()) != null){
                                htmlString.append(line+"\n");
                        }
                } catch (FileNotFoundException e) {
                        logger.error("Unable to find the product summary file", e);
                } catch (IOException e) {
                        logger.error("Unable to read the product summary file", e);
                }
                finally {
                        if(fis != null) {
                                try {
                                        fis.close();
                                } catch (IOException e) {
                                        logger.error("Unable to close the product summary file", e);
                                }
                        }
                }
                
                return htmlString.toString();
        }

        public String getProductPropertiesHtml(long productId) {
                StringBuilder htmlString = new StringBuilder();
                String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "ProductPropertiesSnippet.html";
                File f = new File(filename);
                
                
                FileInputStream fis = null;
                try {
                        fis = new FileInputStream(f);
                        BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                        String line;
                        while((line = br.readLine()) != null){
                                htmlString.append(line+"\n");
                        }
                } catch (FileNotFoundException e) {
                    logger.error("Unable to find the product properties file", e);
                } catch (IOException e) {
                        logger.error("Unable to read the product properties file", e);
                } finally {
                        if(fis != null) {
                                try {
                                        fis.close();
                                } catch (IOException e) {
                                        logger.error("Unable to close the product properties file", e);
                                }
                        }
                }
                
                return htmlString.toString();
        }
        
        public String getSearchBarHtml(long itemCounts, long categoryId) {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/searchbar.vm";
                
                context.put("itemCount", itemCounts+"");
                context.put("categoryId", categoryId+"");
                
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getHeaderHtml(boolean isLoggedIn, String email, int totalItems, String url, long catId, boolean displayBestDealsImg)      {
                VelocityContext context = new VelocityContext();
                
                if (isLoggedIn) {
                        context.put("LOGGED_IN", "TRUE");
                        context.put("WELCOME_MESSAGE", "Hi " + email.split("@")[0]);
                        
                } else  {
                        context.put("WELCOME_MESSAGE", "Hi, Welcome to Saholic");
                        context.put("REDIRECT_URL", url);
                }
                
                context.put("BEST_DEALS_BADGE", displayBestDealsImg);
                context.put("CAT_ID", catId);
                context.put("TOTAL_ITEMS", totalItems);
                String templateFile = "templates/header.vm";
                
                return getHtmlFromVelocity(templateFile, context);
        }

        
        public String getOrderDetailsHtml(long orderId, UserSessionInfo userinfo) {
                long userId = userinfo.getUserId();
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/orderdetails.vm";
                Order order = null;
                Date orderedOn = null, deliveryEstimate = null;
                Provider provider = null;
        List<Address> addresses = null;
        Long defaultAddressId = null;
        boolean initiateOrderCancelation = false;
        boolean requestOrderCancelation = false;
        OrderStatusGroups Groups = new OrderStatusGroups();
        List<OrderStatus> codCancellable = Groups.getCodCancellable();
        List<OrderStatus> prepaidCancellableBeforeBilled = Groups.getPrepaidCancellableBeforeBilled();
        List<OrderStatus> prepaidCancellableAfterBilled = Groups.getPrepaidCancellableAfterBilled();
        
        try{
                        TransactionClient transactionServiceClient = new TransactionClient();
                        in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient.getClient();
                        order = orderClient.getOrderForCustomer(orderId, userId);
                        orderedOn = new Date(order.getCreated_timestamp());
                        deliveryEstimate = new Date(order.getExpected_delivery_time());
                        
                        if(order.isCod()){
                                if(codCancellable.contains(order.getStatus())){
                                        initiateOrderCancelation = true;
                                }
                        }
                        else {
                                if(prepaidCancellableBeforeBilled.contains(order.getStatus())){
                                        initiateOrderCancelation = true;
                                }
                                else if(prepaidCancellableAfterBilled.contains(order.getStatus())){
                                        requestOrderCancelation = true;
                                }
                        }

                        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
                        addresses = userClient.getAllAddressesForUser(userId);
                        defaultAddressId = userClient.getDefaultAddressId(userId);
                        logger.info("Found addresses: " + addresses + " for userId: " + userId);

                        if(order.getLogistics_provider_id() != 0){
                                LogisticsClient logisticsServiceClient = new LogisticsClient();
                                in.shop2020.logistics.LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
                                provider = logisticsClient.getProvider(order.getLogistics_provider_id());
                        }

                        if (order.getPickupStoreId() != 0) {
                            in.shop2020.logistics.LogisticsService.Client logisticsServiceClient = new LogisticsClient().getClient();
                            PickupStore store = logisticsServiceClient.getPickupStore(order.getPickupStoreId());
                            order.setCustomer_name(store.getName());
                            order.setCustomer_address1(store.getLine1());
                            order.setCustomer_address2(store.getLine2());
                            order.setCustomer_city(store.getCity());
                            order.setCustomer_pincode(store.getPin());
                            order.setCustomer_state(store.getState());
                            order.setCustomer_mobilenumber(store.getPhone());
                        }
                } catch (Exception e){
                        
                }
                
                SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
                SimpleDateFormat dateformat1 = new SimpleDateFormat("dd/MM/yyyy");
                
                context.put("order", order);
                context.put("orderedOn", dateformat.format(orderedOn));
                context.put("deliveryEstimate", dateformat1.format(deliveryEstimate));
                context.put("addresses", addresses);
                context.put("defaultAddressId", defaultAddressId);
                context.put("userinfo", userinfo);
                context.put("initiateOrderCancelation", initiateOrderCancelation);
                context.put("requestOrderCancelation", requestOrderCancelation);

                if(provider!=null){
                        context.put("providerName", provider.getName());
                }

                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getMyaccountDetailsHtml(long userId) {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/myaccount.vm";
                List<Order> orders = null;
                Map<Long, String> providerNames = new HashMap<Long, String>();
                try{
                        TransactionClient transactionServiceClient = new TransactionClient();
                        in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient.getClient();
                        orders = orderClient.getOrdersForCustomer(userId, 0, (new Date()).getTime(), null);
                        
                        LogisticsClient logisticsServiceClient = new LogisticsClient();
                        in.shop2020.logistics.LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
                        List<Provider> providers = logisticsClient.getAllProviders();
                        for(Provider provider: providers)
                                providerNames.put(provider.getId(), provider.getName());
                }catch (Exception e){
                        logger.error("Unable to get order or provider details", e);
                }
                List<String> orderDate = new ArrayList<String>();
                SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
                if(orders!=null && !orders.isEmpty()){
                        for(Order order: orders){
                                Date orderedOn = new Date(order.getCreated_timestamp());
                                orderDate.add(dateformat.format(orderedOn));
                        }
                }
                context.put("orders", orders);
                context.put("orderDate", orderDate);
                context.put("providerNames", providerNames);
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }

        
        public String getLoginDetailsHtml(long userId) {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/logindetails.vm";
                String email = "";
                try{
                        email = getEmailId(userId);
                }catch (Exception e){
                        
                }
                context.put("email", email);
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getEmailId(long userId){
                String email = " ";
                
                try {
                        UserClient userContextServiceClient = new UserClient();
                        in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
                        String userEmail = userClient.getUserById(userId).getEmail(); 
                        if( userEmail != null){
                                email = userEmail;
                        }
                } catch (UserContextException e) {
                        logger.error("Unable to get the user for " + userId, e);
                } catch (TException e) {
                    logger.error("Unable to get the user for " + userId, e);
                } catch (Exception e) {
                    logger.error("Unable to get the user for " + userId, e);
                }
                return email; 
        }

        
        public String getPersonalDetailsHtml(long userId) {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/personaldetails.vm";
                String email = "";
                String name = "";
                String dateOfBirth = "";
                String sex = "";
                String subscribe = "false";
                UserClient userContextServiceClient = null;
                in.shop2020.model.v1.user.UserContextService.Client userClient = null;
                try{
                        User user = null;
                        userContextServiceClient = new UserClient();
                        userClient = userContextServiceClient.getClient();
                        user = userClient.getUserById(userId);
                        
                        email = user.getCommunicationEmail();
                        name = user.getName();
                        
                        dateOfBirth = user.getDateOfBirth();
                }catch (Exception e){
                    logger.error("Unable to get the user for " + userId, e);
                }
                context.put("name", name);
                context.put("email", email);
                context.put("dateOfBirth", dateOfBirth+"");
                context.put("subscribe", subscribe);
                context.put("sex", sex);
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }
        
        public String getMyaccountHeaderHtml() {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/myaccountheader.vm";
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }

        public String getShippingAddressDetailsHtml(long userId, String errorMsg){
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/shippingaddressdetails.vm";
                long defaultAddressId = 0;
                List<Address> addresses = null;
                
                UserClient userContextServiceClient = null;
                in.shop2020.model.v1.user.UserContextService.Client userClient = null;
                try {
                        userContextServiceClient = new UserClient();
                        userClient = userContextServiceClient.getClient();
                        
                        addresses = userClient.getAllAddressesForUser(userId);
                        defaultAddressId = userClient.getDefaultAddressId(userId);
                } catch (Exception e) {
                    logger.error("Unable to get either the user for " + userId + " or his address", e);
                }
                context.put("defaultAddressId", defaultAddressId+"");
                context.put("addresses", addresses);
                context.put("errorMsg", errorMsg);
                
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }

        public String getHtmlFromVelocity(String templateFile, VelocityContext context){
                Properties p = new Properties();
                p.setProperty("resource.loader", "class");
                p.setProperty("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
                p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); 
                
        try {
            Velocity.init(p);
            // Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, value)
            Template template = Velocity.getTemplate(templateFile);
            if (template != null) {
                StringWriter writer = new StringWriter();
                template.merge(context, writer);
                writer.flush();
                writer.close();
                return writer.toString();
            }

        } catch (ResourceNotFoundException e) {
            logger.error("Unable to find the template file " + templateFile, e);
        } catch (ParseErrorException e) {
            logger.error("Unable to parse the template file " + templateFile, e);
        } catch (MethodInvocationException e) {
            logger.error("Unable to invoke methods for the velocity template file " + templateFile, e);
        } catch (IOException e) {
            logger.error("Unable to read the template file " + templateFile, e);
        } catch (Exception e) {
            logger.error("Unable to generate the HTML from the template file " + templateFile, e);
        }
        
                return null;
        }

        public String getCartWidgetSnippet(int totalItems, double totalAmount) {
                String htmlString = "";
                VelocityContext context = new VelocityContext();
                String templateFile = "templates/cartwidget.vm";
                htmlString = getHtmlFromVelocity(templateFile, context);
                return htmlString;
        }

}