com.redhat.rhtracking.web.controller.OpportunityController.java Source code

Java tutorial

Introduction

Here is the source code for com.redhat.rhtracking.web.controller.OpportunityController.java

Source

/*
 * Copyright (C) 2015 Nuuptech
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.redhat.rhtracking.web.controller;

import com.redhat.rhtracking.core.services.CustomerService;
import com.redhat.rhtracking.core.services.DeliveryMatrixService;
import com.redhat.rhtracking.core.services.DeliveryService;
import com.redhat.rhtracking.core.services.InvoiceService;
import com.redhat.rhtracking.events.EventStatus;
import static com.redhat.rhtracking.web.controller.Utils.getFlashMessagesList;
import static com.redhat.rhtracking.web.controller.Utils.getMessagesList;
import com.redhat.rhtracking.web.domain.DeliveryMatrixStatusInfo;
import com.redhat.rhtracking.web.domain.OneString;
import com.redhat.rhtracking.web.domain.OpportunityInfo;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 *
 * @author marco-g8
 */
@Controller
public class OpportunityController {

    private static final Logger logger = Logger.getLogger(OpportunityController.class);

    @Autowired
    private CustomerService customerService;
    @Autowired
    private InvoiceService invoiceService;
    @Autowired
    private DeliveryMatrixService deliveryMatrixService;
    @Autowired
    private DeliveryService deliveryService;

    @RequestMapping(value = "/opportunity/add", method = RequestMethod.GET)
    public String saveView(Model model) {
        Map<String, Object> customers = customerService.listAllCustomers();
        if (EventStatus.SUCCESS == (EventStatus) customers.get("status")) {
            model.addAttribute("customerList", customers.get("list"));
        }
        Map<String, Object> billing = customerService.listAllBillingCustomers();
        if (EventStatus.SUCCESS == (EventStatus) billing.get("status")) {
            model.addAttribute("billingList", billing.get("list"));
        }
        return "/opportunity/add";
    }

    @RequestMapping(value = "/opportunity/add", method = RequestMethod.POST)
    public String save(@Valid @ModelAttribute("opportunityInfo") OpportunityInfo opportunityInfo,
            BindingResult result, RedirectAttributes redirectAttributes, Model model, Principal principal) {
        List<String> messages = Utils.getFlashMessagesList(model, redirectAttributes);

        if (result.hasErrors()) {
            messages.add("warning::Los datos introducidos contienen errores.");
            messages.add("info::errors found " + result.getFieldErrors());
            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
            redirectAttributes.addFlashAttribute("opportunityInfo", opportunityInfo);
            return "redirect:/opportunity/add";
        }

        Map<String, Object> request = new HashMap<>();
        request.put("identifier", opportunityInfo.getId());
        request.put("project", opportunityInfo.getProject());
        request.put("opportunityType", opportunityInfo.getOpportunityType());
        request.put("customer", opportunityInfo.getCustomer());
        request.put("customerBilling", opportunityInfo.getCustomerBilling());
        //        request.put("startDate", opportunityInfo.getStartDate());
        //        request.put("endDate", opportunityInfo.getEndDate());
        request.put("currency", opportunityInfo.getCurrency());
        request.put("exchangeRate", opportunityInfo.getExchangeRate());

        request.put("platformHours", opportunityInfo.getPlatformHours());
        request.put("platformPrice", opportunityInfo.getPlatformPrice());
        request.put("middlewareHours", opportunityInfo.getMiddlewareHours());
        request.put("middlewarePrice", opportunityInfo.getMiddlewarePrice());
        request.put("workshopHours", opportunityInfo.getWorkshopHours());
        request.put("workshopPrice", opportunityInfo.getWorkshopPrice());

        Map<String, Object> response = deliveryMatrixService.saveOpportunity(request);
        switch ((EventStatus) response.get("status")) {
        case SUCCESS:
            messages.add("success::Oportunidad registrada.");
            return "redirect:/opportunity/show?id=" + opportunityInfo.getId();
        case DUPLICATED_KEY:
            messages.add("warning::Existe una oportinidad registrada con el id proporcionado");
            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
            redirectAttributes.addFlashAttribute("opportunityInfo", opportunityInfo);
            return "redirect:/opportunity/add";
        default:
            messages.add("error::Ocurrio una excepcion al registrar la oportunidad");
        }
        return "redirect:/opportunity/";
    }

    @RequestMapping(value = "/opportunity/find", method = RequestMethod.POST)
    public String find(@Valid @ModelAttribute("oneString") OneString oneString,
            @RequestParam(required = true) String by, BindingResult result, RedirectAttributes redirectAttributes,
            Model model, Principal principal) {
        List<String> messages = getFlashMessagesList(model, redirectAttributes);
        if (result.hasErrors()) {
            messages.add("warning::Error en el termino de busqueda");
            return "redirect:/opportunity/";
        }
        messages.add("info::Resultados para proyectos que contienen " + oneString.getValue());
        switch (by) {
        case "project":
            return "redirect:/opportunity/?sort=10&find=" + oneString.getValue();
        case "identifier":
            return "redirect:/opportunity/?sort=11&find=" + oneString.getValue();
        default:
            messages.add("error::Ocurrio un error al buscar");
            return "redirect:/opportunity/";
        }

    }

    /**
     * 
     * @param page
     * @param size
     * @param sort the column to find by
     *       0: default, by last created;
     *       1: id;
     *       2: project;
     *       3: customer;
     *       4: total hours;
     *       5: accrued hours.
     * @param asc 1: ascending order, descending otherwise
     * @param find
     * @param model
     * @return 
     */
    @RequestMapping(value = "/opportunity/", method = RequestMethod.GET)
    public String list(@RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "20") int size,
            @RequestParam(required = false, defaultValue = "0") int sort,
            @RequestParam(required = false, defaultValue = "0") int asc,
            @RequestParam(required = false, defaultValue = "") String find, Model model) {

        Map<String, Object> request = new HashMap<>();
        request.put("pageNumber", page - 1);
        request.put("pageSize", size > 9 ? size : 20);
        switch (sort) {
        case 1:
            request.put("sort", "identifier");
            break;
        case 2:
            request.put("sort", "project");
            break;
        case 3:
            request.put("sort", "customerName");
            break;
        case 4:
            request.put("sort", "totalHours");
            break;
        case 5:
            request.put("sort", "accruedHours");
            break;
        case 6:
            break;
        case 10:
            request.put("sort", "likeProject");
            request.put("like", find);
            break;
        case 11:
            request.put("sort", "likeIdentifier");
            request.put("like", find);
            break;
        }
        if (asc == 1)
            request.put("asc", true);
        Map<String, Object> response = deliveryMatrixService.listAllOpportunitiesPaged(request);

        if ((EventStatus) response.get("status") == EventStatus.SUCCESS) {
            model.addAttribute("asc", asc);
            model.addAttribute("sort", sort);
            model.addAllAttributes(response);
        } else
            getMessagesList(model).add("error::Ocurrio un error al obtener al procesar la solicitud");

        for (String key : response.keySet()) {
            if (key.equals("page"))
                continue;
            logger.debug(key + ": " + response.get(key));
        }
        return "/opportunity/list";
    }

    @RequestMapping(value = "/opportunity/show", method = RequestMethod.GET)
    public String show(@RequestParam(required = false, defaultValue = "1") String id,
            RedirectAttributes redirectAttributes, Model model) {
        List<String> messages = getFlashMessagesList(model, redirectAttributes);

        Map<String, Object> request = new HashMap<>();
        request.put("identifier", id);
        Map<String, Object> opportunity = deliveryMatrixService.findOpportunityBy(request);

        if ((EventStatus) opportunity.get("status") != EventStatus.SUCCESS) {
            messages.add("error::Oportunidad no encontrada");
            return "redirect:/opportunity/";
        }

        model.addAllAttributes(opportunity);
        request.put("id", (long) opportunity.get("id"));
        Map<String, Object> hours = deliveryMatrixService.findOpportunityHours(request);
        model.addAttribute("hours", hours.get("list"));

        if (!opportunity.containsKey("deliveryMatrix"))
            return "/opportunity/details";
        Map<String, Object> deliveryMatrix = (Map<String, Object>) opportunity.get("deliveryMatrix");
        model.addAttribute("delivery", deliveryMatrix);

        DeliveryMatrixStatusInfo dmsi = deliveryMatrixStatusInfo();
        dmsi.setDeliveryStatus((String) deliveryMatrix.get("deliveryStatus"));
        dmsi.setDeliverySubStatus((String) deliveryMatrix.get("deliverySubStatus"));
        dmsi.setDeliveryProbability((String) deliveryMatrix.get("deliveryProbability"));
        model.addAttribute("deliveryMatrixStatusInfo", dmsi);

        request.put("deliveryMatrixId", (long) deliveryMatrix.get("id"));
        Map<String, Object> list = invoiceService.listInvoicesFromDeliveryMatrix(request);
        model.addAttribute("invoices", list.get("list"));

        Map<String, Object> assigned = deliveryService.listAssignedConsultantsOfOpportunity(request);
        model.addAttribute("assignations", assigned.get("list"));

        return "/opportunity/details";
    }

    @ModelAttribute("opportunityInfo")
    public OpportunityInfo getOpportunityInfo() {
        return new OpportunityInfo();
    }

    @ModelAttribute("oneString")
    public OneString getOneString() {
        return new OneString();
    }

    @ModelAttribute("deliveryMatrixStatusInfo")
    public DeliveryMatrixStatusInfo deliveryMatrixStatusInfo() {
        return new DeliveryMatrixStatusInfo();
    }

}