Subversion Repositories SmartDukaan

Rev

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

/**
 * 
 */
package in.shop2020.util;

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.user.User;
import in.shop2020.model.v1.user.UserContextException;
import in.shop2020.thrift.clients.CRMClient;
import in.shop2020.thrift.clients.UserClient;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;

/**
 * @author mandeep
 * 
 */
public class CRMEmailProcessor {
    private static final int DESCRIPTION_MAX_WIDTH = 2000;
    private static final Log log                   = LogFactory
                                                           .getLog(CRMEmailProcessor.class);
    private Client           client;

    public CRMEmailProcessor() {
        try {
            client = new CRMClient().getClient();
        } catch (TTransportException e) {
            log.error("Could not create client", e);
        }
    }

    public void processEmail(Message message) throws MessagingException,
            IOException, TException, UserContextException {
        Long ticketId = parseTicketId(message);

        if (ticketId != null) {
            log.info("Response for Ticket: " + ticketId + ": " + message);
            updateTicket(ticketId, message);
        } else {
            log.info("Mail not recognized as CRM ticket response with subject: "
                    + message.getSubject());
            log.info("Creating ticket for the same");
            createTicket(message);
        }
    }

    private Long parseTicketId(Message message) throws MessagingException {
        Long ticketId = null;
        String subject = message.getSubject();
        if (subject != null) {
            Pattern p = Pattern.compile("^.*"
                    + CRMConstants.CRM_SUBJECT_PREFIX_FOR_TICKET_ID
                    + "(\\d+).*$");
            Matcher m = p.matcher(subject);
            if (m.matches()) {
                ticketId = Long.parseLong(m.group(1));
            }
        }

        return ticketId;
    }

    public Date getLastProcessedTimestamp() throws ParseException, TException {
        return new Date(client.getLastEmailProcessedTimestamp());
    }

    public void updateLastProcessedTimestamp(Date date) throws TException {
        client.updateLastEmailProcessedTimestamp(date.getTime());
    }

    private void updateTicket(Long ticketId, Message message) {
        try {
            Ticket ticket = client.getTicket(ticketId);
            Activity activity = new Activity();
            activity.setTicketId(ticketId);
            activity.setTicketAssigneeId(ticket.getAssigneeId());
            activity.setTicketCategory(ticket.getCategory());
            activity.setTicketDescription(ticket.getDescription());
            activity.setTicketPriority(ticket.getPriority());
            activity.setTicketStatus(ticket.getStatus());
            activity.setType(ActivityType.RECEIVED_EMAIL_FROM_CUSTOMER);
            activity.setCreatorId(CRMConstants.ADMIN_AGENT_ID);

            if (ticket.isSetCustomerId()) {
                activity.setCustomerId(ticket.getCustomerId());
            }

            activity.setDescription(convertMessageToText(message));
            client.updateTicket(ticket, activity);
        } catch (TTransportException e) {
            log.error("Could not update ticket " + ticketId + " with mail "
                    + message, e);
        } catch (TException e) {
            log.error("Could not update ticket " + ticketId + " with mail "
                    + message, e);
        } catch (MessagingException e) {
            log.error("Could not update ticket " + ticketId + " with mail "
                    + message, e);
        } catch (IOException e) {
            log.error("Could not update ticket " + ticketId + " with mail "
                    + message, e);
        }
    }

    private void createTicket(Message message) throws MessagingException,
            IOException, TException, UserContextException {
        String description = convertMessageToText(message);
        Ticket ticket = new Ticket();
        ticket.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
        ticket.setCategory(TicketCategory.OTHER);
        String customerEmailId = parseEmailId(message.getFrom()[0].toString());

        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient()
                .getClient();
        User user = userClient.getUserByEmail(customerEmailId);

        if (user == null || user.getUserId() == -1) {
            ticket.setCustomerEmailId(customerEmailId);
        } else {
            ticket.setCustomerId(user.getUserId());
        }

        ticket.setDescription(description);
        ticket.setPriority(TicketPriority.MEDIUM);
        ticket.setStatus(TicketStatus.OPEN);

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

        client.insertTicket(ticket, activity);
    }

    // parsing email Id from strings like
    // Pankaj Jain <ponkoj@hotmail.com>
    private String parseEmailId(String address) {
        Pattern p = Pattern.compile("^.*<(.+)>.*$");
        Matcher m = p.matcher(address);
        if (m.matches()) {
            address = m.group(1);
        }

        return address;
    }

    private String convertMessageToText(Message message)
            throws MessagingException, IOException {
        String messageContent = "";

        if (message.getContent() instanceof String) {
            messageContent = message.getContent().toString();
        } else if (message.getContent() instanceof MimeMultipart) {
            MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
            if (mimeMultipart.getCount() > 0) {
                messageContent = mimeMultipart.getBodyPart(0).getContent()
                        .toString();
            }
        } else {
            log.error("Could not read message content: " + message.getContent());
        }

        String content = "From: " + message.getFrom()[0].toString() + "\n\nSubject: "
                + message.getSubject() + "\n\nBody: " + messageContent;
        if (content.length() > DESCRIPTION_MAX_WIDTH) {
            content = content.substring(0, DESCRIPTION_MAX_WIDTH);
        }

        return content;
    }
}