Subversion Repositories SmartDukaan

Rev

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

/**
 * 
 */
package in.shop2020.crm.service.handler;

import in.shop2020.alert.AlertService;
import in.shop2020.alert.EntityType;
import in.shop2020.alert.MonitoredEntity;
import in.shop2020.config.ConfigException;
import in.shop2020.crm.Activity;
import in.shop2020.crm.ActivityType;
import in.shop2020.crm.Agent;
import in.shop2020.crm.TicketStatus;
import in.shop2020.crm.CRMService.Iface;
import in.shop2020.crm.SearchFilter;
import in.shop2020.crm.Ticket;
import in.shop2020.crm.TicketCategory;
import in.shop2020.crm.handler.ActivityHandler;
import in.shop2020.crm.handler.AgentHandler;
import in.shop2020.crm.handler.TicketHandler;
import in.shop2020.serving.model.ShipmentUpdate;
import in.shop2020.serving.services.FedExTrackingService;
import in.shop2020.thrift.clients.AlertClient;
import in.shop2020.thrift.clients.TransactionClient;
import in.shop2020.thrift.clients.config.ConfigClient;
import in.shop2020.model.v1.order.Order;
import in.shop2020.model.v1.order.TransactionServiceException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.thrift.TException;
import org.apache.thrift.transport.TTransportException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Implementation of the interface/services exposed by thrift to clients!
 * 
 * @author mandeep
 */
@Service
public class CRMServiceHandler implements Iface {
    private static final Log log = LogFactory.getLog(CRMServiceHandler.class);

    private TicketHandler      ticketHandler;
    private ActivityHandler    activityHandler;
    private AgentHandler       agentHandler;
    private FedExTrackingService fedexTrackClient = new FedExTrackingService();

    public CRMServiceHandler() {
        log.info("Creating context");
        ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        ticketHandler              = context.getBean(TicketHandler.class);
        activityHandler            = context.getBean(ActivityHandler.class);
        agentHandler               = context.getBean(AgentHandler.class);
    }

    public List<Ticket> getTickets(SearchFilter searchFilter) throws TException {
        List<Ticket> ttickets = new ArrayList<Ticket>();
        for (in.shop2020.crm.domain.Ticket ticket : ticketHandler
                .getTickets(in.shop2020.crm.domain.SearchFilter
                        .create(searchFilter))) {
            ttickets.add(ticket.getThriftTicket());
        }

        return ttickets;
    }

    public List<Ticket> getUnassignedTickets() throws TException {
        List<Ticket> tickets = new ArrayList<Ticket>();

        for (in.shop2020.crm.domain.Ticket ticket : ticketHandler
                .getUnassignedTickets()) {
            tickets.add(ticket.getThriftTicket());
        }

        return tickets;
    }

    @Transactional
    public void updateTicket(Ticket ticket, Activity activity)
            throws TException {
        try {
            ticketHandler.updateTicket(in.shop2020.crm.domain.Ticket
                    .create(ticket));
            activity.setTicketId(ticket.getId());
            activityHandler.insertActivity(in.shop2020.crm.domain.Activity
                    .create(activity));
            try{
                    /*For now monitoring is only done for New tickets and hence once any 
                         * activity is done on a ticket after its creation, we stop monitoring that ticket*/
                if(activity.getType()== ActivityType.SEND_EMAIL_TO_CUSTOMER || 
                                activity.getType()== ActivityType.ESCALATE_TICKET ||
                                activity.getType()== ActivityType.CALLED_CUSTOMER || 
                                activity.getTicketStatus().equals(TicketStatus.CLOSED)) {
                                AlertService.Client alertClient = new AlertClient().getClient();
                            alertClient.endMonitoringEntity(EntityType.TICKET, "ticketId = " + ticket.getId());
                }
            } catch(Exception ex) {
                log.error("Exception while ending monitoring for ticketId " + ticket.getId());
                log.error(ex);
            }
        } catch (ParseException e) {
            throw new TException("Could not update " + ticket, e);
        }
    }

    @Transactional
    public long insertTicket(Ticket ticket, Activity activity)
            throws TException {
        try {
            long ticketId = ticketHandler
                    .insertTicket(in.shop2020.crm.domain.Ticket.create(ticket));
            activity.setTicketId(ticketId);
            activityHandler.insertActivity(in.shop2020.crm.domain.Activity
                    .create(activity));
            try {
                if(ticket.getCategory()!= TicketCategory.DELIVERY_PROBLEM &&
                                ticket.getCategory()!= TicketCategory.PRODUCT_PROCUREMENT &&
                                ticket.getCategory()!= TicketCategory.DOA_RECEIVED) {
                            MonitoredEntity entity = new MonitoredEntity();
                            entity.setEntityType(EntityType.TICKET);
                            entity.setEventType(0);
                            entity.setEntityIdentifier("ticketId = " + new Long(ticketId).toString());
                            entity.setDescription(ticket.getDescription());
                            Calendar thresholdTime = Calendar.getInstance();
                            thresholdTime.add(Calendar.HOUR, 4);
                            entity.setWarnExpiryTime(thresholdTime.getTimeInMillis());
                            thresholdTime.add(Calendar.HOUR, 2);
                            entity.setCriticalExpiryTime(thresholdTime.getTimeInMillis());
                            AlertService.Client alertClient = new AlertClient().getClient();
                            alertClient.scheduleAlert(entity);
                }
            } catch (Exception ex) {
                log.error("Exception while scheduling alert for Ticket Id "+ticketId);
                log.error(ex);
            }
            return ticketId;
        } catch (ParseException e) {
            throw new TException("Could not insert " + ticket, e);
        }
    }

    public List<Activity> getActivities(SearchFilter searchFilter)
            throws TException {
        List<Activity> tactivities = new ArrayList<Activity>();
        //Start:- Added By Manish Sharma for Displaying Current Ticket Status for Unread Customer Activities on 21-Jun-2013
        in.shop2020.crm.domain.SearchFilter filter_to_check  =in.shop2020.crm.domain.SearchFilter.create(searchFilter);
        List<in.shop2020.crm.domain.Activity> activities = activityHandler
                .getActivities(filter_to_check);
        in.shop2020.crm.domain.SearchFilter new_searchFilter = new in.shop2020.crm.domain.SearchFilter();
        //End:- Added By Manish Sharma for Displaying Current Ticket Status for Unread Customer Activities on 21-Jun-2013
        
        if (activities != null) {
            for (in.shop2020.crm.domain.Activity ticket : activities) {
                //Start:- Added By Manish Sharma for Displaying Current Ticket Status for Unread Customer Activities on 21-Jun-2013
                in.shop2020.crm.Activity activity = ticket.getThriftActivity();
                if(filter_to_check.getIsActivityRead()!=null && !filter_to_check.getIsActivityRead()){
                        if(activity.getTicketId() > 0){
                                new_searchFilter.setTicketId(activity.getTicketId());
                                List<in.shop2020.crm.domain.Ticket> tickets_as_per_activity= ticketHandler.getTickets(new_searchFilter);
                                activity.setTicketStatus(tickets_as_per_activity.get(0).getStatus());
                            }
                }
                tactivities.add(activity);
                //End:- Added By Manish Sharma for Displaying Current Ticket Status for Unread Customer Activities on 21-Jun-2013
            }
        }

        return tactivities;
    }

    public long insertActivity(Activity activity) throws TException {
        try {
            return activityHandler.insertActivity(in.shop2020.crm.domain.Activity
                    .create(activity));
        } catch (ParseException e) {
            throw new TException("Could not insert " + activity, e);
        }
    }

    @Transactional
    public void markAsRead(long activityId, long agentId) throws TException {
        in.shop2020.crm.domain.SearchFilter searchFilter = new in.shop2020.crm.domain.SearchFilter();
        searchFilter.setActivityId(activityId);
        activityHandler.markAsRead(activityId);
        in.shop2020.crm.domain.Activity activity = activityHandler
                .getActivities(searchFilter).get(0);

        // Setting activity fields from latest ticket fields
        if (activity.getTicketId() != null) {
            searchFilter.setTicketId(activity.getTicketId());
            in.shop2020.crm.domain.Ticket ticket = ticketHandler.getTickets(searchFilter).get(0);
            activity.setTicketAssigneeId(ticket.getAssigneeId());
            activity.setTicketCategory(ticket.getCategory());
            activity.setTicketDescription(ticket.getDescription());
            activity.setTicketPriority(ticket.getPriority());
            activity.setTicketStatus(ticket.getStatus());
        }

        activity.setCreatorId(agentId);
        activity.setDescription("Marked as read ticketId: "
                + activity.getTicketId() + ", activityId: " + activityId);
        activity.setType(ActivityType.OTHER);
        activityHandler.insertActivity(activity);
    }

    public List<Agent> getAgents(SearchFilter searchFilter) throws TException {
        List<Agent> agents = new ArrayList<Agent>();

        for (in.shop2020.crm.domain.Agent agent : agentHandler
                .getAgents(in.shop2020.crm.domain.SearchFilter
                        .create(searchFilter))) {
            agents.add(agent.getThriftAgent());
        }

        return agents;
    }
    
    public List<Agent> getInactiveAgents(SearchFilter searchFilter) throws TException {
        List<Agent> agents = new ArrayList<Agent>();

        for (in.shop2020.crm.domain.Agent agent : agentHandler
                .getInactiveAgents(in.shop2020.crm.domain.SearchFilter
                        .create(searchFilter))) {
            agents.add(agent.getThriftAgent());
        }

        return agents;
    }

    public void updatePasswordForAgent(String agentEmailId, String password)
            throws TException {
        agentHandler.updatePasswordForAgent(agentEmailId, password);
    }

    public long getLastEmailProcessedTimestamp() throws TException {
        return agentHandler.getLastEmailProcessedTimestamp().getTime();
    }

    public void updateLastEmailProcessedTimestamp(long timestamp)
            throws TException {
        agentHandler.updateLastEmailProcessedTimestamp(new Date(timestamp));
    }

    public List<String> getRoleNamesForAgent(String agentEmailId)
            throws TException {
        return agentHandler.getRoleNamesForAgent(agentEmailId);
    }

    public List<String> getPermissionsForRoleName(String roleName)
            throws TException {
        return agentHandler.getPermissionsForRoleName(roleName);
    }
    
    public void changeAgentStatus(boolean status, String emailId)
                throws TException {
        agentHandler.changeAgentStatus(status, emailId);
    }

        public boolean isAlive() throws TException {
        try {
            return !agentHandler.getAgents(null).isEmpty();
        } catch (Exception e) {
            log.error("Could not fetch agents", e);
        }

        return false;
    }

        public void closeSession() throws TException {
        }
        
        public void insertAgent(Agent agent, List<String> role) throws TException {
                agentHandler.insertAgent(in.shop2020.crm.domain.Agent.create(agent), role);
        }
        
        public void unassignAgentTickets(int assigneeId) {
                ticketHandler.unassignAgentTickets(assigneeId);
        }
        
        public void changeAgentRole(long id, List<String> role) {
                agentHandler.changeAgentRole(id,role);
        }
        
        public int getOpenTicketCountForAgent(long agentId) {
                return ticketHandler.getOpenTicketCountForAgent(agentId);
        }
        
        public Map<String,Long> getOpenTicketsMap() {
                return ticketHandler.getOpenTicketsMap();
        }
        

        public Map<String, String> getFedexReconciliationDataMap(
                        List<Long> order_ids, String method_key) {
                log.info("Into Method of CRM Service to get Fedex Reconciliation Data");
                Map<String, String> fedexReconciliationDataMap = null;
                try{
                        TransactionClient transactionServiceClient = new TransactionClient();
                        List<Order> orderList= transactionServiceClient.getClient().getOrderList(order_ids);
                        if("delivered_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExDeliveredOrdersMap(orderList);
                        }
                        if("returned_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExReturnedOrdersMap(orderList);
                        }
                        if("undelivered_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExUnDeliveredOrdersMap(orderList);
                        }
                        if("first_delivery_attempted_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExFirstDeliveryAttemptedOrdersMap(orderList);
                        }
                        if("destination_city_reached_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExReachedDestinationOrdersMap(orderList);
                        }
                        if("picked_up_orders".equalsIgnoreCase(method_key) || "local_connection_orders".equalsIgnoreCase(method_key)){
                                fedexReconciliationDataMap = fedexTrackClient.readFedExPickupOrdersMap(orderList);
                        }
                // TODO Auto-generated method stub
                }
                catch (TTransportException e) {
                        log.error("Unable to create thrift Client from fedex reconciliation method.... ", e);
                } catch (TException e) {
                        log.error("Unable to get thrift Client from fedex reconciliation method.... ", e);
                }
                log.info("Into Method of CRM Service to get Fedex Reconciliation Data....and got it successfully");
                return fedexReconciliationDataMap;
        }
 }