Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import in.shop2020.crm.Activity;
import in.shop2020.crm.ActivityType;
import in.shop2020.crm.CRMService.Client;
import in.shop2020.crm.Ticket;
import in.shop2020.crm.TicketCategory;
import in.shop2020.crm.TicketPriority;
import in.shop2020.crm.TicketStatus;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.user.User;
import in.shop2020.model.v1.user.UserCommunicationException;
import in.shop2020.model.v1.user.UserCommunicationType;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.model.v1.user.UserContextService;
import in.shop2020.serving.utils.UserMessage;
import in.shop2020.thrift.clients.CRMClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.UserClient;

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

import org.apache.log4j.Logger;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

/**
 * @author Varun Gupta
 */

@SuppressWarnings("serial")
public class ContactUsController extends BaseController {

    private static final long     ADMIN_AGENT_ID = 1;

    private String                id;

    private static Logger         log        = Logger.getLogger(Class.class);

    private UserCommunicationType formType   = null;

    List<Order>                   orders     = null;
    List<LineItem>                products   = null;
    List<Long>                    order_ids  = null;

    public ContactUsController() {
        super();
    }

    // GET /Show Form
    public String index() {
        try {
            TransactionClient transactionServiceClient = new TransactionClient();
            in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient
                    .getClient();
            orders = orderClient.getOrdersForCustomer(userinfo.getUserId(), 0,
                    (new Date()).getTime(), null);
        } catch (Exception e) {
            log.error("Unable to get the orders for the user becauase of: ", e);
        }

        if (request.getParameter("type") != null) {
            String requestedFormType = request.getParameter("type").toString()
                    .trim();
            log.debug("Contact us requested for: " + requestedFormType);

            if (requestedFormType.equals("return")) {
                this.formType = UserCommunicationType.RETURN_FORM;
            } else if (requestedFormType.equals("cancel")) {
                this.formType = UserCommunicationType.ORDER_CANCELLATION;
            } else if (requestedFormType.equals("delivery")) {
                this.formType = UserCommunicationType.DELIVERY_PROBLEM;
            }
        }
        return "index";
    }

    public String show() throws SecurityException, IOException {
        try {
            TransactionClient transactionServiceClient = new TransactionClient();
            in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient
                    .getClient();

            if (id.equals("to_return")) {
                order_ids = orderClient.getReturnableOrdersForCustomer(
                        userinfo.getUserId(), 0);
            } else if (id.equals("to_cancel")) {
                order_ids = orderClient.getCancellableOrdersForCustomer(
                        userinfo.getUserId(), 0);
            } else if (id.equals("all_orders")) {
                orders = orderClient.getOrdersForCustomer(userinfo.getUserId(),
                        0, (new Date()).getTime(), null);
            } else {
                long orderId = Integer.parseInt(id);
                products = orderClient.getLineItemsForOrder(orderId);
            }
        } catch (NumberFormatException e) {
            log.error("Unable to get order id", e);
        } catch (Exception e) {
            log.error("Unable to get user order details: ", e);
        }
        return "ajax";
    }

    // POST /Save Communication
    public String create() {
        // Default communication type OTHER
        long communicationType = 8;
        long orderId = -1;

        try {
            boolean isUserLoggedIn = userinfo.isLoggedIn();
            long userId = isUserLoggedIn ? userinfo.getUserId() : 0;
            String email = request.getParameter("email");
            communicationType = Integer.parseInt(request
                    .getParameter("communication_type"));

            if (request.getParameter("order_id") != null) {
                orderId = Integer.parseInt(request.getParameter("order_id"));
            }

            String awb = request.getParameter("awb");
            String product = request.getParameter("product");
            String subject = request.getParameter("subject");
            String message = request.getParameter("message");

            UserContextService.Client userClient = (new UserClient())
                    .getClient();

            if (userClient.saveUserCommunication(userId, email,
                    communicationType, orderId, awb, product, subject, message)) {
                log.info("User Communication saved successfully!");
            }

            // We need to have tickets for all data communication!
            log.info("Creating ticket!");
            Client crmServiceClient = new CRMClient().getClient();
            Ticket ticket = new Ticket();
            ticket.setAirwayBillNo(awb);
            ticket.setProductName(product);
            ticket.setCategory(TicketCategory
                    .findByValue((int) communicationType));
            ticket.setDescription("From: " + email + "\n\nSubject: " + subject + "\n\nBody: " + message);

            if (orderId != -1) {
                ticket.setOrderId(orderId);
            }

            ticket.setCreatorId(ADMIN_AGENT_ID);
            ticket.setPriority(TicketPriority.MEDIUM);
            ticket.setStatus(TicketStatus.OPEN);

            log.info("Creating activity!");
            Activity activity = new Activity();
            activity.setCreatorId(ADMIN_AGENT_ID);
            activity.setDescription("Ticket created");
            activity.setTicketCategory(ticket.getCategory());
            activity.setTicketDescription(ticket.getDescription());
            activity.setTicketPriority(ticket.getPriority());
            activity.setTicketStatus(ticket.getStatus());
            activity.setType(ActivityType.OTHER);

            if (isUserLoggedIn) {
                activity.setCustomerId(userId);
                ticket.setCustomerId(userId);
            } else {
                User user = userClient.getUserByEmail(email);
                if (user != null && user.getUserId() != -1) {
                    log.info("Found registered user for: " + email);
                    ticket.setCustomerId(user.getUserId());
                    activity.setCustomerId(user.getUserId());
                } else {
                    log.info("Setting customer email id to: " + email);
                    ticket.setCustomerEmailId(email);
                }
            }

            crmServiceClient.insertTicket(ticket, activity);
        } catch (NumberFormatException e) {
            log.error("Unable to get communication type or order id: ", e);
        } catch (TTransportException e) {
            log.error("Unable to initialize client: ", e);
        } catch (UserCommunicationException e) {
            log.error("Unable to get communication type or order id: ", e);
        } catch (TException e) {
            log.error("Thrift exception: ", e);
        } catch (UserContextException e) {
            log.error("Thrift exception: ", e);
        }
        return "success";
    }

    public String getId() {
        return this.id;
    }

    /**
     * @param id
     */
    public void setId(String id) {
        this.id = id;
    }

    public UserCommunicationType getFormType() {
        return this.formType;
    }

    public String getSuccessMsg() {
        return UserMessage.USER_COMMUNICATION_SUCCESS;
    }

    private String getOrderIdSelector(List<Long> order_ids) {
        StringBuilder html = new StringBuilder();

        if (order_ids == null || order_ids.size() == 0) {
            html.append("<option value='-1'>No Orders Found</option>");
        } else {
            html.append("<option value='-1'>Select Order ID</option>");

            for (long order_id : order_ids) {
                html.append("<option value='" + order_id + "'>" + order_id
                        + "</option>");
            }
        }
        return html.toString();
    }

    public String getProductsForOrder() {
        StringBuilder html = new StringBuilder();

        if (products == null || products.size() == 0) {
            html.append("<option value='-1'>No Products Found</option>");
        } else {
            for (LineItem product : products) {
                html.append("<option value='" + product.getId() + "'>");

                if (product.getBrand() != null)
                    html.append(product.getBrand() + " ");
                if (product.getModel_name() != null)
                    html.append(product.getModel_name() + " ");
                if (product.getModel_number() != null)
                    html.append(product.getModel_number());

                html.append("</option>");
            }
        }
        return html.toString();
    }

    public String getIdsOfAllOrders() {
        List<Long> order_ids = new ArrayList<Long>();

        for (Order order : this.orders) {
            order_ids.add(order.getId());
        }
        return getOrderIdSelector(order_ids);
    }

    public String getIdsOfReturnableOrders() {
        return getOrderIdSelector(this.order_ids);
    }

    public String getIdsOfCancellableOrders() {
        return getOrderIdSelector(this.order_ids);
    }
}