gt:         if (isValid()) {
context: /*
   * Copyright (C) 2018-2019 Prosystem Ingegneri Affiliati.
   *
   * This program is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Affero General Public License as
   * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
   *
   * You should have received a copy of the GNU Affero General Public License
   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
   */
  package com.prosystemingegneri.censistant.presentation.maintenance;
  
  import com.prosystemingegneri.censistant.business.customerSupplier.boundary.CustomerSupplierService;
  import com.prosystemingegneri.censistant.business.customerSupplier.entity.CustomerSupplier;
  import com.prosystemingegneri.censistant.business.customerSupplier.entity.Plant;
  import com.prosystemingegneri.censistant.business.maintenance.boundary.MaintenanceContractService;
  import com.prosystemingegneri.censistant.business.maintenance.boundary.MaintenanceTaskService;
  import com.prosystemingegneri.censistant.business.maintenance.control.MaintenanceType;
  import com.prosystemingegneri.censistant.business.maintenance.entity.ContractedSystem;
  import com.prosystemingegneri.censistant.business.maintenance.entity.InspectionDone;
  import com.prosystemingegneri.censistant.business.maintenance.entity.MaintenanceContract;
  import com.prosystemingegneri.censistant.business.maintenance.entity.MaintenancePlan;
  import com.prosystemingegneri.censistant.business.maintenance.entity.MaintenanceTask;
  import com.prosystemingegneri.censistant.business.maintenance.entity.Replacement;
  import com.prosystemingegneri.censistant.business.maintenance.entity.WorkingDuration;
  import com.prosystemingegneri.censistant.business.production.boundary.SystemService;
  import com.prosystemingegneri.censistant.business.production.entity.Device;
  import com.prosystemingegneri.censistant.business.production.entity.System;
  import com.prosystemingegneri.censistant.business.sales.entity.PlaceType;
  import com.prosystemingegneri.censistant.business.siteSurvey.entity.SystemType;
  import com.prosystemingegneri.censistant.business.siteSurvey.entity.Worker;
  import com.prosystemingegneri.censistant.business.warehouse.boundary.HandledItemService;
  import com.prosystemingegneri.censistant.business.warehouse.entity.HandledItem;
  import com.prosystemingegneri.censistant.presentation.ApplicationUrl;
  import com.prosystemingegneri.censistant.presentation.ExceptionUtility;
  import java.io.Serializable;
  import java.util.ArrayList;
  import java.util.Calendar;
  import java.util.GregorianCalendar;
  import java.util.HashMap;
  import java.util.List;
  import java.util.Locale;
  import java.util.Map;
  import javax.annotation.Resource;
  import javax.ejb.EJBException;
  import javax.faces.application.FacesMessage;
  import javax.faces.context.FacesContext;
  import javax.inject.Inject;
  import javax.inject.Named;
  import javax.mail.MessagingException;
  import javax.validation.ConstraintViolation;
  import javax.validation.Validator;
  import javax.validation.groups.Default;
  import net.sf.jasperreports.engine.JRException;
  import net.sf.jasperreports.engine.JRParameter;
  import net.sf.jasperreports.engine.JasperExportManager;
  import net.sf.jasperreports.engine.JasperFillManager;
  import net.sf.jasperreports.engine.JasperPrint;
  import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
  import org.omnifaces.cdi.ViewScoped;
  import org.omnifaces.util.Messages;
  import org.primefaces.event.SelectEvent;
  import org.primefaces.event.ToggleEvent;
  import org.primefaces.model.ByteArrayContent;
  import org.primefaces.model.StreamedContent;
  import org.primefaces.model.Visibility;
  
  
  /**
   *
   * @author Davide Mainardi <ingmainardi at live.com>
   */
  @Named
  @ViewScoped
  public class MaintenanceTaskPresenter implements Serializable{
      @Inject
      MaintenanceTaskService service;
      @Inject
      private ApplicationUrl applicationUrl;
      
      private MaintenanceTask maintenanceTask;
      private Long id;
      
      @Inject
      HandledItemService handledItemService;
      
      private List<CustomerSupplier> customers;
      private List<Plant> plants;
      @Inject
      private SystemService systemService;
      private List<System> systemsToBeAdded;
      private System systemToBeAdded;
      
      @Inject
      private MaintenanceContractService maintenanceContractService;
      private List<MaintenanceContract> unexpiredMaintenanceContracts;
      private MaintenanceContract unexpiredMaintenanceContract;
      
      private System system;
      private List<Device> importantDevices;
      
      @Resource
      Validator validator;
      
      //userful for creating a new job order and system
      @Inject
      private CustomerSupplierService customerSupplierService;
      private CustomerSupplier customer;
      private CustomerSupplier newCustomer;
      private Plant plant;
      private Plant newPlant;
      private SystemType systemType;
      private PlaceType placeType;
      private Worker seller;
      
      private void init() {
          customers = new ArrayList<>();
          plants = new ArrayList<>();
          maintenanceTask = (MaintenanceTask) FacesContext.getCurrentInstance().getExternalContext().getFlash().get("maintenanceTask");
      }
      
      private boolean isValid() {
          boolean isValidated = true;
          for (ConstraintViolation<MaintenanceTask> constraintViolation : validator.validate(maintenanceTask, Default.class)) {
              isValidated = false;
              FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", constraintViolation.getMessage()));
          }
          
          return isValidated;
      }
      
      public String saveMaintenanceTask() {
          try {
              if (!isValid())
                  return null;
              service.saveMaintenanceTask(maintenanceTask);
          } catch (EJBException e) {
              FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ExceptionUtility.unwrap(e.getCausedByException()).getLocalizedMessage()));
              return null;
          }
          
          Messages.create("success").detail("saved").flash().add();
          if (id == 0L)
              id = maintenanceTask.getId();
          
          return FacesContext.getCurrentInstance().getViewRoot().getViewId() + "?faces-redirect=true&includeViewParams=true";
      }
      
      public void detailMaintenanceTask() {
          init();
          if (maintenanceTask == null && id != null) {
              if (id == 0)
                  maintenanceTask = service.create();
              else
                  maintenanceTask = service.readMaintenanceTask(id);
          }
          if (maintenanceTask != null && (id == null || id > 0)) {
              system = maintenanceTask.getSystem();
              if (system == null)
                  system = maintenanceTask.getMaintenancePlan().getContractedSystem().getSystem();
              GregorianCalendar start = new GregorianCalendar();
              start.add(Calendar.MINUTE, -1);
              List<HandledItem> added = handledItemService.listHandledItems(0, 0, null, null, null, null, null, null, null, system, null, null, null, null, null, Boolean.FALSE, start, new GregorianCalendar());
              if (added != null)
                  for (HandledItem handledItem : added)
                      maintenanceTask.addReplacement(new Replacement(handledItem));
          }
          
          clearNewCustomer();
          clearNewPlant();
          updateImportantDevices();
      }
      
      public void clearCustomerSignature() {
          maintenanceTask.setCustomerSignature(null);
      }
  
      public Long getId() {
          return id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      public MaintenanceTask getMaintenanceTask() {
          return maintenanceTask;
      }
  
      public void setMaintenanceTask(MaintenanceTask maintenanceTask) {
          this.maintenanceTask = maintenanceTask;
      }
      
      public String calculateInspectionDoneResultColor(InspectionDone inspectionDone) {
          switch (inspectionDone.getInspectionResult()) {
              case OK:
                  return "green-row";
              case KO:
                  return "red-row";
              default:
                  return "";
          }
      }
      
      public void onNormalWorkingPanelToggle(ToggleEvent event) {
          if (event.getVisibility().equals(Visibility.VISIBLE))
              maintenanceTask.getTaskPrice().setNormalWorking(new WorkingDuration());
      }
      
      public void onOvertimeWorkingPanelToggle(ToggleEvent event) {
          if (event.getVisibility().equals(Visibility.VISIBLE))
              maintenanceTask.getTaskPrice().setOvertimeWorking(new WorkingDuration());
      }
      
      public void onTravelWorkingPanelToggle(ToggleEvent event) {
          if (event.getVisibility().equals(Visibility.VISIBLE))
              maintenanceTask.getTaskPrice().setTravelWorking(new WorkingDuration());
      }
      
      public void onSystemSelect(SelectEvent event) {
          System tempSystem = (System) event.getObject();
          if (tempSystem != null) {
              this.system = tempSystem;
              updateUnexpiredMaintenanceContracts();
          }
          updateImportantDevices();
      }
      
      public void onMaintenanceContractSelect(SelectEvent event) {
          MaintenanceContract maintenanceContract = (MaintenanceContract) event.getObject();
          if (maintenanceContract != null) {
              for (ContractedSystem contractedSystem : maintenanceContract.getContractedSystems()) {
                  if (contractedSystem.getSystem().equals(systemToBeAdded)) {
                      MaintenancePlan maintenancePlan = null;
                      for (MaintenancePlan maintenancePlan2 : contractedSystem.getMaintenancePlans())
                          if (maintenancePlan2.getMaintenanceType() == MaintenanceType.MAINTENANCE)
                              maintenancePlan = maintenancePlan2;
                      if (maintenancePlan == null) {
                          maintenancePlan = new MaintenancePlan(MaintenanceType.MAINTENANCE);
                          contractedSystem.addMaintenancePlan(maintenancePlan);
                      }
                      maintenanceTask.setSystem(null);
                      maintenanceTask.setMaintenancePlan(maintenancePlan);
                  }
              }
          }
          updateImportantDevices();
      }
      
      public void onHandledItemSelect(SelectEvent event) {
          HandledItem handledItem = (HandledItem) event.getObject();
          if (!maintenanceTask.isHandledItemPresent(handledItem))
              maintenanceTask.addReplacement(new Replacement(handledItem));
      }
      
      public void sendToWorkers() {
          if (isValid()) {
              try {
                  maintenanceTask = service.sendToWorker(maintenanceTask, applicationUrl.getApplicationUrl());
                  FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Success", "E-mail sent"));
              } catch (EJBException e) {
                  FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ExceptionUtility.unwrap(e.getCausedByException()).getLocalizedMessage()));
              } catch (MessagingException ex) {
                  FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", ExceptionUtility.unwrap(ex.getCause()).getLocalizedMessage()));
              }
          }
      }
      
      public StreamedContent print() {
  