Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.serving.controllers;

import in.shop2020.crm.TicketCategory;
import in.shop2020.model.v1.order.LineItem;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.TransactionServiceException;
import in.shop2020.model.v1.user.UserCommunicationException;
import in.shop2020.model.v1.user.UserCommunicationType;
import in.shop2020.model.v1.user.UserContextService;
import in.shop2020.serving.utils.UserMessage;
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.commons.lang.StringUtils;
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 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"));

            TicketCategory ticketCategory = TicketCategory.findByValue((int) communicationType);
            
            // Validating ticket category to avoid cases where someone tries to programmatically
            // send requests to us with invalid communication types
            if (ticketCategory != null) {
                if (request.getParameter("order_id") != null) {
                    orderId = Integer.parseInt(request.getParameter("order_id"));
                }
                if (StringUtils.isNotEmpty(request.getParameter("rechargeOrderNumber"))) {
                        //Valid recharge formats are:
                        //MOBR9999
                        //99999
                        String []strOrder = request.getParameter("rechargeOrderNumber").split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
                        if(strOrder.length==2) {
                                orderId = Integer.parseInt(strOrder[1]);
                        } else {
                                orderId = Integer.parseInt(strOrder[0]);
                        }
                }
                

                String awb = request.getParameter("awb");
                if(StringUtils.isEmpty(awb)){
                        awb = request.getParameter("deviceNumber");
                }
                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 change status for the given order to
                 * CANCELLATION_REQUEST_RECIEVED
                 */
                if(communicationType == 2) {
                    in.shop2020.model.v1.order.TransactionService.Client transactionClient = 
                        (new TransactionClient()).getClient();
                    transactionClient.markOrderCancellationRequestReceived(orderId);
                }
            }
        } 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 (TransactionServiceException e) {
            log.error("Unable to mark cancellation request recieved", 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);
    }
}