Resolve some TODO`s.

Code refactoring.
This commit is contained in:
Vova Perebykivskyi 2016-10-31 16:49:57 +02:00 committed by Dgray16
parent fd19610a40
commit 35ccbec0ac
40 changed files with 1152 additions and 1403 deletions

View file

@ -50,8 +50,8 @@ public class I18nHelper {
} }
//TODO It should be changed since JDK9.
/** /**
* TODO It should be changed since JDK9
* Use of '_' as an identifier might not be supported in releases after Java SE 8. * Use of '_' as an identifier might not be supported in releases after Java SE 8.
* *
* @param str * @param str

View file

@ -36,19 +36,6 @@ import org.libreplan.business.planner.entities.consolidations.NonCalculatedConso
public class AdvanceMeasurement extends BaseEntity { public class AdvanceMeasurement extends BaseEntity {
public static AdvanceMeasurement create(LocalDate date, BigDecimal value) {
AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(date,
value);
advanceMeasurement.setNewObject(true);
return advanceMeasurement;
}
public static AdvanceMeasurement create() {
AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement();
advanceMeasurement.setNewObject(true);
return advanceMeasurement;
}
private LocalDate date; private LocalDate date;
private BigDecimal value; private BigDecimal value;
@ -58,7 +45,7 @@ public class AdvanceMeasurement extends BaseEntity {
private Date communicationDate; private Date communicationDate;
@Valid @Valid
private Set<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues = new HashSet<NonCalculatedConsolidatedValue>(); private Set<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues = new HashSet<>();
public AdvanceMeasurement() { public AdvanceMeasurement() {
} }
@ -71,9 +58,20 @@ public class AdvanceMeasurement extends BaseEntity {
} }
} }
public static AdvanceMeasurement create(LocalDate date, BigDecimal value) {
AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement(date, value);
advanceMeasurement.setNewObject(true);
return advanceMeasurement;
}
public static AdvanceMeasurement create() {
AdvanceMeasurement advanceMeasurement = new AdvanceMeasurement();
advanceMeasurement.setNewObject(true);
return advanceMeasurement;
}
public void setDate(LocalDate date) { public void setDate(LocalDate date) {
if ((date != null) && (this.date != null) if ((date != null) && (this.date != null) && (this.date.compareTo(date) != 0)) {
&& (this.date.compareTo(date) != 0)) {
resetCommunicationDate(); resetCommunicationDate();
} }
this.date = date; this.date = date;
@ -89,13 +87,13 @@ public class AdvanceMeasurement extends BaseEntity {
if (value != null) { if (value != null) {
this.value.setScale(2, BigDecimal.ROUND_DOWN); this.value.setScale(2, BigDecimal.ROUND_DOWN);
} }
if ((this.value != null) && (value != null)
&& (this.value.compareTo(value) != 0)) { if ((this.value != null) && (value != null) && (this.value.compareTo(value) != 0)) {
resetCommunicationDate(); resetCommunicationDate();
} }
if (advanceAssignment != null) { if (advanceAssignment != null) {
advanceAssignment.getOrderElement() advanceAssignment.getOrderElement().markAsDirtyLastAdvanceMeasurementForSpreading();
.markAsDirtyLastAdvanceMeasurementForSpreading();
} }
} }
@ -122,8 +120,8 @@ public class AdvanceMeasurement extends BaseEntity {
} }
/** /**
* Just set the communication date if it was <code>null</code>. Otherwise * Just set the communication date if it was <code>null</code>.
* keep the old value stored. * Otherwise keep the old value stored.
* *
* @param communicationDate * @param communicationDate
*/ */
@ -131,14 +129,13 @@ public class AdvanceMeasurement extends BaseEntity {
DirectAdvanceAssignment advanceAssignment = (DirectAdvanceAssignment) getAdvanceAssignment(); DirectAdvanceAssignment advanceAssignment = (DirectAdvanceAssignment) getAdvanceAssignment();
if (advanceAssignment.isFake()) { if (advanceAssignment.isFake()) {
OrderElement orderElement = advanceAssignment.getOrderElement(); OrderElement orderElement = advanceAssignment.getOrderElement();
Set<DirectAdvanceAssignment> directAdvanceAssignments = orderElement
.getAllDirectAdvanceAssignments(advanceAssignment Set<DirectAdvanceAssignment> directAdvanceAssignments =
.getAdvanceType()); orderElement.getAllDirectAdvanceAssignments(advanceAssignment.getAdvanceType());
for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) { for (DirectAdvanceAssignment directAdvanceAssignment : directAdvanceAssignments) {
for (AdvanceMeasurement advanceMeasurement : directAdvanceAssignment for (AdvanceMeasurement advanceMeasurement : directAdvanceAssignment.getAdvanceMeasurements()) {
.getAdvanceMeasurements()) { advanceMeasurement.updateCommunicationDate(communicationDate);
advanceMeasurement
.updateCommunicationDate(communicationDate);
} }
} }
} else { } else {
@ -159,32 +156,26 @@ public class AdvanceMeasurement extends BaseEntity {
} }
if (this.advanceAssignment instanceof DirectAdvanceAssignment) { if (this.advanceAssignment instanceof DirectAdvanceAssignment) {
BigDecimal defaultMaxValue = ((DirectAdvanceAssignment) this.advanceAssignment) BigDecimal defaultMaxValue = ((DirectAdvanceAssignment) this.advanceAssignment).getMaxValue();
.getMaxValue(); return this.value.compareTo(defaultMaxValue) <= 0;
return (this.value.compareTo(defaultMaxValue) <= 0);
} }
return true; return true;
} }
@AssertTrue(message = "The current value must be less than the max value.") @AssertTrue(message = "The current value must be less than the max value.")
public boolean isValidPrecisionConstraint() { public boolean isValidPrecisionConstraint() {
if ((this.value == null) || (this.advanceAssignment == null) if ((this.value == null) || (this.advanceAssignment == null) || (this.advanceAssignment.getAdvanceType() == null)) {
|| (this.advanceAssignment.getAdvanceType() == null)) {
return true; return true;
} }
BigDecimal precision = this.advanceAssignment.getAdvanceType() BigDecimal precision = this.advanceAssignment.getAdvanceType().getUnitPrecision();
.getUnitPrecision();
BigDecimal result[] = value.divideAndRemainder(precision); BigDecimal result[] = value.divideAndRemainder(precision);
BigDecimal zero = (BigDecimal.ZERO).setScale(4); BigDecimal zero = (BigDecimal.ZERO).setScale(4);
if (result[1].compareTo(zero) == 0) {
return true; return result[1].compareTo(zero) == 0;
}
return false;
} }
public void setNonCalculatedConsolidatedValues( public void setNonCalculatedConsolidatedValues(Set<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues) {
Set<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues) {
this.nonCalculatedConsolidatedValues = nonCalculatedConsolidatedValues; this.nonCalculatedConsolidatedValues = nonCalculatedConsolidatedValues;
} }

View file

@ -28,7 +28,6 @@ import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions; import org.hibernate.criterion.Restrictions;
import org.libreplan.business.common.IntegrationEntity; import org.libreplan.business.common.IntegrationEntity;
import org.libreplan.business.common.exceptions.InstanceNotFoundException; import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -39,18 +38,17 @@ import org.springframework.transaction.annotation.Transactional;
* @author Fernando Bellas Permuy <fbellas@udc.es> * @author Fernando Bellas Permuy <fbellas@udc.es>
*/ */
public class IntegrationEntityDAO<E extends IntegrationEntity> public class IntegrationEntityDAO<E extends IntegrationEntity>
extends GenericDAOHibernate<E, Long> implements IIntegrationEntityDAO<E> { extends GenericDAOHibernate<E, Long>
implements IIntegrationEntityDAO<E> {
@Override @Override
public boolean existsByCode(String code) { public boolean existsByCode(String code) {
try { try {
findByCode(code); findByCode(code);
return true; return true;
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
return false; return false;
} }
} }
@Override @Override
@ -64,17 +62,17 @@ public class IntegrationEntityDAO<E extends IntegrationEntity>
@Transactional(readOnly = true) @Transactional(readOnly = true)
public E findByCode(String code) throws InstanceNotFoundException { public E findByCode(String code) throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) { if (code == null || StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(null, throw new InstanceNotFoundException(null, getEntityClass().getName());
getEntityClass().getName());
} }
E entity = (E) getSession().createCriteria(getEntityClass()).add( E entity = (E) getSession()
Restrictions.eq("code", code.trim()).ignoreCase()).uniqueResult(); .createCriteria(getEntityClass())
.add(Restrictions.eq("code", code.trim()).ignoreCase())
.uniqueResult();
if (entity == null) { if (entity == null) {
throw new InstanceNotFoundException( throw new InstanceNotFoundException(code, getEntityClass().getName());
code, getEntityClass().getName());
} else { } else {
return entity; return entity;
} }
@ -83,22 +81,17 @@ public class IntegrationEntityDAO<E extends IntegrationEntity>
@Override @Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public E findByCodeAnotherTransaction(String code) public E findByCodeAnotherTransaction(String code) throws InstanceNotFoundException {
throws InstanceNotFoundException {
return findByCode(code); return findByCode(code);
} }
@Override @Override
public E findExistingEntityByCode(String code) { public E findExistingEntityByCode(String code) {
try { try {
return findByCode(code); return findByCode(code);
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View file

@ -80,6 +80,7 @@ import org.springframework.stereotype.Component;
/** /**
* @author Óscar González Fernández * @author Óscar González Fernández
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
@Component @Component
@Scope(BeanDefinition.SCOPE_SINGLETON) @Scope(BeanDefinition.SCOPE_SINGLETON)
@ -93,93 +94,131 @@ public class PredefinedDatabaseSnapshots {
@Autowired @Autowired
private ISnapshotRefresherService snapshotRefresherService; private ISnapshotRefresherService snapshotRefresherService;
@Autowired
private ICriterionTypeDAO criterionTypeDAO;
@Autowired
private ICriterionDAO criterionDAO;
@Autowired
private ILabelTypeDAO labelTypeDAO;
@Autowired
private ILabelDAO labelDAO;
@Autowired
private IWorkerDAO workerDAO;
@Autowired
private ICostCategoryDAO costCategoryDAO;
@Autowired
private IResourceDAO resourceDAO;
@Autowired
private IExternalCompanyDAO externalCompanyDAO;
@Autowired
private IOrderDAO orderDAO;
@Autowired
private IDayAssignmentDAO dayAssignmentDAO;
@Autowired
private IScenarioManager scenarioManager;
@Autowired
private IWorkReportLineDAO workReportLineDAO;
@Autowired
private ICostCalculator hoursCostCalculator;
@Autowired
private ITaskElementDAO taskElementDAO;
private IAutoUpdatedSnapshot<SortedMap<CriterionType, List<Criterion>>> criterionsMap; private IAutoUpdatedSnapshot<SortedMap<CriterionType, List<Criterion>>> criterionsMap;
private IAutoUpdatedSnapshot<Map<LabelType, List<Label>>> labelsMap;
private IAutoUpdatedSnapshot<List<Worker>> listWorkers;
private IAutoUpdatedSnapshot<List<CostCategory>> listCostCategories;
private IAutoUpdatedSnapshot<List<Criterion>> listCriterion;
private IAutoUpdatedSnapshot<Map<Class<?>, List<Resource>>> mapResources;
private IAutoUpdatedSnapshot<List<ExternalCompany>> externalCompanies;
private IAutoUpdatedSnapshot<List<String>> customerReferences;
private IAutoUpdatedSnapshot<List<String>> ordersCodes;
private IAutoUpdatedSnapshot<ResourceLoadChartData> resourceLoadChartData;
private IAutoUpdatedSnapshot<List<WorkReportLine>> workReportLines;
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>> estimatedCostPerTask;
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>> advanceCostPerTask;
private boolean snapshotsRegistered = false;
public SortedMap<CriterionType, List<Criterion>> snapshotCriterionsMap() { public SortedMap<CriterionType, List<Criterion>> snapshotCriterionsMap() {
return criterionsMap.getValue(); return criterionsMap.getValue();
} }
private IAutoUpdatedSnapshot<Map<LabelType, List<Label>>> labelsMap;
public Map<LabelType, List<Label>> snapshotLabelsMap() { public Map<LabelType, List<Label>> snapshotLabelsMap() {
return labelsMap.getValue(); return labelsMap.getValue();
} }
private IAutoUpdatedSnapshot<List<Worker>> listWorkers;
public List<Worker> snapshotListWorkers() { public List<Worker> snapshotListWorkers() {
return listWorkers.getValue(); return listWorkers.getValue();
} }
private IAutoUpdatedSnapshot<List<CostCategory>> listCostCategories;
public List<CostCategory> snapshotListCostCategories() { public List<CostCategory> snapshotListCostCategories() {
return listCostCategories.getValue(); return listCostCategories.getValue();
} }
private IAutoUpdatedSnapshot<List<Criterion>> listCriterion;
public List<Criterion> snapshotListCriterion() { public List<Criterion> snapshotListCriterion() {
return listCriterion.getValue(); return listCriterion.getValue();
} }
private IAutoUpdatedSnapshot<Map<Class<?>, List<Resource>>> mapResources;
public Map<Class<?>, List<Resource>> snapshotMapResources() { public Map<Class<?>, List<Resource>> snapshotMapResources() {
return mapResources.getValue(); return mapResources.getValue();
} }
private IAutoUpdatedSnapshot<List<ExternalCompany>> externalCompanies;
public List<ExternalCompany> snapshotExternalCompanies() { public List<ExternalCompany> snapshotExternalCompanies() {
return externalCompanies.getValue(); return externalCompanies.getValue();
} }
private IAutoUpdatedSnapshot<List<String>> customerReferences;
public List<String> snapshotCustomerReferences() { public List<String> snapshotCustomerReferences() {
return customerReferences.getValue(); return customerReferences.getValue();
} }
private IAutoUpdatedSnapshot<List<String>> ordersCodes;
public List<String> snapshotOrdersCodes() { public List<String> snapshotOrdersCodes() {
return ordersCodes.getValue(); return ordersCodes.getValue();
} }
private IAutoUpdatedSnapshot<ResourceLoadChartData>
resourceLoadChartData;
public ResourceLoadChartData snapshotResourceLoadChartData() { public ResourceLoadChartData snapshotResourceLoadChartData() {
return resourceLoadChartData.getValue(); return resourceLoadChartData.getValue();
} }
private IAutoUpdatedSnapshot<List<WorkReportLine>> workReportLines;
public List<WorkReportLine> snapshotWorkReportLines() { public List<WorkReportLine> snapshotWorkReportLines() {
return workReportLines.getValue(); return workReportLines.getValue();
} }
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>>
estimatedCostPerTask;
public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> snapshotEstimatedCostPerTask() { public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> snapshotEstimatedCostPerTask() {
return estimatedCostPerTask.getValue(); return estimatedCostPerTask.getValue();
} }
private IAutoUpdatedSnapshot<Map<TaskElement,SortedMap<LocalDate, BigDecimal>>>
advanceCostPerTask;
public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> snapshotAdvanceCostPerTask() { public Map<TaskElement,SortedMap<LocalDate, BigDecimal>> snapshotAdvanceCostPerTask() {
return advanceCostPerTask.getValue(); return advanceCostPerTask.getValue();
} }
private boolean snapshotsRegistered = false;
public void registerSnapshots() { public void registerSnapshots() {
if ( snapshotsRegistered ) { if ( snapshotsRegistered ) {
LOG.warn("snapshots have already been registered"); LOG.warn("snapshots have already been registered");
return; return;
} }
@ -242,12 +281,6 @@ public class PredefinedDatabaseSnapshots {
return AdHocTransactionService.readOnlyProxy(transactionService, Callable.class, callable); return AdHocTransactionService.readOnlyProxy(transactionService, Callable.class, callable);
} }
@Autowired
private ICriterionTypeDAO criterionTypeDAO;
@Autowired
private ICriterionDAO criterionDAO;
private Callable<SortedMap<CriterionType, List<Criterion>>> calculateCriterionsMap() { private Callable<SortedMap<CriterionType, List<Criterion>>> calculateCriterionsMap() {
return () -> { return () -> {
SortedMap<CriterionType, List<Criterion>> result = new TreeMap<>(getComparatorByName()); SortedMap<CriterionType, List<Criterion>> result = new TreeMap<>(getComparatorByName());
@ -262,15 +295,9 @@ public class PredefinedDatabaseSnapshots {
} }
private Comparator<CriterionType> getComparatorByName(){ private Comparator<CriterionType> getComparatorByName(){
return (arg0, arg1) -> (arg0.getName().compareTo(arg1.getName())); return (arg0, arg1) -> arg0.getName().compareTo(arg1.getName());
} }
@Autowired
private ILabelTypeDAO labelTypeDAO;
@Autowired
private ILabelDAO labelDAO;
private Callable<Map<LabelType, List<Label>>> calculateLabelsMap() { private Callable<Map<LabelType, List<Label>>> calculateLabelsMap() {
return () -> { return () -> {
Map<LabelType, List<Label>> result = new HashMap<>(); Map<LabelType, List<Label>> result = new HashMap<>();
@ -282,15 +309,13 @@ public class PredefinedDatabaseSnapshots {
}; };
} }
@Autowired
private IWorkerDAO workerDAO;
private Callable<List<Worker>> calculateWorkers() { private Callable<List<Worker>> calculateWorkers() {
return () -> workerDAO.getAll(); return () -> workerDAO.getAll();
} }
@Autowired
private ICostCategoryDAO costCategoryDAO;
private Callable<List<CostCategory>> calculateListCostCategories() { private Callable<List<CostCategory>> calculateListCostCategories() {
return () -> costCategoryDAO.findActive(); return () -> costCategoryDAO.findActive();
@ -300,9 +325,6 @@ public class PredefinedDatabaseSnapshots {
return criterionDAO::getAll; return criterionDAO::getAll;
} }
@Autowired
private IResourceDAO resourceDAO;
private Callable<Map<Class<?>, List<Resource>>> calculateMapResources() { private Callable<Map<Class<?>, List<Resource>>> calculateMapResources() {
return () -> { return () -> {
Map<Class<?>, List<Resource>> result = new HashMap<>(); Map<Class<?>, List<Resource>> result = new HashMap<>();
@ -314,26 +336,16 @@ public class PredefinedDatabaseSnapshots {
}; };
} }
@Autowired
private IExternalCompanyDAO externalCompanyDAO;
private Callable<List<ExternalCompany>> calculateExternalCompanies() { private Callable<List<ExternalCompany>> calculateExternalCompanies() {
return () -> externalCompanyDAO.getExternalCompaniesAreClient(); return () -> externalCompanyDAO.getExternalCompaniesAreClient();
} }
@Autowired
private IOrderDAO orderDAO;
private Callable<List<String>> calculateCustomerReferences() { private Callable<List<String>> calculateCustomerReferences() {
return () -> { return () -> {
// FIXME replace by a HQL query, for god's sake!
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
for (Order order : orderDAO.getOrders()) { for (Order order : orderDAO.getOrdersWithNotEmptyCustomersReferences()) {
if ( (order.getCustomerReference() != null) && (!order.getCustomerReference().isEmpty()) ) {
result.add(order.getCustomerReference()); result.add(order.getCustomerReference());
} }
}
return result; return result;
}; };
} }
@ -348,40 +360,29 @@ public class PredefinedDatabaseSnapshots {
}; };
} }
@Autowired
private IDayAssignmentDAO dayAssignmentDAO;
@Autowired
private IScenarioManager scenarioManager;
private Callable<ResourceLoadChartData> calculateResourceLoadChartData() { private Callable<ResourceLoadChartData> calculateResourceLoadChartData() {
return () -> { return () -> {
List<DayAssignment> dayAssignments = dayAssignmentDAO.getAllFor(scenarioManager.getCurrent(), null, null); List<DayAssignment> dayAssignments = dayAssignmentDAO.getAllFor(scenarioManager.getCurrent(), null, null);
List<Resource> resources = resourceDAO.list(Resource.class); List<Resource> resources = resourceDAO.list(Resource.class);
return new ResourceLoadChartData(dayAssignments, resources); return new ResourceLoadChartData(dayAssignments, resources);
}; };
} }
@Autowired
private IWorkReportLineDAO workReportLineDAO;
private Callable<List<WorkReportLine>> calculateWorkReportLines() { private Callable<List<WorkReportLine>> calculateWorkReportLines() {
return () -> workReportLineDAO.list(WorkReportLine.class); return () -> workReportLineDAO.list(WorkReportLine.class);
} }
@Autowired
private ICostCalculator hoursCostCalculator;
@Autowired
private ITaskElementDAO taskElementDAO;
private Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>> calculateEstimatedCostPerTask() { private Callable<Map<TaskElement, SortedMap<LocalDate, BigDecimal>>> calculateEstimatedCostPerTask() {
return () -> { return () -> {
Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map = new HashMap<>(); Map<TaskElement, SortedMap<LocalDate, BigDecimal>> map = new HashMap<>();
taskElementDAO.list(TaskElement.class).stream().filter(task -> task instanceof Task) taskElementDAO.
list(TaskElement.class)
.stream()
.filter(task -> task instanceof Task)
.forEach(task -> map.put(task, hoursCostCalculator.getEstimatedCost((Task) task))); .forEach(task -> map.put(task, hoursCostCalculator.getEstimatedCost((Task) task)));
return map; return map;

View file

@ -24,20 +24,21 @@ package org.libreplan.business.i18n;
/** /**
* This class provides a function to mark strings to be translated. * This class provides a function to mark strings to be translated.
* Real translation have to be done in webapp module depending on user language and * Real translation have to be done in webapp module depending on user language and not done here depending on server language.
* not done here depending on server language.
* *
* @author Manuel Rego Casasnovas <rego@igalia.com> * @author Manuel Rego Casasnovas <rego@igalia.com>
*/ */
public class I18nHelper { public class I18nHelper {
private I18nHelper() {} private I18nHelper() {
}
//TODO It should be changed since JDK9.
/** /**
* TODO It should be changed since JDK9
*
* Use of '_' as an identifier might not be supported in releases after Java SE 8. * Use of '_' as an identifier might not be supported in releases after Java SE 8.
* *
* @param str * @param text
* @return Text depends on locale * @return Text depends on locale
*/ */
public static String _(String text) { public static String _(String text) {

View file

@ -39,48 +39,49 @@ import org.libreplan.business.scenarios.entities.Scenario;
import org.libreplan.business.users.entities.User; import org.libreplan.business.users.entities.User;
/** /**
* Contract for {@link OrderDAO} * Contract for {@link OrderDAO}.
*
* @author Óscar González Fernández <ogonzalez@igalia.com> * @author Óscar González Fernández <ogonzalez@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com> * @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
* @author Diego Pino Garcia <dpino@igalia.com> * @author Diego Pino Garcia <dpino@igalia.com>
* @author Jacobo Aragunde Pérez <jaragunde@igalia.com> * @author Jacobo Aragunde Pérez <jaragunde@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
public interface IOrderDAO extends IIntegrationEntityDAO<Order> { public interface IOrderDAO extends IIntegrationEntityDAO<Order> {
/** /**
* Gets all the orders. * Gets all the orders.
*
* @return A {@link List} of {@link Order} objects * @return A {@link List} of {@link Order} objects
*/ */
List<Order> getOrders(); List<Order> getOrders();
/** /**
* Builds contents for OrderCostsPerResource report * Builds contents for OrderCostsPerResource report.
* @return A {@link List} of {@link OrderCostsPerResourceDTO} objects for *
* reporting * @return A {@link List} of {@link OrderCostsPerResourceDTO} objects for reporting
*/ */
List<OrderCostsPerResourceDTO> getOrderCostsPerResource(List<Order> orders, List<OrderCostsPerResourceDTO> getOrderCostsPerResource(
Date startingDate, Date endingDate, List<Order> orders, Date startingDate, Date endingDate, List<Criterion> criterions);
List<Criterion> criterions);
/** /**
* Returns a list of orders filtered by the read authorizations of the indicated * Returns a list of orders filtered by the read authorizations of the indicated user.
* user. Write authorizations are also counted, because they implicitly suppose * Write authorizations are also counted, because they implicitly suppose read access.
* read access. *
* @param user User. * @param user User.
* @return Filtered list of orders. * @return Filtered list of orders.
*/ */
List<Order> getOrdersByReadAuthorization(User user); List<Order> getOrdersByReadAuthorization(User user);
/** /**
* Returns a list of orders filtered by the write authorizations of the indicated * Returns a list of orders filtered by the write authorizations of the indicated user.
* user. *
* @param user User. * @param user User.
* @return Filtered list of orders. * @return Filtered list of orders.
*/ */
List<Order> getOrdersByWriteAuthorization(User user); List<Order> getOrdersByWriteAuthorization(User user);
List<Order> getOrdersByReadAuthorizationByScenario(String username, List<Order> getOrdersByReadAuthorizationByScenario(String username, Scenario scenario);
Scenario scenario);
List<Order> getOrdersByReadAuthorizationBetweenDatesByLabelsCriteriaCustomerAndState( List<Order> getOrdersByReadAuthorizationBetweenDatesByLabelsCriteriaCustomerAndState(
String username, Scenario scenario, Date startDate, Date endDate, String username, Scenario scenario, Date startDate, Date endDate,
@ -88,30 +89,35 @@ public interface IOrderDAO extends IIntegrationEntityDAO<Order> {
ExternalCompany customer, OrderStatusEnum state); ExternalCompany customer, OrderStatusEnum state);
/** /**
* Returns the order filtered by the name. If name is blank (whitespace, * Returns the order filtered by the name.
* empty ("") or null, it throws <code>InstanceNotFoundException</code>. * If name is blank (whitespace, empty ("") or null, it throws <code>InstanceNotFoundException</code>.
*
* @param name * @param name
* String * String
* @return order Order * @return order Order
*/ */
public Order findByNameAnotherTransaction(String name) Order findByNameAnotherTransaction(String name) throws InstanceNotFoundException;
throws InstanceNotFoundException;
List<Order> getOrdersByScenario(Scenario scenario); List<Order> getOrdersByScenario(Scenario scenario);
List<Task> getFilteredTask(List<OrderElement> orderElements, List<Task> getFilteredTask(List<OrderElement> orderElements, List<Criterion> criterions);
List<Criterion> criterions);
public Order loadOrderAvoidingProxyFor(OrderElement orderElement); Order loadOrderAvoidingProxyFor(OrderElement orderElement);
public List<Order> loadOrdersAvoidingProxyFor( List<Order> loadOrdersAvoidingProxyFor(List<OrderElement> orderElement);
List<OrderElement> orderElement);
boolean existsByNameAnotherTransaction(String name); boolean existsByNameAnotherTransaction(String name);
List<Order> getActiveOrders(); List<Order> getActiveOrders();
List<CostExpenseSheetDTO> getCostExpenseSheet(List<Order> orders, Date startingDate, List<CostExpenseSheetDTO> getCostExpenseSheet(
Date endingDate, List<Criterion> criterions); List<Order> orders, Date startingDate, Date endingDate, List<Criterion> criterions);
/**
* Get {@link Order} where {@link Order#getCustomerReference()} is not NULL and not equals empty {@link String}.
*
* @return {@link List<Order>}
*/
List<Order> getOrdersWithNotEmptyCustomersReferences();
} }

View file

@ -172,7 +172,7 @@ public class OrderDAO extends IntegrationEntityDAO<Order> implements IOrderDAO {
// Apply filtering // Apply filtering
if (matchFilterCriterion(each.getOrderElement(), criterions) && isOrderContained(order, orders)) { if (matchFilterCriterion(each.getOrderElement(), criterions) && isOrderContained(order, orders)) {
// Attach ordername value // Attach orderName value
each.setOrderName(order.getName()); each.setOrderName(order.getName());
each.setOrderCode(order.getCode()); each.setOrderCode(order.getCode());
@ -455,14 +455,16 @@ public class OrderDAO extends IntegrationEntityDAO<Order> implements IOrderDAO {
* Otherwise, it returns the list of orders identifiers for which the user has read permissions. * Otherwise, it returns the list of orders identifiers for which the user has read permissions.
*/ */
private List<Long> getOrdersIdsByReadAuthorization(User user) { private List<Long> getOrdersIdsByReadAuthorization(User user) {
if (user.isInRole(UserRole.ROLE_SUPERUSER) if (user.isInRole(UserRole.ROLE_SUPERUSER) ||
|| user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) user.isInRole(UserRole.ROLE_READ_ALL_PROJECTS) ||
|| user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) { user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) {
return null; return null;
} else { } else {
String strQuery = "SELECT oa.order.id " String strQuery = "SELECT oa.order.id " +
+ "FROM OrderAuthorization oa " "FROM OrderAuthorization oa " +
+ "WHERE oa.user = :user "; "WHERE oa.user = :user ";
if (!user.getProfiles().isEmpty()) { if (!user.getProfiles().isEmpty()) {
strQuery += "OR oa.profile IN (:profiles) "; strQuery += "OR oa.profile IN (:profiles) ";
} }
@ -479,8 +481,7 @@ public class OrderDAO extends IntegrationEntityDAO<Order> implements IOrderDAO {
@Override @Override
public List<Order> getOrdersByWriteAuthorization(User user) { public List<Order> getOrdersByWriteAuthorization(User user) {
if (user.isInRole(UserRole.ROLE_SUPERUSER) if (user.isInRole(UserRole.ROLE_SUPERUSER) || user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) {
|| user.isInRole(UserRole.ROLE_EDIT_ALL_PROJECTS)) {
return getOrders(); return getOrders();
} }
else { else {
@ -695,8 +696,7 @@ public class OrderDAO extends IntegrationEntityDAO<Order> implements IOrderDAO {
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW) @Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public boolean existsByNameAnotherTransaction(String name) { public boolean existsByNameAnotherTransaction(String name) {
try { try {
Order order = findByName(name); return findByName(name)!= null;
return order != null;
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
return false; return false;
} }
@ -764,4 +764,13 @@ public class OrderDAO extends IntegrationEntityDAO<Order> implements IOrderDAO {
return filteredList; return filteredList;
} }
@Override
public List<Order> getOrdersWithNotEmptyCustomersReferences() {
return getSession()
.createCriteria(Order.class)
.add(Restrictions.isNotNull("customerReference"))
.add(Restrictions.ne("customerReference", ""))
.list();
}
} }

View file

@ -29,35 +29,49 @@ import java.util.EnumSet;
/** /**
* @author Susana Montes Pedreiera <smotnes@wirelessgalicia.com> * @author Susana Montes Pedreiera <smotnes@wirelessgalicia.com>
* @author Manuel Rego Casasnovas <rego@igalia.com> * @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
public enum OrderStatusEnum { public enum OrderStatusEnum {
PRE_SALES(_("PRE-SALES")), PRE_SALES(_("PRE-SALES"), 0),
OFFERED(_("OFFERED")), OFFERED(_("OFFERED"), 1),
OUTSOURCED(_("OUTSOURCED")), OUTSOURCED(_("OUTSOURCED"), 2),
ACCEPTED(_("ACCEPTED")), ACCEPTED(_("ACCEPTED"), 3),
STARTED(_("STARTED")), STARTED(_("STARTED"), 4),
ON_HOLD(_("ON HOLD")), ON_HOLD(_("ON HOLD"), 5),
FINISHED(_("FINISHED")), FINISHED(_("FINISHED"), 6),
CANCELLED(_("CANCELLED")), CANCELLED(_("CANCELLED"), 7),
STORED(_("ARCHIVED")); STORED(_("ARCHIVED"), 8);
private String description; private String description;
private OrderStatusEnum(String description) { /**
* For {@link DashboardControllerGlobal}.
* When I am building Global Dashboard page I need to know order of enums in {@link Grid}.
*/
private final int index;
OrderStatusEnum(String description, int index) {
this.description = description; this.description = description;
this.index = index;
} }
@Override
public String toString() { public String toString() {
return this.description; return this.description;
} }
public int getIndex() {
return this.index;
}
public static OrderStatusEnum getDefault() { public static OrderStatusEnum getDefault() {
return PRE_SALES; return PRE_SALES;
} }
public static EnumSet<OrderStatusEnum> getVisibleStatus() { public static EnumSet<OrderStatusEnum> getVisibleStatus() {
return EnumSet.of(OrderStatusEnum.PRE_SALES, OrderStatusEnum.OFFERED, return EnumSet.of(
OrderStatusEnum.PRE_SALES, OrderStatusEnum.OFFERED,
OrderStatusEnum.OUTSOURCED, OrderStatusEnum.ACCEPTED, OrderStatusEnum.OUTSOURCED, OrderStatusEnum.ACCEPTED,
OrderStatusEnum.STARTED, OrderStatusEnum.ON_HOLD, OrderStatusEnum.STARTED, OrderStatusEnum.ON_HOLD,
OrderStatusEnum.FINISHED); OrderStatusEnum.FINISHED);

View file

@ -42,7 +42,7 @@ import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
/** /**
* DAO for {@DayAssignment} * DAO for {@link DayAssignment}.
* *
* @author Diego Pino García <dpino@igalia.com> * @author Diego Pino García <dpino@igalia.com>
* @author Manuel Rego Casasnovas <mrego@igalia.com> * @author Manuel Rego Casasnovas <mrego@igalia.com>
@ -50,12 +50,12 @@ import org.springframework.stereotype.Repository;
*/ */
@Repository @Repository
@Scope(BeanDefinition.SCOPE_SINGLETON) @Scope(BeanDefinition.SCOPE_SINGLETON)
public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long> public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long> implements IDayAssignmentDAO {
implements IDayAssignmentDAO {
private final String SCENARIO = "scenario";
@Override @Override
public void removeDerived( public void removeDerived(Collection<? extends DerivedDayAssignment> assignments) {
Collection<? extends DerivedDayAssignment> assignments) {
for (DerivedDayAssignment each : assignments) { for (DerivedDayAssignment each : assignments) {
getSession().delete(each); getSession().delete(each);
} }
@ -63,54 +63,53 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
@Override @Override
public List<DayAssignment> getAllFor(Scenario scenario) { public List<DayAssignment> getAllFor(Scenario scenario) {
List<DayAssignment> result = new ArrayList<DayAssignment>(); List<DayAssignment> result = new ArrayList<>();
result.addAll(getSpecific(scenario, null, null, null)); result.addAll(getSpecific(scenario, null, null, null));
result.addAll(getGeneric(scenario, null, null, null)); result.addAll(getGeneric(scenario, null, null, null));
result.addAll(getDerived(scenario, null, null, null)); result.addAll(getDerived(scenario, null, null, null));
return result; return result;
} }
@Override @Override
public List<DayAssignment> getAllFor(Scenario scenario, LocalDate init, public List<DayAssignment> getAllFor(Scenario scenario, LocalDate init, LocalDate end) {
LocalDate end) { List<DayAssignment> result = new ArrayList<>();
List<DayAssignment> result = new ArrayList<DayAssignment>();
result.addAll(getSpecific(scenario, init, end, null)); result.addAll(getSpecific(scenario, init, end, null));
result.addAll(getGeneric(scenario, init, end, null)); result.addAll(getGeneric(scenario, init, end, null));
result.addAll(getDerived(scenario, init, end, null)); result.addAll(getDerived(scenario, init, end, null));
return result; return result;
} }
@Override @Override
public List<DayAssignment> getAllFor(Scenario scenario, public List<DayAssignment> getAllFor(
LocalDate startDateInclusive, LocalDate endDateInclusive, Scenario scenario, LocalDate startDateInclusive, LocalDate endDateInclusive, Resource resource) {
Resource resource) {
List<DayAssignment> result = new ArrayList<DayAssignment>(); List<DayAssignment> result = new ArrayList<>();
result.addAll(getSpecific(scenario, startDateInclusive, result.addAll(getSpecific(scenario, startDateInclusive, endDateInclusive, resource));
endDateInclusive, resource)); result.addAll(getGeneric(scenario, startDateInclusive, endDateInclusive, resource));
result.addAll(getGeneric(scenario, startDateInclusive, result.addAll(getDerived(scenario, startDateInclusive, endDateInclusive, resource));
endDateInclusive, resource));
result.addAll(getDerived(scenario, startDateInclusive,
endDateInclusive, resource));
return result; return result;
} }
private List<DerivedDayAssignment> getDerived(Scenario scenario, private List<DerivedDayAssignment> getDerived(
LocalDate initInclusive, LocalDate endInclusive, Resource resource) { Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) {
String queryString = "select d from DerivedDayAssignmentsContainer c "
+ "JOIN c.dayAssignments d where c.scenario = :scenario" String queryString = "select d from DerivedDayAssignmentsContainer c " +
+ addQueryConditionForInitAndEndDate(initInclusive, "JOIN c.dayAssignments d where c.scenario = :scenario" +
endInclusive) + addQueryConditionsForResource(resource); addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource);
Query query = getSession().createQuery(queryString); Query query = getSession().createQuery(queryString);
query = query.setParameter("scenario", scenario); query = query.setParameter(SCENARIO, scenario);
addInitAndEndParameters(query, initInclusive, endInclusive); addInitAndEndParameters(query, initInclusive, endInclusive);
addResourceParameter(query, resource); addResourceParameter(query, resource);
return query.list(); return query.list();
} }
private String addQueryConditionForInitAndEndDate(LocalDate initInclusive, private String addQueryConditionForInitAndEndDate(LocalDate initInclusive, LocalDate endInclusive) {
LocalDate endInclusive) { String initCondition = initInclusive != null ? " and d.day >= :init" : "";
String initCondition = initInclusive != null ? " and d.day >= :init"
: "";
String endCondition = endInclusive != null ? " and d.day <= :end" : ""; String endCondition = endInclusive != null ? " and d.day <= :end" : "";
return initCondition + endCondition; return initCondition + endCondition;
} }
@ -119,11 +118,11 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
return resource != null ? " and d.resource = :resource " : ""; return resource != null ? " and d.resource = :resource " : "";
} }
private Query addInitAndEndParameters(Query query, LocalDate initInclusive, private Query addInitAndEndParameters(Query query, LocalDate initInclusive, LocalDate endInclusive) {
LocalDate endInclusive) {
if (initInclusive != null) { if (initInclusive != null) {
query.setParameter("init", initInclusive); query.setParameter("init", initInclusive);
} }
if (endInclusive != null) { if (endInclusive != null) {
query.setParameter("end", endInclusive); query.setParameter("end", endInclusive);
} }
@ -131,33 +130,34 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
} }
private Query addResourceParameter(Query query, Resource resource) { private Query addResourceParameter(Query query, Resource resource) {
return resource != null ? query.setParameter("resource", resource) return resource != null ? query.setParameter("resource", resource) : query;
: query;
} }
private List<GenericDayAssignment> getGeneric(Scenario scenario, private List<GenericDayAssignment> getGeneric(
LocalDate initInclusive, LocalDate endInclusive, Resource resource) { Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) {
String queryString = "select d from GenericDayAssignmentsContainer c "
+ "JOIN c.dayAssignments d where c.scenario = :scenario" String queryString = "select d from GenericDayAssignmentsContainer c " +
+ addQueryConditionForInitAndEndDate(initInclusive, "JOIN c.dayAssignments d where c.scenario = :scenario" +
endInclusive) + addQueryConditionsForResource(resource); addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource);
Query query = getSession().createQuery(queryString).setParameter(
"scenario", scenario); Query query = getSession().createQuery(queryString).setParameter(SCENARIO, scenario);
addInitAndEndParameters(query, initInclusive, endInclusive); addInitAndEndParameters(query, initInclusive, endInclusive);
addResourceParameter(query, resource); addResourceParameter(query, resource);
return query.list(); return query.list();
} }
private List<SpecificDayAssignment> getSpecific(Scenario scenario, private List<SpecificDayAssignment> getSpecific(
LocalDate initInclusive, LocalDate endInclusive, Resource resource) { Scenario scenario, LocalDate initInclusive, LocalDate endInclusive, Resource resource) {
String queryString = "select d from SpecificDayAssignmentsContainer c "
+ "JOIN c.dayAssignments d where c.scenario = :scenario" String queryString = "select d from SpecificDayAssignmentsContainer c " +
+ addQueryConditionForInitAndEndDate(initInclusive, "JOIN c.dayAssignments d where c.scenario = :scenario" +
endInclusive) + addQueryConditionsForResource(resource); addQueryConditionForInitAndEndDate(initInclusive, endInclusive) + addQueryConditionsForResource(resource);
Query query = getSession().createQuery(queryString).setParameter(
"scenario", scenario); Query query = getSession().createQuery(queryString).setParameter(SCENARIO, scenario);
addInitAndEndParameters(query, initInclusive, endInclusive); addInitAndEndParameters(query, initInclusive, endInclusive);
addResourceParameter(query, resource); addResourceParameter(query, resource);
return query.list(); return query.list();
} }
@ -169,8 +169,7 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
return criteria.list(); return criteria.list();
} }
private void addDateRestrictionsToDayAssignmentQuery(Criteria criteria, private void addDateRestrictionsToDayAssignmentQuery(Criteria criteria, LocalDate init, LocalDate end) {
LocalDate init, LocalDate end) {
if (init != null) { if (init != null) {
criteria.add(Restrictions.ge("day", init)); criteria.add(Restrictions.ge("day", init));
} }
@ -181,19 +180,18 @@ public class DayAssignmentDAO extends GenericDAOHibernate<DayAssignment, Long>
@Override @Override
public List<DayAssignment> findByResources(Scenario scenario, List<Resource> resources) { public List<DayAssignment> findByResources(Scenario scenario, List<Resource> resources) {
// TODO incorporate scenario filtering to the query instead of doing it // TODO incorporate scenario filtering to the query instead of doing it in memory
// in memory
return DayAssignment.withScenario(scenario, findByResources(resources)); return DayAssignment.withScenario(scenario, findByResources(resources));
} }
@Override @Override
public List<DayAssignment> findByResources(List<Resource> resources) { public List<DayAssignment> findByResources(List<Resource> resources) {
if (resources.isEmpty()) { return resources.isEmpty()
return Collections.emptyList(); ? Collections.emptyList()
} : getSession()
Criteria criteria = getSession().createCriteria(DayAssignment.class) .createCriteria(DayAssignment.class)
.add(Restrictions.in("resource", resources)); .add(Restrictions.in("resource", resources))
return criteria.list(); .list();
} }
} }

View file

@ -74,7 +74,8 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
/** /**
* Constructor for Hibernate. DO NOT USE! * Constructor for Hibernate. DO NOT USE!
*/ */
public GenericResourceAllocation() {} public GenericResourceAllocation() {
}
public static GenericResourceAllocation create() { public static GenericResourceAllocation create() {
return create(new GenericResourceAllocation()); return create(new GenericResourceAllocation());
@ -168,9 +169,8 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
} }
public List<GenericDayAssignment> getOrderedAssignmentsFor(Resource resource) { public List<GenericDayAssignment> getOrderedAssignmentsFor(Resource resource) {
List<GenericDayAssignment> list = getOrderedAssignmentsFor().get(resource); List<GenericDayAssignment> assignments = getOrderedAssignmentsFor().get(resource);
return assignments == null ? Collections.emptyList() : Collections.unmodifiableList(assignments);
return list == null ? Collections.emptyList() : Collections.unmodifiableList(list);
} }
private Map<Resource, List<GenericDayAssignment>> getOrderedAssignmentsFor() { private Map<Resource, List<GenericDayAssignment>> getOrderedAssignmentsFor() {
@ -186,7 +186,6 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
@Override @Override
public boolean isSelectable(Resource resource, LocalDate day) { public boolean isSelectable(Resource resource, LocalDate day) {
ICriterion compoundCriterion = CriterionCompounder.buildAnd(criterions).getResult(); ICriterion compoundCriterion = CriterionCompounder.buildAnd(criterions).getResult();
return compoundCriterion.isSatisfiedBy(resource, day); return compoundCriterion.isSatisfiedBy(resource, day);
} }
} }
@ -268,7 +267,6 @@ public class GenericResourceAllocation extends ResourceAllocation<GenericDayAssi
ResourceAllocation<GenericDayAssignment> createCopy(Scenario scenario) { ResourceAllocation<GenericDayAssignment> createCopy(Scenario scenario) {
GenericResourceAllocation allocation = create(); GenericResourceAllocation allocation = create();
allocation.criterions = new HashSet<>(criterions); allocation.criterions = new HashSet<>(criterions);
return allocation; return allocation;
} }

View file

@ -27,7 +27,6 @@ import static org.libreplan.business.workingday.EffortDuration.zero;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -53,31 +52,23 @@ import org.libreplan.business.workingday.IntraDayDate.PartialDay;
* Note: this class has a natural ordering that is inconsistent with equals. * Note: this class has a natural ordering that is inconsistent with equals.
* *
* @author Diego Pino Garcia <dpino@igalia.com> * @author Diego Pino Garcia <dpino@igalia.com>
*
*/ */
public class Gap implements Comparable<Gap> { public class Gap implements Comparable<Gap> {
private DateAndHour startTime;
private DateAndHour endTime;
private Integer hoursInGap;
public Gap(Resource resource, DateAndHour startTime, DateAndHour endTime) {
this.startTime = startTime;
this.endTime = endTime;
hoursInGap = calculateHoursInGap(resource, startTime, endTime);
}
public static class GapOnQueue { public static class GapOnQueue {
public static List<GapOnQueue> onQueue(LimitingResourceQueue queue,
Collection<? extends Gap> gaps) {
List<GapOnQueue> result = new ArrayList<GapOnQueue>();
for (Gap each : gaps) {
result.add(each.onQueue(queue));
}
return result;
}
public static List<GapOnQueue> onQueue(
LimitingResourceQueue queue, DateAndHour startTime,
DateAndHour endTime) {
Gap gap = (endTime == null || endTime.compareTo(startTime) <= 0) ? Gap
.untilEnd(queue.getResource(), startTime) : Gap.create(
queue.getResource(), startTime, endTime);
return GapOnQueue.onQueue(queue, Collections.singleton(gap));
}
private final LimitingResourceQueue originQueue; private final LimitingResourceQueue originQueue;
private final Gap gap; private final Gap gap;
@ -87,6 +78,23 @@ public class Gap implements Comparable<Gap> {
this.gap = gap; this.gap = gap;
} }
public static List<GapOnQueue> onQueue(LimitingResourceQueue queue, Collection<? extends Gap> gaps) {
List<GapOnQueue> result = new ArrayList<>();
for (Gap each : gaps) {
result.add(each.onQueue(queue));
}
return result;
}
public static List<GapOnQueue> onQueue(LimitingResourceQueue queue, DateAndHour startTime, DateAndHour endTime) {
Gap gap = (endTime == null || endTime.compareTo(startTime) <= 0)
? Gap.untilEnd(queue.getResource(), startTime)
: Gap.create(queue.getResource(), startTime, endTime);
return GapOnQueue.onQueue(queue, Collections.singleton(gap));
}
public LimitingResourceQueue getOriginQueue() { public LimitingResourceQueue getOriginQueue() {
return originQueue; return originQueue;
} }
@ -95,13 +103,11 @@ public class Gap implements Comparable<Gap> {
return gap; return gap;
} }
public List<GapOnQueue> splitIntoGapsSatisfyingCriteria( public List<GapOnQueue> splitIntoGapsSatisfyingCriteria(Set<Criterion> criteria) {
Set<Criterion> criteria) { return GapOnQueue.onQueue(originQueue, gap.splitIntoGapsSatisfyingCriteria(originQueue.getResource(), criteria));
return GapOnQueue.onQueue(originQueue, gap
.splitIntoGapsSatisfyingCriteria(originQueue.getResource(),
criteria));
} }
@Override
public String toString() { public String toString() {
return "queue: " + originQueue + "; gap: " + gap; return "queue: " + originQueue + "; gap: " + gap;
} }
@ -109,10 +115,9 @@ public class Gap implements Comparable<Gap> {
} }
/** /**
* @author Diego Pino García <dpino@igalia.com> * Stores a {@link GapOnQueue} plus its adjacent {@link LimitingResourceQueueElement}.
* *
* Stores a {@link GapOnQueue} plus its adjacent * @author Diego Pino García <dpino@igalia.com>
* {@link LimitingResourceQueueElement}
*/ */
public static class GapOnQueueWithQueueElement { public static class GapOnQueueWithQueueElement {
@ -120,16 +125,15 @@ public class Gap implements Comparable<Gap> {
private final GapOnQueue gapOnQueue; private final GapOnQueue gapOnQueue;
public static GapOnQueueWithQueueElement create(GapOnQueue gapOnQueue,
LimitingResourceQueueElement queueElement) {
return new GapOnQueueWithQueueElement(gapOnQueue, queueElement);
}
GapOnQueueWithQueueElement(GapOnQueue gapOnQueue, LimitingResourceQueueElement queueElement) { GapOnQueueWithQueueElement(GapOnQueue gapOnQueue, LimitingResourceQueueElement queueElement) {
this.gapOnQueue = gapOnQueue; this.gapOnQueue = gapOnQueue;
this.queueElement = queueElement; this.queueElement = queueElement;
} }
public static GapOnQueueWithQueueElement create(GapOnQueue gapOnQueue, LimitingResourceQueueElement queueElement) {
return new GapOnQueueWithQueueElement(gapOnQueue, queueElement);
}
public LimitingResourceQueueElement getQueueElement() { public LimitingResourceQueueElement getQueueElement() {
return queueElement; return queueElement;
} }
@ -139,36 +143,31 @@ public class Gap implements Comparable<Gap> {
} }
/** /**
* Joins first.gap + second.gap and keeps second.queueElement as * Joins first.gap + second.gap and keeps second.queueElement as {@link LimitingResourceQueueElement}.
* {@link LimitingResourceQueueElement}
* *
* @param first * @param first
* @param second * @param second
* @return * @return {@link GapOnQueueWithQueueElement}
*/ */
public static GapOnQueueWithQueueElement coalesce( public static GapOnQueueWithQueueElement coalesce(
GapOnQueueWithQueueElement first, GapOnQueueWithQueueElement first, GapOnQueueWithQueueElement second) {
GapOnQueueWithQueueElement second) {
LimitingResourceQueue queue = first.getGapOnQueue() LimitingResourceQueue queue = first.getGapOnQueue().getOriginQueue();
.getOriginQueue(); DateAndHour startTime = first.getGapOnQueue().getGap().getStartTime();
DateAndHour startTime = first.getGapOnQueue().getGap()
.getStartTime();
DateAndHour endTime = second.getGapOnQueue().getGap().getEndTime(); DateAndHour endTime = second.getGapOnQueue().getGap().getEndTime();
Gap coalescedGap = Gap.create(queue.getResource(), startTime, Gap coalescedGap = Gap.create(queue.getResource(), startTime, endTime);
endTime);
return create(coalescedGap.onQueue(queue), second.getQueueElement()); return create(coalescedGap.onQueue(queue), second.getQueueElement());
} }
@Override
public String toString() { public String toString() {
return "gapOnQueue: " + gapOnQueue + "; queueElement: " + queueElement; return "gapOnQueue: " + gapOnQueue + "; queueElement: " + queueElement;
} }
} }
public static Gap untilEnd(LimitingResourceQueueElement current, public static Gap untilEnd(LimitingResourceQueueElement current, DateAndHour startInclusive) {
DateAndHour startInclusive) {
return untilEnd(current.getResource(), startInclusive); return untilEnd(current.getResource(), startInclusive);
} }
@ -176,48 +175,27 @@ public class Gap implements Comparable<Gap> {
return new Gap(resource, startInclusive, null); return new Gap(resource, startInclusive, null);
} }
private DateAndHour startTime;
private DateAndHour endTime;
private Integer hoursInGap;
public Gap(Resource resource, DateAndHour startTime,
DateAndHour endTime) {
this.startTime = startTime;
this.endTime = endTime;
hoursInGap = calculateHoursInGap(resource, startTime, endTime);
}
public GapOnQueue onQueue(LimitingResourceQueue queue) { public GapOnQueue onQueue(LimitingResourceQueue queue) {
return new GapOnQueue(queue, this); return new GapOnQueue(queue, this);
} }
private Integer calculateHoursInGap(Resource resource, DateAndHour startTime, DateAndHour endTime) { private Integer calculateHoursInGap(Resource resource, DateAndHour startTime, DateAndHour endTime) {
// TODO remove this method. Use GapRequirements instead
if (endTime == null || startTime == null) { if (endTime == null || startTime == null) {
// startTime is never null when hours in gap is really use // startTime is never null when hours in gap is really use
return Integer.MAX_VALUE; return Integer.MAX_VALUE;
} else { } else {
return calculateHoursInGap(resource, startTime.getDate(), startTime return calculateHoursInGap(
.getHour(), endTime.getDate(), endTime.getHour()); resource, startTime.getDate(), startTime.getHour(), endTime.getDate(), endTime.getHour());
} }
} }
public int getHoursInGap() { private Integer calculateHoursInGap(Resource resource, LocalDate startDate, int startHour, LocalDate endDate, int endHour) {
return hoursInGap; IntraDayDate intraStart = IntraDayDate.create(startDate, hours(startHour));
}
private Integer calculateHoursInGap(Resource resource, LocalDate startDate,
int startHour, LocalDate endDate, int endHour) {
IntraDayDate intraStart = IntraDayDate.create(startDate,
hours(startHour));
IntraDayDate intraEnd = IntraDayDate.create(endDate, hours(endHour)); IntraDayDate intraEnd = IntraDayDate.create(endDate, hours(endHour));
return calculateHoursInGap(resource, intraStart, intraEnd); return calculateHoursInGap(resource, intraStart, intraEnd);
} }
private Integer calculateHoursInGap(Resource resource, IntraDayDate start, private Integer calculateHoursInGap(Resource resource, IntraDayDate start, IntraDayDate end) {
IntraDayDate end) {
final ResourceCalendar calendar = resource.getCalendar(); final ResourceCalendar calendar = resource.getCalendar();
Iterable<PartialDay> days = start.daysUntil(end); Iterable<PartialDay> days = start.daysUntil(end);
EffortDuration result = zero(); EffortDuration result = zero();
@ -228,14 +206,12 @@ public class Gap implements Comparable<Gap> {
} }
public List<Integer> getHoursInGapUntilAllocatingAndGoingToTheEnd( public List<Integer> getHoursInGapUntilAllocatingAndGoingToTheEnd(
BaseCalendar calendar, BaseCalendar calendar, DateAndHour realStart, DateAndHour allocationEnd, int total) {
DateAndHour realStart, DateAndHour allocationEnd, int total) {
Validate.isTrue(endTime == null || allocationEnd.compareTo(endTime) <= 0); Validate.isTrue(endTime == null || allocationEnd.compareTo(endTime) <= 0);
Validate.isTrue(startTime == null Validate.isTrue(startTime == null || realStart.compareTo(startTime) >= 0);
|| realStart.compareTo(startTime) >= 0);
Validate.isTrue(total >= 0); Validate.isTrue(total >= 0);
List<Integer> result = new ArrayList<Integer>(); List<Integer> result = new ArrayList<>();
// If endTime is null (last tasks) assume the end is in 10 years from now // If endTime is null (last tasks) assume the end is in 10 years from now
DateAndHour endDate = getEndTime(); DateAndHour endDate = getEndTime();
@ -243,31 +219,24 @@ public class Gap implements Comparable<Gap> {
endDate = DateAndHour.TEN_YEARS_FROM(realStart); endDate = DateAndHour.TEN_YEARS_FROM(realStart);
} }
Iterator<PartialDay> daysUntilEnd = realStart.toIntraDayDate() for (PartialDay each : realStart.toIntraDayDate().daysUntil(endDate.toIntraDayDate())) {
.daysUntil(endDate.toIntraDayDate()).iterator();
while (daysUntilEnd.hasNext()) {
PartialDay each = daysUntilEnd.next();
int hoursAtDay = calendar.getCapacityOn(each).roundToHours(); int hoursAtDay = calendar.getCapacityOn(each).roundToHours();
int hours = Math.min(hoursAtDay, total); int hours = Math.min(hoursAtDay, total);
total -= hours; total -= hours;
// Don't add hours when total and hours are zero (it'd be like // Don't add hours when total and hours are zero (it'd be like adding an extra 0 hour day when total is completed)
// adding an extra 0 hour day when total is completed)
if ( total != 0 || hours != 0 ) { if ( total != 0 || hours != 0 ) {
result.add(hours); result.add(hours);
} }
if (total == 0 if ( total == 0 && DateAndHour.from(each.getDate()).compareTo(allocationEnd) >= 0 ) {
&& DateAndHour.from(each.getDate())
.compareTo(allocationEnd) >= 0) {
break; break;
} }
} }
return result; return result;
} }
public static Gap create(Resource resource, DateAndHour startTime, public static Gap create(Resource resource, DateAndHour startTime, DateAndHour endTime) {
DateAndHour endTime) {
return new Gap(resource, startTime, endTime); return new Gap(resource, startTime, endTime);
} }
@ -280,21 +249,18 @@ public class Gap implements Comparable<Gap> {
} }
/** /**
* Returns true if the gap starts after earlierStartDateBecauseOfGantt and * Returns true if the gap starts after earlierStartDateBecauseOfGantt and if it's big enough for fitting candidate.
* if it's big enough for fitting candidate
* *
* @param hours * @param candidate
* @return * @return boolean
*/ */
public boolean canFit(LimitingResourceQueueElement candidate) { public boolean canFit(LimitingResourceQueueElement candidate) {
LocalDate startAfter = LocalDate.fromDateFields(candidate LocalDate startAfter = LocalDate.fromDateFields(candidate.getEarliestStartDateBecauseOfGantt());
.getEarliestStartDateBecauseOfGantt()); LocalDate endsAfter = LocalDate.fromDateFields(candidate.getEarliestEndDateBecauseOfGantt());
LocalDate endsAfter = LocalDate.fromDateFields(candidate
.getEarliestEndDateBecauseOfGantt());
return canSatisfyStartConstraint(startAfter) return canSatisfyStartConstraint(startAfter) &&
&& canSatisfyEndConstraint(endsAfter) canSatisfyEndConstraint(endsAfter) &&
&& hoursInGap >= candidate.getIntentedTotalHours(); hoursInGap >= candidate.getIntentedTotalHours();
} }
private boolean canSatisfyStartConstraint(final LocalDate startsAfter) { private boolean canSatisfyStartConstraint(final LocalDate startsAfter) {
@ -305,6 +271,7 @@ public class Gap implements Comparable<Gap> {
return endTime == null || endsAfter.compareTo(endTime.getDate()) <= 0; return endTime == null || endsAfter.compareTo(endTime.getDate()) <= 0;
} }
@Override
public String toString() { public String toString() {
String result = ""; String result = "";
@ -322,10 +289,13 @@ public class Gap implements Comparable<Gap> {
if (other == null) { if (other == null) {
return 1; return 1;
} }
if (this.getStartTime() == null && other.getStartTime() == null) { if (this.getStartTime() == null && other.getStartTime() == null) {
return 0; return 0;
} else if (this.getStartTime() == null) { } else if (this.getStartTime() == null) {
return -1; return -1;
} else if (other.getStartTime() == null) { } else if (other.getStartTime() == null) {
return 1; return 1;
} }
@ -333,19 +303,17 @@ public class Gap implements Comparable<Gap> {
} }
public boolean isBefore(Gap gap) { public boolean isBefore(Gap gap) {
return (compareTo(gap) < 0); return compareTo(gap) < 0;
} }
public List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource, public List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource, Set<Criterion> criteria) {
Set<Criterion> criteria) { return splitIntoGapsSatisfyingCriteria(resource, criteria, getStartTime(), getEndTime());
return splitIntoGapsSatisfyingCriteria(resource, criteria,
getStartTime(), getEndTime());
} }
/** /**
* Returns a set of {@link Gap} composed by those gaps which satisfy * Returns a set of {@link Gap} composed by those gaps which satisfy <em>criteria</em> within the period:
* <em>criteria</em> within the period: <em>gapStartTime</em> till * <em>gapStartTime</em> till <em>gapEndTime</em>.
* <em>gapEndTime</em> *
* @param resource * @param resource
* @param criteria * @param criteria
* criteria to be satisfied by resource * criteria to be satisfied by resource
@ -353,42 +321,45 @@ public class Gap implements Comparable<Gap> {
* start time of gap * start time of gap
* @param gapEndTime * @param gapEndTime
* end time of gap * end time of gap
* @return * @return {@link List<Gap>}
*/ */
private static List<Gap> splitIntoGapsSatisfyingCriteria(Resource resource, private static List<Gap> splitIntoGapsSatisfyingCriteria(
Set<Criterion> criteria, DateAndHour gapStartTime, Resource resource, Set<Criterion> criteria, DateAndHour gapStartTime, DateAndHour gapEndTime) {
DateAndHour gapEndTime) {
AvailabilityTimeLine criterionsAvailability = AvailabilityCalculator AvailabilityTimeLine criterionsAvailability =
.getCriterionsAvailabilityFor(criteria, resource); AvailabilityCalculator.getCriterionsAvailabilityFor(criteria, resource);
if (gapStartTime != null) { if (gapStartTime != null) {
criterionsAvailability.invalidUntil(gapStartTime.getDate()); criterionsAvailability.invalidUntil(gapStartTime.getDate());
} }
if (gapEndTime != null) { if (gapEndTime != null) {
criterionsAvailability.invalidFrom(gapEndTime.getDate()); criterionsAvailability.invalidFrom(gapEndTime.getDate());
} }
List<Interval> validPeriods = criterionsAvailability.getValidPeriods(); List<Interval> validPeriods = criterionsAvailability.getValidPeriods();
List<Gap> result = new ArrayList<Gap>(); List<Gap> result = new ArrayList<>();
for (Interval each : validPeriods) { for (Interval each : validPeriods) {
result.add(createGap(resource, each, gapStartTime, gapEndTime)); result.add(createGap(resource, each, gapStartTime, gapEndTime));
} }
return result; return result;
} }
private static Gap createGap(Resource resource, Interval interval, private static Gap createGap(
DateAndHour originalGapStartTime, DateAndHour originalGapEndTime) { Resource resource, Interval interval, DateAndHour originalGapStartTime, DateAndHour originalGapEndTime) {
DateAndHour start = convert(originalGapStartTime, interval.getStart()); DateAndHour start = convert(originalGapStartTime, interval.getStart());
DateAndHour end = convert(originalGapEndTime, interval.getEnd()); DateAndHour end = convert(originalGapEndTime, interval.getEnd());
return Gap.create(resource, start, end); return Gap.create(resource, start, end);
} }
private static DateAndHour convert(DateAndHour possibleMatch, private static DateAndHour convert(DateAndHour possibleMatch, DatePoint datePoint) {
DatePoint datePoint) {
if (datePoint instanceof StartOfTime || datePoint instanceof EndOfTime) { if (datePoint instanceof StartOfTime || datePoint instanceof EndOfTime) {
return null; return null;
} }
FixedPoint p = (FixedPoint) datePoint; FixedPoint p = (FixedPoint) datePoint;
if (possibleMatch != null if (possibleMatch != null && possibleMatch.getDate().equals(p.getDate())) {
&& possibleMatch.getDate().equals(p.getDate())) {
return possibleMatch; return possibleMatch;
} }
return DateAndHour.from(p.getDate()); return DateAndHour.from(p.getDate());

View file

@ -33,6 +33,7 @@ import org.libreplan.business.scenarios.entities.Scenario;
* Contract for {@link ScenarioDAO}. * Contract for {@link ScenarioDAO}.
* *
* @author Manuel Rego Casasnovas <mrego@igalia.com> * @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
public interface IScenarioDAO extends IGenericDAO<Scenario, Long> { public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
@ -44,6 +45,14 @@ public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
List<Scenario> getAll(); List<Scenario> getAll();
/**
* Gets all {@link Scenario}s except chosen.
*
* @param scenario Selected {@link Scenario} that you want to exclude
* @return {@link List<Scenario>}
*/
List<Scenario> getAllExcept(Scenario scenario);
boolean thereIsOtherWithSameName(Scenario scenario); boolean thereIsOtherWithSameName(Scenario scenario);
List<Scenario> findByPredecessor(Scenario scenario); List<Scenario> findByPredecessor(Scenario scenario);
@ -51,7 +60,6 @@ public interface IScenarioDAO extends IGenericDAO<Scenario, Long> {
List<Scenario> getDerivedScenarios(Scenario scenario); List<Scenario> getDerivedScenarios(Scenario scenario);
void updateDerivedScenariosWithNewVersion( void updateDerivedScenariosWithNewVersion(
OrderVersion previousOrderVersion, Order order, OrderVersion previousOrderVersion, Order order, Scenario currentScenario, OrderVersion newOrderVersion);
Scenario currentScenario, OrderVersion newOrderVersion);
} }

View file

@ -45,6 +45,7 @@ import org.springframework.transaction.annotation.Transactional;
* DAO implementation for {@link Scenario}. * DAO implementation for {@link Scenario}.
* *
* @author Manuel Rego Casasnovas <mrego@igalia.com> * @author Manuel Rego Casasnovas <mrego@igalia.com>
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
@Repository @Repository
@Scope(BeanDefinition.SCOPE_SINGLETON) @Scope(BeanDefinition.SCOPE_SINGLETON)
@ -118,6 +119,14 @@ public class ScenarioDAO extends GenericDAOHibernate<Scenario, Long> implements
return list(Scenario.class); return list(Scenario.class);
} }
@Override
public List<Scenario> getAllExcept(Scenario scenario) {
return getSession()
.createCriteria(Scenario.class)
.add(Restrictions.ne("name", scenario.getName()))
.list();
}
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true) @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
@Override @Override
public boolean thereIsOtherWithSameName(Scenario scenario) { public boolean thereIsOtherWithSameName(Scenario scenario) {
@ -135,11 +144,9 @@ public class ScenarioDAO extends GenericDAOHibernate<Scenario, Long> implements
@Override @Override
public List<Scenario> findByPredecessor(Scenario scenario) { public List<Scenario> findByPredecessor(Scenario scenario) {
if (scenario == null) { return scenario == null
return Collections.emptyList(); ? Collections.emptyList()
} : getSession()
return getSession()
.createCriteria(Scenario.class) .createCriteria(Scenario.class)
.add(Restrictions.eq("predecessor", scenario)) .add(Restrictions.eq("predecessor", scenario))
.list(); .list();

View file

@ -27,7 +27,9 @@ import static org.junit.Assert.assertTrue;
import static org.libreplan.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE; import static org.libreplan.business.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_FILE;
import static org.libreplan.business.test.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_TEST_FILE; import static org.libreplan.business.test.BusinessGlobalNames.BUSINESS_SPRING_CONFIG_TEST_FILE;
import java.util.Date;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -48,7 +50,6 @@ import org.libreplan.business.scenarios.daos.IOrderVersionDAO;
import org.libreplan.business.scenarios.daos.IScenarioDAO; import org.libreplan.business.scenarios.daos.IScenarioDAO;
import org.libreplan.business.scenarios.entities.OrderVersion; import org.libreplan.business.scenarios.entities.OrderVersion;
import org.libreplan.business.scenarios.entities.Scenario; import org.libreplan.business.scenarios.entities.Scenario;
import org.libreplan.business.test.scenarios.daos.ScenarioDAOTest;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
@ -106,8 +107,7 @@ public class ScenariosBootstrapTest {
deleteSchedulingStatesByOrderVersion.executeUpdate(); deleteSchedulingStatesByOrderVersion.executeUpdate();
session.flush(); session.flush();
Query deleteSchedulingDataForVersion = Query deleteSchedulingDataForVersion = session.createSQLQuery("DELETE FROM scheduling_data_for_version");
session.createSQLQuery("DELETE FROM scheduling_data_for_version");
deleteSchedulingDataForVersion.executeUpdate(); deleteSchedulingDataForVersion.executeUpdate();
session.flush(); session.flush();
@ -115,18 +115,23 @@ public class ScenariosBootstrapTest {
for (Order order : orderDAO.findAll()) { for (Order order : orderDAO.findAll()) {
orderDAO.remove(order.getId()); orderDAO.remove(order.getId());
} }
// TODO: replace with Hibernate Criteria
for (Scenario scenario : scenarioDAO.getAll()) { Scenario masterScenario = null;
if (!"master".equals(scenario.getName())) { try {
masterScenario = PredefinedScenarios.MASTER.getScenario();
} catch (RuntimeException ignored) {
}
if ( masterScenario != null ) {
for (Scenario scenario : scenarioDAO.getAllExcept(masterScenario)) {
scenarioDAO.remove(scenario.getId()); scenarioDAO.remove(scenario.getId());
} }
else {
for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) { for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) {
scenario.removeVersion(orderVersion); masterScenario.removeVersion(orderVersion);
} }
session.flush(); session.flush();
} }
}
for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) { for (OrderVersion orderVersion : orderVersionDAO.list(OrderVersion.class)) {
orderVersionDAO.remove(orderVersion.getId()); orderVersionDAO.remove(orderVersion.getId());
@ -140,8 +145,18 @@ public class ScenariosBootstrapTest {
private Order givenOrderStored() { private Order givenOrderStored() {
// TODO : refactor this ( do not use method from other testClass ) return createOrderStored(orderDAO, configurationDAO);
return ScenarioDAOTest.createOrderStored(orderDAO, configurationDAO); }
public Order createOrderStored(IOrderDAO orderDAO, IConfigurationDAO configurationDAO) {
Order order = Order.create();
order.setInitDate(new Date());
order.setName("name-" + UUID.randomUUID().toString());
order.setCode("code-" + UUID.randomUUID().toString());
order.setCalendar(configurationDAO.getConfiguration().getDefaultCalendar());
orderDAO.save(order);
return order;
} }
@Test @Test

View file

@ -30,24 +30,21 @@ import org.libreplan.business.orders.entities.OrderSyncInfo;
import org.libreplan.importers.jira.IssueDTO; import org.libreplan.importers.jira.IssueDTO;
/** /**
* Synchronize order elements inclusive progress assignments and measurements of * Synchronize order elements inclusive progress assignments and measurements of an existing order with Jira issues.
* an existing order with Jira issues. * Jira issues will be retrieved from Jira RESTful web service using {@link JiraRESTClient}.
*
* Jira issues will be retrieved from Jira RESTful web service using
* {@link JiraRESTClient}
* *
* @author Miciele Ghiorghis <m.ghiorghis@antoniusziekenhuis.nl> * @author Miciele Ghiorghis <m.ghiorghis@antoniusziekenhuis.nl>
*/ */
public interface IJiraOrderElementSynchronizer { public interface IJiraOrderElementSynchronizer {
/** /**
* Gets all distinct jira lables from an external 'php' script. * Gets all distinct JIRA lables from an external 'php' script.
* *
* FIXME: This is because at this moment Jira doesn't support Labels * FIXME: This is because at this moment Jira doesn't support Labels request.
* request. As workaround we build a simple php script to do the query in * As workaround we build a simple php script to do the query in
* Jira database and returns a comma separated string(labels). Once Jira * Jira database and returns a comma separated string(labels).
* supports the labels request this method will be modified. More info: * Once Jira supports the labels request this method will be modified.
* https://jira.atlassian.com/browse/JRA-29409 * More info: https://jira.atlassian.com/browse/JRA-29409
* *
* @return A list of labels * @return A list of labels
* @throws ConnectorException * @throws ConnectorException
@ -56,13 +53,12 @@ public interface IJiraOrderElementSynchronizer {
List<String> getAllJiraLabels() throws ConnectorException; List<String> getAllJiraLabels() throws ConnectorException;
/** /**
* Get all jira issues based on the specified <code>label</code> parameter * Get all JIRA issues based on the specified <code>label</code> parameter from JIRA RESTFul web service.
* from jira RESTFul web service
* *
* @param label * @param label
* search criteria for jira issues * search criteria for JIRA issues
* *
* @return list of jira issues * @return list of JIRA issues
* @throws ConnectorException * @throws ConnectorException
* if connector not found or contains invalid connection values * if connector not found or contains invalid connection values
*/ */
@ -70,26 +66,23 @@ public interface IJiraOrderElementSynchronizer {
/** /**
* Synchronizes the list of {@link OrderElement}s, * Synchronizes the list of {@link OrderElement}s,
* {@link DirectAdvanceAssignment}s and {@link AdvanceMeasurement}s of the * {@link DirectAdvanceAssignment}s and {@link AdvanceMeasurement}s of the given {@link Order} with JIRA issues.
* given {@link Order} with jira issues.
* *
* Loops through all jira <code>issues</code> and check if an * Loops through all JIRA <code>issues</code> and check if an {@link OrderElement} of the given <code>order</code> exists.
* {@link OrderElement} of the given <code>order</code> exists. If it * If it exists, update the {@link OrderElement} with the issue item.
* exists, update the {@link OrderElement} with the issue item. If not * If not create new {@link OrderElement}, update it with the issue item and add to
* create new {@link OrderElement}, update it with the issue item and add to * the <code>order</code> and start synchronization of {@link DirectAdvanceAssignment} and {@link AdvanceMeasurement}.
* the <code>order</code> and start synchronization of
* {@link DirectAdvanceAssignment} and {@link AdvanceMeasurement}
* *
* @param order * @param order
* an existing order where its orderElements will be synchronized * an existing order where its orderElements will be synchronized
* with jira issues * with JIRA issues
* @param issues * @param issues
* jira issues * JIRA issues
*/ */
void syncOrderElementsWithJiraIssues(List<IssueDTO> issues, Order order); void syncOrderElementsWithJiraIssues(List<IssueDTO> issues, Order order);
/** /**
* Saves synchronization info * Saves synchronization info.
* *
* @param key * @param key
* the key(label) * the key(label)
@ -99,7 +92,7 @@ public interface IJiraOrderElementSynchronizer {
void saveSyncInfo(String key, Order order); void saveSyncInfo(String key, Order order);
/** /**
* Gets the most recent synchronized info * Gets the most recent synchronized info.
* *
* @param order * @param order
* the order * the order
@ -108,17 +101,15 @@ public interface IJiraOrderElementSynchronizer {
OrderSyncInfo getOrderLastSyncInfo(Order order); OrderSyncInfo getOrderLastSyncInfo(Order order);
/** /**
* returns synchronization info, success or fail info * Returns synchronization info, success or fail info.
*/ */
SynchronizationInfo getSynchronizationInfo(); SynchronizationInfo getSynchronizationInfo();
/** /**
* Synchronize order elements with JIRA issues if they already synchronized * Synchronize order elements with JIRA issues if they already synchronized using
* using * {@link IJiraOrderElementSynchronizer#syncOrderElementsWithJiraIssues(List, Order).
* {@link IJiraOrderElementSynchronizer#syncOrderElementsWithJiraIssues(List, Order)
* *
* It gets then an already synchronized orders from the * It gets then an already synchronized orders from the {@link OrderSyncInfo} and re-synchronize them.
* {@link OrderSyncInfo} and re-synchronize them
* *
* @return a list of {@link SynchronizationInfo} * @return a list of {@link SynchronizationInfo}
* *

View file

@ -26,8 +26,8 @@ import org.libreplan.business.orders.entities.OrderElement;
import org.libreplan.business.planner.entities.TaskElement; import org.libreplan.business.planner.entities.TaskElement;
/** /**
* Class that represents no persistent imported tasks. <br /> * Class that represents no persistent imported tasks.
* * <br />
* At these moment it only represent the tasks that can have any subtasks. * At these moment it only represent the tasks that can have any subtasks.
* *
* @author Alba Carro Pérez <alba.carro@gmail.com> * @author Alba Carro Pérez <alba.carro@gmail.com>
@ -81,7 +81,7 @@ public class OrderElementDTO implements IHasTaskAssociated {
public ConstraintDTO constraint; public ConstraintDTO constraint;
/** /**
* Contraint date of this task. * Constraint date of this task.
*/ */
public Date constraintDate; public Date constraintDate;
@ -90,14 +90,14 @@ public class OrderElementDTO implements IHasTaskAssociated {
*/ */
public TaskElement taskElement; public TaskElement taskElement;
@Override
public TaskElement getTaskAssociated() {
return taskElement;
}
/** /**
* Name of the calendar that this OrderElementDTO is linked to. * Name of the calendar that this OrderElementDTO is linked to.
*/ */
public String calendarName = null; public String calendarName = null;
@Override
public TaskElement getTaskAssociated() {
return taskElement;
}
} }

View file

@ -47,7 +47,7 @@ import java.util.List;
* and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_FINISH}. * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_FINISH}.
* Data will be send when current day equals to finish date. * Data will be send when current day equals to finish date.
* *
* @author Created by Vova Perebykivskyi <vova@libreplan-enterprise.com> on 21.01.2016. * @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
@Component @Component
@ -77,12 +77,14 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
List<EmailNotification> notifications = List<EmailNotification> notifications =
emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH); emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_FINISH);
for (int i = 0; i < notifications.size(); i++) for (int i = 0; i < notifications.size(); i++) {
if ( composeMessageForUser(notifications.get(i)) ) if ( composeMessageForUser(notifications.get(i)) ) {
deleteSingleNotification(notifications.get(i)); deleteSingleNotification(notifications.get(i));
} }
} }
} }
}
}
@Override @Override
public boolean composeMessageForUser(EmailNotification notification) { public boolean composeMessageForUser(EmailNotification notification) {
@ -120,11 +122,10 @@ public class SendEmailOnTaskShouldFinish implements IEmailNotificationJob {
private void sendEmailNotificationAboutTaskShouldFinish(TaskElement item){ private void sendEmailNotificationAboutTaskShouldFinish(TaskElement item){
List<ResourceAllocation<?>> list = new ArrayList<>(); List<ResourceAllocation<?>> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations());
list.addAll(item.getAllResourceAllocations());
List<Resource> resources = new ArrayList<>(); List<Resource> resources = new ArrayList<>();
for (ResourceAllocation<?> allocation : list) for (ResourceAllocation<?> allocation : resourceAllocations)
resources.add(allocation.getAssociatedResources().get(0)); resources.add(allocation.getAssociatedResources().get(0));
for (Resource resourceItem : resources){ for (Resource resourceItem : resources){

View file

@ -47,7 +47,7 @@ import java.util.List;
* and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_START}. * and that are treat to {@link EmailTemplateEnum#TEMPLATE_TODAY_TASK_SHOULD_START}.
* Data will be send if current data equals to start date. * Data will be send if current data equals to start date.
* *
* @author Created by Vova Perebykivskyi <vova@libreplan-enterprise.com> on 20.01.2016. * @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
@Component @Component
@ -79,11 +79,12 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob {
emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START); emailNotificationModel.getAllByType(EmailTemplateEnum.TEMPLATE_TODAY_TASK_SHOULD_START);
for (EmailNotification notification : notifications) for (EmailNotification notification : notifications)
if ( composeMessageForUser(notification) ) if ( composeMessageForUser(notification) ) {
deleteSingleNotification(notification); deleteSingleNotification(notification);
} }
} }
} }
}
@Override @Override
public boolean composeMessageForUser(EmailNotification notification) { public boolean composeMessageForUser(EmailNotification notification) {
@ -118,11 +119,10 @@ public class SendEmailOnTaskShouldStart implements IEmailNotificationJob {
} }
private void sendEmailNotificationAboutTaskShouldStart(TaskElement item) { private void sendEmailNotificationAboutTaskShouldStart(TaskElement item) {
List<ResourceAllocation<?>> list = new ArrayList<>(); List<ResourceAllocation<?>> resourceAllocations = new ArrayList<>(item.getAllResourceAllocations());
list.addAll(item.getAllResourceAllocations());
List<Resource> resources = new ArrayList<>(); List<Resource> resources = new ArrayList<>();
for (ResourceAllocation<?> allocation : list) for (ResourceAllocation<?> allocation : resourceAllocations)
resources.add(allocation.getAssociatedResources().get(0)); resources.add(allocation.getAssociatedResources().get(0));
for (Resource resourceItem : resources) { for (Resource resourceItem : resources) {

View file

@ -42,6 +42,9 @@ public class I18nHelper {
private static HashMap<Locale, I18n> localesCache = new HashMap<>(); private static HashMap<Locale, I18n> localesCache = new HashMap<>();
private I18nHelper() {
}
public static I18n getI18n() { public static I18n getI18n() {
setPreferredLocale(); setPreferredLocale();
@ -89,11 +92,9 @@ public class I18nHelper {
return i18n; return i18n;
} }
private I18nHelper() {
}
//TODO It should be changed since JDK9.
/** /**
* TODO It should be changed since JDK9
*
* Use of '_' as an identifier might not be supported in releases after Java SE 8. * Use of '_' as an identifier might not be supported in releases after Java SE 8.
* *
* @param str * @param str

View file

@ -172,7 +172,8 @@ public class ConfigurationController extends GenericForwardComposer {
private String LOGO_PREVIEW_COMPONENT = "logoPreview"; private String LOGO_PREVIEW_COMPONENT = "logoPreview";
public ConfigurationController() {} public ConfigurationController() {
}
@Override @Override
public void doAfterCompose(Component comp) throws Exception { public void doAfterCompose(Component comp) throws Exception {
@ -389,7 +390,6 @@ public class ConfigurationController extends GenericForwardComposer {
public void testConnection() { public void testConnection() {
if (selectedConnector == null) { if (selectedConnector == null) {
messages.showMessage(Level.ERROR, _("Please select a connector to test it")); messages.showMessage(Level.ERROR, _("Please select a connector to test it"));
return; return;
} }
@ -1588,7 +1588,8 @@ public class ConfigurationController extends GenericForwardComposer {
ch = in.read(buffer); ch = in.read(buffer);
} }
} catch (IOException ignored) {} } catch (IOException ignored) {
}
finally { finally {
try { try {
@ -1596,7 +1597,8 @@ public class ConfigurationController extends GenericForwardComposer {
out.close(); out.close();
in.close(); in.close();
} catch (IOException ignored) {} } catch (IOException ignored) {
}
} }
Util.setLogoFromTarget(media.getName()); Util.setLogoFromTarget(media.getName());
@ -1651,6 +1653,7 @@ public class ConfigurationController extends GenericForwardComposer {
try { try {
fileToDelete = ContextLoaderListener.getCurrentWebApplicationContext().getResource(name).getFile(); fileToDelete = ContextLoaderListener.getCurrentWebApplicationContext().getResource(name).getFile();
fileToDelete.delete(); fileToDelete.delete();
} catch (IOException ignored) {} } catch (IOException ignored) {
}
} }
} }

View file

@ -104,7 +104,8 @@ public class Util {
*/ */
public static Image logo; public static Image logo;
private Util() {} private Util() {
}
/** /**
* Forces to reload the bindings of the provided components if there is an associated {@link DefaultBinder}. * Forces to reload the bindings of the provided components if there is an associated {@link DefaultBinder}.
@ -201,7 +202,7 @@ public class Util {
public static void saveBindings(Component... toReload) { public static void saveBindings(Component... toReload) {
for (Component reload : toReload) { for (Component reload : toReload) {
/* TODO resolve deprecated */
DataBinder binder = Util.getBinder(reload); DataBinder binder = Util.getBinder(reload);
if (binder != null) { if (binder != null) {
@ -224,7 +225,7 @@ public class Util {
} }
} }
public static void createBindingsFor(org.zkoss.zk.ui.Component result) { public static void createBindingsFor(Component result) {
if (ignoreCreateBindings.get()) { if (ignoreCreateBindings.get()) {
return; return;
} }
@ -290,7 +291,6 @@ public class Util {
public static Textbox bind(Textbox textBox, Getter<String> getter) { public static Textbox bind(Textbox textBox, Getter<String> getter) {
textBox.setValue(getter.get()); textBox.setValue(getter.get());
textBox.setDisabled(true); textBox.setDisabled(true);
return textBox; return textBox;
} }
@ -323,16 +323,15 @@ public class Util {
* Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be
* used to get the value that is going to be showed in the {@link Textbox}. * used to get the value that is going to be showed in the {@link Textbox}.
* *
* @param textBox * @param comboBox
* The {@link Textbox} to be bound * The {@link Combobox} to be bound
* @param getter * @param getter
* The {@link Getter} interface that will implement a get method. * The {@link Getter} interface that will implement a get method.
* @return The {@link Textbox} bound * @return The {@link Combobox} bound
*/ */
public static Combobox bind(Combobox comboBox, Getter<Comboitem> getter) { public static Combobox bind(Combobox comboBox, Getter<Comboitem> getter) {
comboBox.setSelectedItem(getter.get()); comboBox.setSelectedItem(getter.get());
comboBox.setDisabled(true); comboBox.setDisabled(true);
return comboBox; return comboBox;
} }
@ -340,13 +339,14 @@ public class Util {
* Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be * Binds a {@link Textbox} with a {@link Getter}. The {@link Getter} will be
* used to get the value that is going to be showed in the {@link Textbox}. * used to get the value that is going to be showed in the {@link Textbox}.
* The {@link Setter} will be used to store the value inserted by the user in the {@link Textbox}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Textbox}.
* @param textBox *
* The {@link Textbox} to be bound * @param comboBox
* The {@link Combobox} to be bound
* @param getter * @param getter
* The {@link Getter} interface that will implement a get method. * The {@link Getter} interface that will implement a get method.
* @param setter * @param setter
* The {@link Setter} interface that will implement a set method. * The {@link Setter} interface that will implement a set method.
* @return The {@link Textbox} bound * @return The {@link Combobox} bound
*/ */
public static Combobox bind(final Combobox comboBox, public static Combobox bind(final Combobox comboBox,
final Getter<Comboitem> getter, final Getter<Comboitem> getter,
@ -455,7 +455,7 @@ public class Util {
* Binds a {@link Timebox} with a {@link Getter}. * Binds a {@link Timebox} with a {@link Getter}.
* The {@link Getter} will be used to get the value that is going to be showed in the {@link Timebox}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Timebox}.
* *
* @param dateBox * @param timeBox
* The {@link Timebox} to be bound * The {@link Timebox} to be bound
* @param getter * @param getter
* The {@link Getter} interface that will implement a get method. * The {@link Getter} interface that will implement a get method.
@ -549,7 +549,6 @@ public class Util {
public static Checkbox bind(final Checkbox checkBox, final Getter<Boolean> getter) { public static Checkbox bind(final Checkbox checkBox, final Getter<Boolean> getter) {
checkBox.setChecked(getter.get()); checkBox.setChecked(getter.get());
checkBox.setDisabled(true); checkBox.setDisabled(true);
return checkBox; return checkBox;
} }
@ -558,7 +557,7 @@ public class Util {
* The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}.
* The {@link Setter} will be used to store the value inserted by the user in the {@link Checkbox}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Checkbox}.
* *
* @param decimalBox * @param checkBox
* @param getter * @param getter
* The {@link Getter} interface that will implement a get method. * The {@link Getter} interface that will implement a get method.
* @param setter * @param setter
@ -579,7 +578,7 @@ public class Util {
* Binds a {@link Checkbox} with a {@link Getter}. * Binds a {@link Checkbox} with a {@link Getter}.
* The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Checkbox}.
* *
* @param Radio * @param radio
* The {@link Radio} to be bound * The {@link Radio} to be bound
* @param getter * @param getter
* The {@link Getter} interface that will implement a get method. * The {@link Getter} interface that will implement a get method.
@ -588,7 +587,6 @@ public class Util {
public static Radio bind(final Radio radio, final Getter<Boolean> getter) { public static Radio bind(final Radio radio, final Getter<Boolean> getter) {
radio.setSelected(getter.get()); radio.setSelected(getter.get());
radio.setDisabled(true); radio.setDisabled(true);
return radio; return radio;
} }
@ -597,7 +595,7 @@ public class Util {
* The {@link Getter} will be used to get the value that is going to be showed in the {@link Radio}. * The {@link Getter} will be used to get the value that is going to be showed in the {@link Radio}.
* The {@link Setter} will be used to store the value inserted by the user in the {@link Radio}. * The {@link Setter} will be used to store the value inserted by the user in the {@link Radio}.
* *
* @param decimalBox * @param radio
* The {@link Radio} to be bound * The {@link Radio} to be bound
* @param getter * @param getter
* he {@link Getter} interface that will implement a get method. * he {@link Getter} interface that will implement a get method.
@ -629,7 +627,6 @@ public class Util {
public static Bandbox bind(Bandbox bandBox, Getter<String> getter) { public static Bandbox bind(Bandbox bandBox, Getter<String> getter) {
bandBox.setValue(getter.get()); bandBox.setValue(getter.get());
bandBox.setDisabled(true); bandBox.setDisabled(true);
return bandBox; return bandBox;
} }
@ -663,7 +660,7 @@ public class Util {
* Creates an edit button with class and icon already set. * Creates an edit button with class and icon already set.
* *
* @param eventListener * @param eventListener
* A event listener for {@link Events.ON_CLICK} * A event listener for {@link Events#ON_CLICK}
* @return An edit {@link Button} * @return An edit {@link Button}
*/ */
public static Button createEditButton(EventListener eventListener) { public static Button createEditButton(EventListener eventListener) {
@ -682,7 +679,7 @@ public class Util {
* Creates a remove button with class and icon already set. * Creates a remove button with class and icon already set.
* *
* @param eventListener * @param eventListener
* A event listener for {@link Events.ON_CLICK} * A event listener for {@link Events#ON_CLICK}
* @return A remove {@link Button} * @return A remove {@link Button}
*/ */
public static Button createRemoveButton(EventListener eventListener) { public static Button createRemoveButton(EventListener eventListener) {
@ -784,10 +781,9 @@ public class Util {
/** /**
* Gets money format for a {@link Decimalbox} using 2 figures for the * Gets money format for a {@link Decimalbox} using 2 figures for the
* decimal part and concatenating the currency symbol * decimal part and concatenating the currency symbol.
* *
* @return Format for a {@link Decimalbox} <code>###.##</code> plus currency * @return Format for a {@link Decimalbox} <code>###.##</code> plus currency symbol
* symbol
*/ */
public static String getMoneyFormat() { public static String getMoneyFormat() {
return "###.## " + escapeDecimalFormatSpecialChars(getCurrencySymbol()); return "###.## " + escapeDecimalFormatSpecialChars(getCurrencySymbol());
@ -919,8 +915,7 @@ public class Util {
} }
/** /**
* Format specific <code>time</code> using the {@link DateFormat#SHORT} * Format specific <code>time</code> using the {@link DateFormat#SHORT} format and showing only the time.
* format and showing only the time.
*/ */
public static String formatTime(LocalTime time) { public static String formatTime(LocalTime time) {
return time == null ? "" : formatTime(time.toDateTimeToday().toDate()); return time == null ? "" : formatTime(time.toDateTimeToday().toDate());
@ -940,7 +935,8 @@ public class Util {
.getFile() .getFile()
.getPath()); .getPath());
} catch (IOException ignored) {} } catch (IOException ignored) {
}
} }
/** /**
@ -962,7 +958,8 @@ public class Util {
.getFile() .getFile()
.getPath()); .getPath());
} }
} catch (IOException ignored) {} } catch (IOException ignored) {
}
} }
} }

View file

@ -45,6 +45,7 @@ public abstract class Finder implements IFinder {
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
@Override
public SimpleListModelExt getModel() { public SimpleListModelExt getModel() {
return new SimpleListModelExt(getAll()); return new SimpleListModelExt(getAll());
} }
@ -73,13 +74,11 @@ public abstract class Finder implements IFinder {
* Use _toString() to indicate how an object is shown in the list of matching elements. * Use _toString() to indicate how an object is shown in the list of matching elements.
*/ */
private class ComboWorkerRenderer implements ComboitemRenderer { private class ComboWorkerRenderer implements ComboitemRenderer {
@Override @Override
public void render(Comboitem item, Object data, int i) { public void render(Comboitem item, Object data, int i) {
item.setLabel(_toString(data)); item.setLabel(_toString(data));
item.setValue(data); item.setValue(data);
} }
} }
/** /**
@ -102,8 +101,8 @@ public abstract class Finder implements IFinder {
/** /**
* Searches for value among all model entries. * Searches for value among all model entries.
* *
* entryMatchesText method is used to check if an entry matches or not. * {@link #entryMatchesText(String, String)}is used to check if an entry matches or not.
* Overwrite this method to provide your own behaviour * Overwrite this method to provide your own behaviour.
* *
* @param value * @param value
* String to search * String to search
@ -120,10 +119,10 @@ public abstract class Finder implements IFinder {
final LinkedList data = new LinkedList(); final LinkedList data = new LinkedList();
for (int i = 0; i < getSize(); i++) { for (int i = 0; i < getSize(); i++) {
if ( idx.equals("") || entryMatchesText(_toString(getElementAt(i)), idx) ) { if ( "".equals(idx) || entryMatchesText(_toString(getElementAt(i)), idx) ) {
data.add(getElementAt(i)); data.add(getElementAt(i));
if ( --nRows <= 0 ) { if ( --nRows <= 0 ) {
break; // done break; // Done
} }
} }
} }

View file

@ -28,7 +28,7 @@ import org.zkoss.zk.ui.Component;
import org.zkoss.zkplus.databind.TypeConverter; import org.zkoss.zkplus.databind.TypeConverter;
/** /**
* Converter for the type java.util.Date * Converter for the type {@link Date}.
* *
* @author Diego Pino Garcia <dpino@igalia.com> * @author Diego Pino Garcia <dpino@igalia.com>
* *

View file

@ -50,7 +50,7 @@ import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer; import org.zkoss.zul.RowRenderer;
/** /**
* Controller for CRUD actions over a {@link ResourcesCostCategoryAssignment} * Controller for CRUD actions over a {@link ResourcesCostCategoryAssignment}.
* *
* @author Jacobo Aragunde Perez <jaragunde@igalia.com> * @author Jacobo Aragunde Perez <jaragunde@igalia.com>
*/ */
@ -67,8 +67,10 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
public void doAfterCompose(Component comp) throws Exception { public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp); super.doAfterCompose(comp);
if ( resourcesCostCategoryAssignmentModel == null ) {
resourcesCostCategoryAssignmentModel = resourcesCostCategoryAssignmentModel =
(IResourcesCostCategoryAssignmentModel) SpringUtil.getBean("resourcesCostCategoryAssignmentModel"); (IResourcesCostCategoryAssignmentModel) SpringUtil.getBean("resourcesCostCategoryAssignmentModel");
}
comp.setAttribute("assignmentController", this, true); comp.setAttribute("assignmentController", this, true);
this.listResourcesCostCategoryAssignments = (Grid) comp.getFellowIfAny("listResourcesCostCategoryAssignments"); this.listResourcesCostCategoryAssignments = (Grid) comp.getFellowIfAny("listResourcesCostCategoryAssignments");
@ -90,12 +92,11 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
private CostCategory getCostCategory(Row listitem) { private CostCategory getCostCategory(Row listitem) {
ResourcesCostCategoryAssignment assignment = listitem.getValue(); ResourcesCostCategoryAssignment assignment = listitem.getValue();
return assignment.getCostCategory(); return assignment.getCostCategory();
} }
/** /**
* Append a Autocomplete @{link CostCategory} to row * Append a Autocomplete @{link CostCategory} to row.
* *
* @param row * @param row
*/ */
@ -130,15 +131,17 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
} }
public void confirmRemove(ResourcesCostCategoryAssignment assignment) { public void confirmRemove(ResourcesCostCategoryAssignment assignment) {
int status = Messagebox.show(_("Confirm deleting this hour cost. Are you sure?"), _("Delete"), int status = Messagebox.show(
_("Confirm deleting this hour cost. Are you sure?"), _("Delete"),
Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION); Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION);
if (Messagebox.OK == status) { if (Messagebox.OK == status) {
removeCostCategoryAssignment(assignment); removeCostCategoryAssignment(assignment);
} }
} }
/** /**
* Append a delete {@link Button} to {@link Row} * Append a delete {@link Button} to {@link Row}.
* *
* @param row * @param row
*/ */
@ -147,6 +150,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
delete.setHoverImage("/common/img/ico_borrar.png"); delete.setHoverImage("/common/img/ico_borrar.png");
delete.setSclass("icono"); delete.setSclass("icono");
delete.setTooltiptext(_("Delete")); delete.setTooltiptext(_("Delete"));
delete.addEventListener(Events.ON_CLICK, new EventListener() { delete.addEventListener(Events.ON_CLICK, new EventListener() {
@Override @Override
public void onEvent(Event event) { public void onEvent(Event event) {
@ -157,7 +161,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
} }
/** /**
* Append a Datebox "init date" to row * Append a Datebox "init date" to row.
* *
* @param row * @param row
*/ */
@ -183,32 +187,31 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
} }
/** /**
* Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment} * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment}.
* *
* @param dateBoxInitDate * @param dateBoxInitDate
* @param hourCost * @param assignment
*/ */
private void bindDateboxInitDate(final Datebox dateBoxInitDate, private void bindDateboxInitDate(final Datebox dateBoxInitDate, final ResourcesCostCategoryAssignment assignment) {
final ResourcesCostCategoryAssignment assignment) {
Util.bind(dateBoxInitDate, new Util.Getter<Date>() {
Util.bind(
dateBoxInitDate,
new Util.Getter<Date>() {
@Override @Override
public Date get() { public Date get() {
LocalDate dateTime = assignment.getInitDate(); LocalDate dateTime = assignment.getInitDate();
if (dateTime != null) { /* TODO resolve deprecated */
return new Date(dateTime.getYear()-1900, return dateTime != null
dateTime.getMonthOfYear()-1,dateTime.getDayOfMonth()); ? new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1, dateTime.getDayOfMonth())
: null;
} }
return null; },
} new Util.Setter<Date>() {
}, new Util.Setter<Date>() {
@Override @Override
public void set(Date value) { public void set(Date value) {
if (value != null) { if (value != null) {
assignment.setInitDate(new LocalDate(value.getYear()+1900, /* TODO resolve deprecated */
value.getMonth()+1,value.getDate())); assignment.setInitDate(new LocalDate(value.getYear() + 1900, value.getMonth() + 1,value.getDate()));
} }
else { else {
assignment.setInitDate(null); assignment.setInitDate(null);
@ -218,7 +221,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
} }
/** /**
* Append a Datebox "end date" to row * Append a Datebox "end date" to row.
* *
* @param row * @param row
*/ */
@ -226,6 +229,7 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
Datebox endDateBox = new Datebox(); Datebox endDateBox = new Datebox();
bindDateboxEndDate(endDateBox, row.getValue()); bindDateboxEndDate(endDateBox, row.getValue());
LocalDate initDate = ((ResourcesCostCategoryAssignment)row.getValue()).getInitDate(); LocalDate initDate = ((ResourcesCostCategoryAssignment)row.getValue()).getInitDate();
if (initDate != null) { if (initDate != null) {
endDateBox.setConstraint("after " + endDateBox.setConstraint("after " +
String.format("%04d", initDate.getYear()) + String.format("%04d", initDate.getYear()) +
@ -236,27 +240,25 @@ public class ResourcesCostCategoryAssignmentController extends GenericForwardCom
} }
/** /**
* Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment} * Binds Datebox "init date" to the corresponding attribute of a {@link ResourcesCostCategoryAssignment}.
* *
* @param dateBoxInitDate * @param dateBoxEndDate
* @param hourCost * @param assignment
*/ */
private void bindDateboxEndDate(final Datebox dateBoxEndDate, private void bindDateboxEndDate(final Datebox dateBoxEndDate, final ResourcesCostCategoryAssignment assignment) {
final ResourcesCostCategoryAssignment assignment) { Util.bind(
Util.bind(dateBoxEndDate, new Util.Getter<Date>() { dateBoxEndDate,
new Util.Getter<Date>() {
@Override @Override
public Date get() { public Date get() {
LocalDate dateTime = assignment.getEndDate(); LocalDate dateTime = assignment.getEndDate();
if (dateTime != null) { /* TODO resolve deprecated */
return new Date(dateTime.getYear()-1900, return dateTime != null
dateTime.getMonthOfYear()-1,dateTime.getDayOfMonth()); ? new Date(dateTime.getYear() - 1900, dateTime.getMonthOfYear() - 1,dateTime.getDayOfMonth())
: null;
} }
},
return null; new Util.Setter<Date>() {
}
}, new Util.Setter<Date>() {
@Override @Override
public void set(Date value) { public void set(Date value) {
if (value != null) { if (value != null) {

View file

@ -32,16 +32,14 @@ import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
/** /**
* Model for UI operations related to CostStatus in Dashboard view.
*
* FIXME: This Model contains several operations for calculating 'Earned Value' measures related with cost.
* The code for calculating the basic measures: BCWP, ACWP and BCWS is copied from {@link OrderPlanningModel}.
* At this moment this code cannot be reused as it's coupled with the logic for displaying the 'Earned Value' chart.
* We may consider to refactor this code in the future.
*
* @author Diego Pino García <ltilve@igalia.com> * @author Diego Pino García <ltilve@igalia.com>
*
* Model for UI operations related to CostStatus in Dashboard view
*
* FIXME: This Model contains several operations for calculating 'Earned
* Value' measures related with cost. The code for calculating the basic
* measures: BCWP, ACWP and BCWS is copied from
* {@link OrderPlanningModel}. At this moment this code cannot be reused
* as it's coupled with the logic for displaying the 'Earned Value'
* chart. We may consider to refactor this code in the future.
*/ */
@Component @Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
@ -53,7 +51,6 @@ public class CostStatusModel implements ICostStatusModel {
private Order order; private Order order;
public CostStatusModel() { public CostStatusModel() {
} }
@Override @Override
@ -64,8 +61,7 @@ public class CostStatusModel implements ICostStatusModel {
@Override @Override
public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost, BigDecimal actualCost) { public BigDecimal getCostPerformanceIndex(BigDecimal budgetedCost, BigDecimal actualCost) {
return earnedValueCalculator.getCostPerformanceIndex(budgetedCost, return earnedValueCalculator.getCostPerformanceIndex(budgetedCost, actualCost);
actualCost);
} }
@Override @Override
@ -75,8 +71,7 @@ public class CostStatusModel implements ICostStatusModel {
@Override @Override
public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion, BigDecimal costPerformanceIndex) { public BigDecimal getEstimateAtCompletion(BigDecimal budgetAtCompletion, BigDecimal costPerformanceIndex) {
return earnedValueCalculator.getEstimateAtCompletion( return earnedValueCalculator.getEstimateAtCompletion(budgetAtCompletion, costPerformanceIndex);
budgetAtCompletion, costPerformanceIndex);
} }
@Override @Override

View file

@ -2,6 +2,7 @@ package org.libreplan.web.dashboard;
import org.libreplan.business.orders.entities.Order; import org.libreplan.business.orders.entities.Order;
import org.libreplan.business.orders.entities.OrderStatusEnum;
import org.libreplan.web.orders.IOrderModel; import org.libreplan.web.orders.IOrderModel;
import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.Scope;
@ -24,14 +25,15 @@ import java.util.List;
* *
* @author Vova Perebykivskyi <vova@libreplan-enterprise.com> * @author Vova Perebykivskyi <vova@libreplan-enterprise.com>
*/ */
@org.springframework.stereotype.Component @org.springframework.stereotype.Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class DashboardControllerGlobal extends GenericForwardComposer { public class DashboardControllerGlobal extends GenericForwardComposer {
// TODO enumns instead of numbers ( 0, 1, 2, 3, ... )
// TODO 1 list instead of 8 // TODO 1 list instead of 8
// TODO insert Label only in needed Cell // TODO insert Label only in needed Cell
// ( is it possible at all? Seems that we need to make own Grid )
// Because we cannot createCell at selected row-index, column-index
private IOrderModel orderModel; private IOrderModel orderModel;
@ -61,7 +63,11 @@ public class DashboardControllerGlobal extends GenericForwardComposer {
public void doAfterCompose(Component component) throws Exception { public void doAfterCompose(Component component) throws Exception {
super.doAfterCompose(component); super.doAfterCompose(component);
component.setAttribute("dashboardControllerGlobal", this, true); component.setAttribute("dashboardControllerGlobal", this, true);
if ( orderModel == null ) {
orderModel = (IOrderModel) SpringUtil.getBean("orderModel"); orderModel = (IOrderModel) SpringUtil.getBean("orderModel");
}
fillOrderLists(); fillOrderLists();
setupPipelineGrid(); setupPipelineGrid();
showStoredColumn(); showStoredColumn();
@ -128,7 +134,8 @@ public class DashboardControllerGlobal extends GenericForwardComposer {
onHoldOrders.size(), onHoldOrders.size(),
finishedOrders.size(), finishedOrders.size(),
cancelledOrders.size(), cancelledOrders.size(),
storedOrders.size() }; storedOrders.size()
};
int rowsCount = findMaxList(sizes); int rowsCount = findMaxList(sizes);
@ -146,18 +153,18 @@ public class DashboardControllerGlobal extends GenericForwardComposer {
pipelineGrid.appendChild(rows); pipelineGrid.appendChild(rows);
// Fill data into first column and so on with other columns divided by Enter in code // Fill data into first column and so on with other columns divided by Enter in code
processList(preSalesOrders, 0); processList(preSalesOrders, OrderStatusEnum.PRE_SALES);
processList(offeredOrders, 1); processList(offeredOrders, OrderStatusEnum.OFFERED);
processList(outsourcedOrders, 2); processList(outsourcedOrders, OrderStatusEnum.OUTSOURCED);
processList(acceptedOrders, 3); processList(acceptedOrders, OrderStatusEnum.ACCEPTED);
processList(startedOrders, 4); processList(startedOrders, OrderStatusEnum.STARTED);
processList(onHoldOrders, 5); processList(onHoldOrders, OrderStatusEnum.ON_HOLD);
processList(finishedOrders, 6); processList(finishedOrders, OrderStatusEnum.FINISHED);
processList(cancelledOrders, 7); processList(cancelledOrders, OrderStatusEnum.CANCELLED);
processList(storedOrders, 8); processList(storedOrders, OrderStatusEnum.STORED);
} }
private void processList(List<Order> currentList, int index) { private void processList(List<Order> currentList, OrderStatusEnum orderStatus) {
if ( !currentList.isEmpty() ) { if ( !currentList.isEmpty() ) {
for (int i = 0; i < currentList.size(); i++) { for (int i = 0; i < currentList.size(); i++) {
@ -165,14 +172,14 @@ public class DashboardControllerGlobal extends GenericForwardComposer {
String outputInit = getOrderInitDate(currentList.get(i)); String outputInit = getOrderInitDate(currentList.get(i));
String outputDeadline = getOrderDeadline(currentList.get(i)); String outputDeadline = getOrderDeadline(currentList.get(i));
( (Label) pipelineGrid.getCell(i, index) ).setValue(currentList.get(i).getName()); ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setValue(currentList.get(i).getName());
String tooltipText = "Start date: " + outputInit + String tooltipText = "Start date: " + outputInit +
"\n" + "End date: " + outputDeadline + "\n" + "End date: " + outputDeadline +
"\n" + "Progress: " + currentList.get(i).getAdvancePercentage() + " %"; "\n" + "Progress: " + currentList.get(i).getAdvancePercentage() + " %";
( (Label) pipelineGrid.getCell(i, index) ).setTooltiptext(tooltipText); ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setTooltiptext(tooltipText);
( (Label) pipelineGrid.getCell(i, index) ).setClass("label-highlight"); ( (Label) pipelineGrid.getCell(i, orderStatus.getIndex()) ).setClass("label-highlight");
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -142,8 +142,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
private Scenario master; private Scenario master;
private Map<LimitingResourceQueueElement, HashSet<LimitingResourceQueueDependency>> toBeSavedDependencies = private Map<LimitingResourceQueueElement, HashSet<LimitingResourceQueueDependency>> toBeSavedDependencies = new HashMap<>();
new HashMap<>();
private boolean checkAllocationIsAppropriative = true; private boolean checkAllocationIsAppropriative = true;
@ -191,7 +190,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
private boolean isEarlier(LimitingResourceQueueElement arg1, LimitingResourceQueueElement arg2) { private boolean isEarlier(LimitingResourceQueueElement arg1, LimitingResourceQueueElement arg2) {
return (arg1.getStartDate().isBefore(arg2.getStartDate())); return arg1.getStartDate().isBefore(arg2.getStartDate());
} }
private LimitingResourceQueueElement getFirstLimitingResourceQueueElement(LimitingResourceQueue queue) { private LimitingResourceQueueElement getFirstLimitingResourceQueueElement(LimitingResourceQueue queue) {
@ -199,7 +198,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
private LimitingResourceQueueElement getFirstChild(SortedSet<LimitingResourceQueueElement> elements) { private LimitingResourceQueueElement getFirstChild(SortedSet<LimitingResourceQueueElement> elements) {
return (elements.isEmpty()) ? null : elements.iterator().next(); return elements.isEmpty() ? null : elements.iterator().next();
} }
/** /**
@ -233,8 +232,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
private void initializeTask(Task task) { private void initializeTask(Task task) {
if ( hasResourceAllocation(task) ) { if ( hasResourceAllocation(task) ) {
ResourceAllocation<?> resourceAllocation = ResourceAllocation<?> resourceAllocation = initializeResourceAllocationIfNecessary(getResourceAllocation(task));
initializeResourceAllocationIfNecessary(getResourceAllocation(task));
task.setResourceAllocation(resourceAllocation); task.setResourceAllocation(resourceAllocation);
} }
@ -275,8 +273,10 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
} }
// FIXME: Needed to fetch order.name in QueueComponent.composeTooltiptext. /**
// Try to replace it with a HQL query instead of iterating all the way up through order * FIXME: Needed to fetch order.name in QueueComponent.composeTooltiptext
* Try to replace it with a HQL query instead of iterating all the way up through order.
*/
private void initializeRootOrder(Task task) { private void initializeRootOrder(Task task) {
Hibernate.initialize(task.getOrderElement()); Hibernate.initialize(task.getOrderElement());
OrderElement order = task.getOrderElement(); OrderElement order = task.getOrderElement();
@ -318,21 +318,23 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
private ResourceAllocation<?> initializeResourceAllocationIfNecessary(ResourceAllocation<?> resourceAllocation) { private ResourceAllocation<?> initializeResourceAllocationIfNecessary(ResourceAllocation<?> resourceAllocation) {
if ( resourceAllocation instanceof HibernateProxy ) { ResourceAllocation<?> newResourceAllocation = resourceAllocation;
resourceAllocation = (ResourceAllocation<?>) ((HibernateProxy) resourceAllocation) if ( newResourceAllocation instanceof HibernateProxy ) {
newResourceAllocation = (ResourceAllocation<?>) ((HibernateProxy) newResourceAllocation)
.getHibernateLazyInitializer().getImplementation(); .getHibernateLazyInitializer().getImplementation();
if ( resourceAllocation instanceof GenericResourceAllocation ) { if ( newResourceAllocation instanceof GenericResourceAllocation ) {
GenericResourceAllocation generic = (GenericResourceAllocation) resourceAllocation; GenericResourceAllocation generic = (GenericResourceAllocation) newResourceAllocation;
initializeCriteria(generic.getCriterions()); initializeCriteria(generic.getCriterions());
} }
Hibernate.initialize(resourceAllocation.getAssignments()); Hibernate.initialize(newResourceAllocation.getAssignments());
Hibernate.initialize(resourceAllocation.getLimitingResourceQueueElement()); Hibernate.initialize(newResourceAllocation.getLimitingResourceQueueElement());
} }
return resourceAllocation; return newResourceAllocation;
} }
private void initializeCriteria(Set<Criterion> criteria) { private void initializeCriteria(Set<Criterion> criteria) {
@ -354,7 +356,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
for (LimitingResourceQueue each : queues) { for (LimitingResourceQueue each : queues) {
initializeLimitingResourceQueue(each); initializeLimitingResourceQueue(each);
} }
return queues; return queues;
} }
@ -392,10 +393,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public boolean userCanRead(Order order, String loginName) { public boolean userCanRead(Order order, String loginName) {
if ( SecurityUtils.isSuperuserOrUserInRoles( if ( SecurityUtils.isSuperuserOrUserInRoles(UserRole.ROLE_READ_ALL_PROJECTS, UserRole.ROLE_EDIT_ALL_PROJECTS)) {
UserRole.ROLE_READ_ALL_PROJECTS,
UserRole.ROLE_EDIT_ALL_PROJECTS)) {
return true; return true;
} }
@ -412,7 +410,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
// This case shouldn't happen, because it would mean that there isn't a logged user // This case shouldn't happen, because it would mean that there isn't a logged user
// anyway, if it happened we don't allow the user to pass. // anyway, if it happened we don't allow the user to pass.
} }
return false; return false;
} }
@ -460,16 +457,15 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
/** /**
* After an allocation dependencies might be broken, this method unschedules * After an allocation dependencies might be broken, this method unscheduled
* elements affected by an allocation and reschedule them again in * elements affected by an allocation and reschedule them again in topological order, so dependencies are satisfied.
* topological order, so dependencies are satisfied.
* *
* If the allocation was appropriative it also allocates those elements that * If the allocation was appropriative it also allocates those elements that
* might be unscheduled before due to the appropriative allocation. * might be unscheduled before due to the appropriative allocation.
* *
* @param allocation * @param allocation
* @param moved * @param moved
* @return * @return {@link Collection<? extends LimitingResourceQueueElement>}
*/ */
private Collection<? extends LimitingResourceQueueElement> rescheduleAffectedElementsToSatisfyDependencies( private Collection<? extends LimitingResourceQueueElement> rescheduleAffectedElementsToSatisfyDependencies(
AllocationSpec allocation, List<LimitingResourceQueueElement> moved) { AllocationSpec allocation, List<LimitingResourceQueueElement> moved) {
@ -597,7 +593,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
for (Edge each : edges) { for (Edge each : edges) {
result = DateAndHour.max(result, calculateStart(previous, each.type)); result = DateAndHour.max(result, calculateStart(previous, each.type));
} }
return result; return result;
} }
@ -634,8 +629,7 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
/** /**
* @return <code>null</code> if no suitable gap found; the allocation found * @return <code>null</code> if no suitable gap found; the allocation found otherwise
* otherwise
*/ */
private AllocationSpec insertAtGap(InsertionRequirements requirements) { private AllocationSpec insertAtGap(InsertionRequirements requirements) {
return doAppropriativeIfNecessary(findAllocationSpecFor(requirements), requirements); return doAppropriativeIfNecessary(findAllocationSpecFor(requirements), requirements);
@ -673,21 +667,16 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
if ( checkAllocationIsAppropriative() && requirements.isAppropiativeAllocation(allocation) ) { if ( checkAllocationIsAppropriative() && requirements.isAppropiativeAllocation(allocation) ) {
return doAppropriativeAllocation(requirements); return doAppropriativeAllocation(requirements);
} }
return allocation; return allocation;
} }
return null; return null;
} }
private AllocationSpec insertAtGap(InsertionRequirements requirements, LimitingResourceQueue queue) { private AllocationSpec insertAtGap(InsertionRequirements requirements, LimitingResourceQueue queue) {
AllocationSpec allocationStillNotDone = findAllocationSpecForInQueue(requirements, queue); return doAppropriativeIfNecessary(findAllocationSpecForInQueue(requirements, queue), requirements);
return doAppropriativeIfNecessary(allocationStillNotDone, requirements);
} }
private AllocationSpec findAllocationSpecForInQueue(InsertionRequirements requirements, private AllocationSpec findAllocationSpecForInQueue(InsertionRequirements requirements, LimitingResourceQueue queue) {
LimitingResourceQueue queue) {
List<GapOnQueue> potentiallyValidGapsFor = new ArrayList<>(); List<GapOnQueue> potentiallyValidGapsFor = new ArrayList<>();
@ -894,7 +883,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
} }
private void addLimitingResourceQueueElementIfNeeded(LimitingResourceQueue queue, LimitingResourceQueueElement element) { private void addLimitingResourceQueueElementIfNeeded(LimitingResourceQueue queue, LimitingResourceQueueElement element) {
if ( element.getLimitingResourceQueue() == null ) { if ( element.getLimitingResourceQueue() == null ) {
queuesState.assignedToQueue(element, queue); queuesState.assignedToQueue(element, queue);
} }
@ -1045,7 +1033,6 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
public LimitingResourceQueueElement unschedule(LimitingResourceQueueElement queueElement) { public LimitingResourceQueueElement unschedule(LimitingResourceQueueElement queueElement) {
queuesState.unassingFromQueue(queueElement); queuesState.unassingFromQueue(queueElement);
markAsModified(queueElement); markAsModified(queueElement);
return queueElement; return queueElement;
} }
@ -1110,14 +1097,14 @@ public class LimitingResourceQueueModel implements ILimitingResourceQueueModel {
@Override @Override
public Set<LimitingResourceQueueElement> appropriativeAllocation( public Set<LimitingResourceQueueElement> appropriativeAllocation(
LimitingResourceQueueElement _element, LimitingResourceQueueElement limitingResourceQueueElement,
LimitingResourceQueue _queue, LimitingResourceQueue limitingResourceQueue,
DateAndHour allocationTime) { DateAndHour allocationTime) {
Set<LimitingResourceQueueElement> result = new HashSet<>(); Set<LimitingResourceQueueElement> result = new HashSet<>();
LimitingResourceQueue queue = queuesState.getEquivalent(_queue); LimitingResourceQueue queue = queuesState.getEquivalent(limitingResourceQueue);
LimitingResourceQueueElement element = queuesState.getEquivalent(_element); LimitingResourceQueueElement element = queuesState.getEquivalent(limitingResourceQueueElement);
InsertionRequirements requirements = queuesState.getRequirementsFor(element, allocationTime); InsertionRequirements requirements = queuesState.getRequirementsFor(element, allocationTime);

View file

@ -110,12 +110,7 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
private final LimitingResourceQueueElementsRenderer limitingResourceQueueElementsRenderer = private final LimitingResourceQueueElementsRenderer limitingResourceQueueElementsRenderer =
new LimitingResourceQueueElementsRenderer(); new LimitingResourceQueueElementsRenderer();
public LimitingResourcesController() public LimitingResourcesController() {
{}
public void add(IToolbarCommand... commands) {
Validate.noNullElements(commands);
this.commands.addAll(Arrays.asList(commands));
} }
@Override @Override
@ -123,6 +118,11 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
super.doAfterCompose(comp); super.doAfterCompose(comp);
} }
public void add(IToolbarCommand... commands) {
Validate.noNullElements(commands);
this.commands.addAll(Arrays.asList(commands));
}
public void reload() { public void reload() {
transactionService.runOnReadOnlyTransaction(new IOnTransaction<Void>() { transactionService.runOnReadOnlyTransaction(new IOnTransaction<Void>() {
@ -133,7 +133,7 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
} }
private void reloadInTransaction() { private void reloadInTransaction() {
// FIXME: Temporary fix. // FIXME: Temporary fix
// It seems the page was already rendered, so clear it all as it's going to be rendered again // It seems the page was already rendered, so clear it all as it's going to be rendered again
self.getChildren().clear(); self.getChildren().clear();
@ -196,12 +196,14 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
} }
private TimeTracker buildTimeTracker() { private TimeTracker buildTimeTracker() {
return timeTracker = new TimeTracker( timeTracker = new TimeTracker(
limitingResourceQueueModel.getViewInterval(), limitingResourceQueueModel.getViewInterval(),
ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_THREE,
SeveralModifiers.create(), SeveralModifiers.create(),
SeveralModifiers.create(BankHolidaysMarker.create(getDefaultCalendar())), SeveralModifiers.create(BankHolidaysMarker.create(getDefaultCalendar())),
self); self);
return timeTracker;
} }
private BaseCalendar getDefaultCalendar() { private BaseCalendar getDefaultCalendar() {
@ -222,7 +224,6 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
* @return {@link List<LimitingResourceQueueElementDTO>} * @return {@link List<LimitingResourceQueueElementDTO>}
*/ */
public List<LimitingResourceQueueElementDTO> getUnassignedLimitingResourceQueueElements() { public List<LimitingResourceQueueElementDTO> getUnassignedLimitingResourceQueueElements() {
// TODO check it
return limitingResourceQueueModel return limitingResourceQueueModel
.getUnassignedLimitingResourceQueueElements() .getUnassignedLimitingResourceQueueElements()
.stream() .stream()
@ -528,7 +529,6 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
public boolean moveTask(LimitingResourceQueueElement element) { public boolean moveTask(LimitingResourceQueueElement element) {
showManualAllocationWindow(element); showManualAllocationWindow(element);
return getManualAllocationWindowStatus() == Messagebox.OK; return getManualAllocationWindowStatus() == Messagebox.OK;
} }
@ -560,9 +560,7 @@ public class LimitingResourcesController extends GenericForwardComposer<org.zkos
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Checkbox getAutoQueueing(Row row) { private Checkbox getAutoQueueing(Row row) {
List<org.zkoss.zk.ui.Component> children = row.getChildren(); return (Checkbox) row.getChildren().get(0);
return (Checkbox) children.get(0);
} }
public void assignAllSelectedElements() { public void assignAllSelectedElements() {

View file

@ -186,6 +186,7 @@ public class QueueComponent extends XulElement implements AfterCompose {
if ( each.getEndDate().toDateTimeAtStartOfDay().isAfter(interval.getStart().toDateTimeAtStartOfDay()) && if ( each.getEndDate().toDateTimeAtStartOfDay().isAfter(interval.getStart().toDateTimeAtStartOfDay()) &&
each.getStartDate().toDateTimeAtStartOfDay() each.getStartDate().toDateTimeAtStartOfDay()
.isBefore(interval.getFinish().toDateTimeAtStartOfDay()) ) { .isBefore(interval.getFinish().toDateTimeAtStartOfDay()) ) {
result.add(createQueueTask(datesMapper, each)); result.add(createQueueTask(datesMapper, each));
} }
@ -246,7 +247,7 @@ public class QueueComponent extends XulElement implements AfterCompose {
* Returns end date considering % of task completion. * Returns end date considering % of task completion.
* *
* @param element * @param element
* @return * @return {@link DateAndHour}
*/ */
private static DateAndHour getAdvanceEndDate(LimitingResourceQueueElement element) { private static DateAndHour getAdvanceEndDate(LimitingResourceQueueElement element) {
int hoursWorked = 0; int hoursWorked = 0;
@ -279,9 +280,8 @@ public class QueueComponent extends XulElement implements AfterCompose {
} }
private static int estimatedWorkedHours(Integer totalHours, BigDecimal percentageWorked) { private static int estimatedWorkedHours(Integer totalHours, BigDecimal percentageWorked) {
boolean bool = totalHours != null && percentageWorked != null; boolean condition = totalHours != null && percentageWorked != null;
return condition ? percentageWorked.multiply(new BigDecimal(totalHours)).intValue() : 0;
return bool ? percentageWorked.multiply(new BigDecimal(totalHours)).intValue() : 0;
} }
private static QueueTask createDivForElement(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) { private static QueueTask createDivForElement(IDatesMapper datesMapper, LimitingResourceQueueElement queueElement) {
@ -472,7 +472,6 @@ public class QueueComponent extends XulElement implements AfterCompose {
return each; return each;
} }
} }
return null; return null;
} }

View file

@ -153,18 +153,14 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl
@Override @Override
public EffortDuration getAssignedDirectEffort() { public EffortDuration getAssignedDirectEffort() {
if (orderElement == null) { return orderElement == null ? EffortDuration.zero() : this.assignedDirectEffort;
return EffortDuration.zero();
}
return this.assignedDirectEffort;
} }
@Override @Override
public EffortDuration getTotalAssignedEffort() { public EffortDuration getTotalAssignedEffort() {
if (orderElement == null || orderElement.getSumChargedEffort() == null) { return orderElement == null || orderElement.getSumChargedEffort() == null
return EffortDuration.zero(); ? EffortDuration.zero()
} : this.orderElement.getSumChargedEffort().getTotalChargedEffort();
return this.orderElement.getSumChargedEffort().getTotalChargedEffort();
} }
@Override @Override
@ -225,45 +221,32 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public int getProgressWork() { public int getProgressWork() {
if (orderElement == null) { return orderElement == null
return 0; ? 0
} : orderElementDAO.getHoursAdvancePercentage(orderElement).multiply(new BigDecimal(100)).intValue();
return orderElementDAO.getHoursAdvancePercentage(orderElement).multiply(new BigDecimal(100)).intValue();
} }
@Override @Override
public BigDecimal getBudget() { public BigDecimal getBudget() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO : orderElement.getBudget();
return BigDecimal.ZERO;
}
return orderElement.getBudget();
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public BigDecimal getCalculatedBudget() { public BigDecimal getCalculatedBudget() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO : getBudget().subtract(getResourcesBudget());
return BigDecimal.ZERO;
}
return getBudget().subtract(getResourcesBudget());
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public BigDecimal getResourcesBudget() { public BigDecimal getResourcesBudget() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO : orderElement.getResourcesBudget();
return BigDecimal.ZERO;
}
return orderElement.getResourcesBudget();
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public BigDecimal getMoneyCost() { public BigDecimal getMoneyCost() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO : moneyCostCalculator.getTotalMoneyCost(orderElement);
return BigDecimal.ZERO;
}
return moneyCostCalculator.getTotalMoneyCost(orderElement);
} }
@Override @Override
@ -285,28 +268,21 @@ public class AssignedHoursToOrderElementModel implements IAssignedHoursToOrderEl
@Override @Override
public BigDecimal getCostOfExpenses() { public BigDecimal getCostOfExpenses() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO.setScale(2) : moneyCostCalculator.getExpensesMoneyCost(orderElement);
return BigDecimal.ZERO.setScale(2);
}
return moneyCostCalculator.getExpensesMoneyCost(orderElement);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public BigDecimal getCostOfHours() { public BigDecimal getCostOfHours() {
if (orderElement == null) { return orderElement == null ? BigDecimal.ZERO.setScale(2) : moneyCostCalculator.getHoursMoneyCost(orderElement);
return BigDecimal.ZERO.setScale(2);
}
return moneyCostCalculator.getHoursMoneyCost(orderElement);
} }
@Override @Override
@Transactional(readOnly = true) @Transactional(readOnly = true)
public BigDecimal getMoneyCostPercentage() { public BigDecimal getMoneyCostPercentage() {
if (orderElement == null) { return orderElement == null
return BigDecimal.ZERO; ? BigDecimal.ZERO
} : MoneyCostCalculator.getMoneyCostProportion(
return MoneyCostCalculator.getMoneyCostProportion(
moneyCostCalculator.getTotalMoneyCost(orderElement), moneyCostCalculator.getTotalMoneyCost(orderElement),
orderElement.getTotalBudget()).multiply(new BigDecimal(100)); orderElement.getTotalBudget()).multiply(new BigDecimal(100));
} }

View file

@ -26,10 +26,9 @@ import static org.libreplan.web.I18nHelper._;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.SortedSet;
import org.joda.time.LocalDate; import org.joda.time.LocalDate;
import org.libreplan.business.advance.entities.AdvanceMeasurement; import org.libreplan.business.advance.entities.AdvanceMeasurement;
@ -277,10 +276,8 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
} else { } else {
AdvanceMeasurement measure = dto.getAdvanceMeasurement(); AdvanceMeasurement measure = dto.getAdvanceMeasurement();
NonCalculatedConsolidatedValue consolidatedValue = NonCalculatedConsolidatedValue NonCalculatedConsolidatedValue consolidatedValue = NonCalculatedConsolidatedValue.create(
.create(LocalDate.fromDateFields(dto.getDate()), LocalDate.fromDateFields(dto.getDate()), dto.getPercentage(), measure, task.getIntraDayEndDate());
dto.getPercentage(), measure,
task.getIntraDayEndDate());
measure.getNonCalculatedConsolidatedValues().add(consolidatedValue); measure.getNonCalculatedConsolidatedValues().add(consolidatedValue);
return consolidatedValue; return consolidatedValue;
@ -417,20 +414,22 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
if (consolidation != null) { if (consolidation != null) {
if (!consolidation.isCalculated()) { if (!consolidation.isCalculated()) {
/* TODO check it */ SortedSet<NonCalculatedConsolidatedValue> nonCalculatedConsolidatedValues =
consolidationDTOs ((NonCalculatedConsolidation) consolidation).getNonCalculatedConsolidatedValues();
.addAll(((NonCalculatedConsolidation) consolidation)
.getNonCalculatedConsolidatedValues() for (NonCalculatedConsolidatedValue consolidatedValue : nonCalculatedConsolidatedValues) {
.stream()
.map(consolidatedValue -> new AdvanceConsolidationDTO( consolidationDTOs.add(
consolidatedValue.getAdvanceMeasurement(), consolidatedValue)) new AdvanceConsolidationDTO(consolidatedValue.getAdvanceMeasurement(), consolidatedValue));
.collect(Collectors.toList())); }
} else { } else {
consolidationDTOs
.addAll(((CalculatedConsolidation) consolidation) SortedSet<CalculatedConsolidatedValue> consolcalculatedConsolidatedValuestedValues =
.getCalculatedConsolidatedValues() ((CalculatedConsolidation) consolidation).getCalculatedConsolidatedValues();
.stream().map(consolidatedValue -> new AdvanceConsolidationDTO(null, consolidatedValue))
.collect(Collectors.toList())); for (CalculatedConsolidatedValue consolidatedValue : consolcalculatedConsolidatedValuestedValues) {
consolidationDTOs.add(new AdvanceConsolidationDTO(null, consolidatedValue));
}
} }
} }
} }
@ -445,26 +444,18 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
} }
private boolean canBeConsolidateAndShow(AdvanceMeasurement advanceMeasurement) { private boolean canBeConsolidateAndShow(AdvanceMeasurement advanceMeasurement) {
Date date = advanceMeasurement.getDate().toDateTimeAtStartOfDay().toDate(); return AdvanceConsolidationDTO
return AdvanceConsolidationDTO.canBeConsolidateAndShow(date) && !containsAdvance(advanceMeasurement); .canBeConsolidateAndShow(advanceMeasurement.getDate().toDateTimeAtStartOfDay().toDate()) &&
!containsAdvance(advanceMeasurement);
} }
@Override @Override
public String getInfoAdvanceAssignment() { public String getInfoAdvanceAssignment() {
if (this.spreadAdvance == null || this.orderElement == null) { return this.spreadAdvance == null || this.orderElement == null ? "" : getInfoAdvanceAssignment(this.spreadAdvance);
return "";
}
return getInfoAdvanceAssignment(this.spreadAdvance);
} }
private String getInfoAdvanceAssignment(DirectAdvanceAssignment assignment) { private String getInfoAdvanceAssignment(DirectAdvanceAssignment assignment) {
if (assignment == null) { return assignment == null || assignment.getMaxValue() == null ? "" : _("( max: {0} )", assignment.getMaxValue());
return "";
}
if (assignment.getMaxValue() == null) {
return "";
}
return _("( max: {0} )", assignment.getMaxValue());
} }
private List<AdvanceMeasurement> getAdvances() { private List<AdvanceMeasurement> getAdvances() {
@ -473,16 +464,16 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
@Override @Override
public boolean isVisibleAdvances() { public boolean isVisibleAdvances() {
return (!isVisibleMessages()); return !isVisibleMessages();
} }
@Override @Override
public boolean isVisibleMessages() { public boolean isVisibleMessages() {
return ((getAdvances().size() == 0) || (isSubcontracted()) || (!hasResourceAllocation())); return getAdvances().size() == 0 || isSubcontracted() || !hasResourceAllocation();
} }
private boolean advanceIsCalculated(){ private boolean advanceIsCalculated(){
return ((spreadAdvance != null) && (spreadAdvance.isFake())); return spreadAdvance != null && spreadAdvance.isFake();
} }
public String infoMessages() { public String infoMessages() {
@ -500,15 +491,15 @@ public class AdvanceConsolidationModel implements IAdvanceConsolidationModel {
} }
private boolean hasResourceAllocation() { private boolean hasResourceAllocation() {
return ((task != null) && (task.hasResourceAllocations())); return task != null && task.hasResourceAllocations();
} }
private boolean isSubcontracted() { private boolean isSubcontracted() {
return ((task != null) && (task.isSubcontracted())); return task != null && task.isSubcontracted();
} }
public boolean hasLimitingResourceAllocation() { public boolean hasLimitingResourceAllocation() {
return ((task != null) && (task.hasLimitedResourceAllocation())); return task != null && task.hasLimitedResourceAllocation();
} }
@Override @Override

View file

@ -89,6 +89,8 @@ import org.zkoss.zul.Tabpanel;
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TaskPropertiesController extends GenericForwardComposer<Component> { public class TaskPropertiesController extends GenericForwardComposer<Component> {
private final String WARNING = "Warning";
private IScenarioManager scenarioManager; private IScenarioManager scenarioManager;
private TaskEditFormComposer taskEditFormComposer = new TaskEditFormComposer(); private TaskEditFormComposer taskEditFormComposer = new TaskEditFormComposer();
@ -140,10 +142,18 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
private List<Resource> listToAdd = new ArrayList<>(); private List<Resource> listToAdd = new ArrayList<>();
public TaskPropertiesController() { public TaskPropertiesController() {
if ( emailNotificationModel == null ) {
emailNotificationModel = (IEmailNotificationModel) SpringUtil.getBean("emailNotificationModel"); emailNotificationModel = (IEmailNotificationModel) SpringUtil.getBean("emailNotificationModel");
}
if ( workerModel == null ) {
workerModel = (IWorkerModel) SpringUtil.getBean("workerModel"); workerModel = (IWorkerModel) SpringUtil.getBean("workerModel");
}
if ( scenarioManager == null ) {
scenarioManager = (IScenarioManager) SpringUtil.getBean("scenarioManager"); scenarioManager = (IScenarioManager) SpringUtil.getBean("scenarioManager");
} }
}
public void init(final EditTaskController editTaskController, public void init(final EditTaskController editTaskController,
IContextWithPlannerTask<TaskElement> context, IContextWithPlannerTask<TaskElement> context,
@ -317,8 +327,8 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
TaskPositionConstraint taskConstraint = currentTaskElementAsTaskLeafConstraint().getPositionConstraint(); TaskPositionConstraint taskConstraint = currentTaskElementAsTaskLeafConstraint().getPositionConstraint();
PositionConstraintType type = startConstraintTypes.getSelectedItem().getValue(); PositionConstraintType type = startConstraintTypes.getSelectedItem().getValue();
IntraDayDate inputDate = type.isAssociatedDateRequired() ? IntraDayDate inputDate = type.isAssociatedDateRequired()
IntraDayDate.startOfDay(LocalDate.fromDateFields(startConstraintDate.getValue())) ? IntraDayDate.startOfDay(LocalDate.fromDateFields(startConstraintDate.getValue()))
: null; : null;
if ( taskConstraint.isValid(type, inputDate) ) { if ( taskConstraint.isValid(type, inputDate) ) {
@ -466,7 +476,6 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
* Enum for showing type of resource assignation option list. * Enum for showing type of resource assignation option list.
* *
* @author Diego Pino Garcia <dpino@igalia.com> * @author Diego Pino Garcia <dpino@igalia.com>
*
*/ */
enum ResourceAllocationTypeEnum { enum ResourceAllocationTypeEnum {
NON_LIMITING_RESOURCES(_("Normal resource assignment")), NON_LIMITING_RESOURCES(_("Normal resource assignment")),
@ -542,7 +551,8 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
* *
* @param resourceAllocation * @param resourceAllocation
*/ */
public void setResourceAllocationType(ResourceAllocationTypeEnum resourceAllocation) {} public void setResourceAllocationType(ResourceAllocationTypeEnum resourceAllocation) {
}
ResourceAllocationTypeEnum getResourceAllocationType(TaskElement taskElement) { ResourceAllocationTypeEnum getResourceAllocationType(TaskElement taskElement) {
return taskElement == null || !isTask(taskElement) return taskElement == null || !isTask(taskElement)
@ -604,7 +614,7 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
if ( task.hasResourceAllocations() ) { if ( task.hasResourceAllocations() ) {
if ( Messagebox.show( if ( Messagebox.show(
_("Assigned resources for this task will be deleted. Are you sure?"), _("Assigned resources for this task will be deleted. Are you sure?"),
_("Warning"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) { _(WARNING), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) {
task.removeAllResourceAllocations(); task.removeAllResourceAllocations();
setStateTo(newState); setStateTo(newState);
} else { } else {
@ -640,7 +650,7 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
if (task.hasResourceAllocations()) { if (task.hasResourceAllocations()) {
if (Messagebox.show( if (Messagebox.show(
_("Assigned resources for this task will be deleted. Are you sure?"), _("Assigned resources for this task will be deleted. Are you sure?"),
_("Warning"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK ) { _(WARNING), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK ) {
task.removeAllResourceAllocations(); task.removeAllResourceAllocations();
setStateTo(newState); setStateTo(newState);
} else { } else {
@ -667,9 +677,11 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
// Notification has been sent // Notification has been sent
if ( communicationDate != null ) { if ( communicationDate != null ) {
if ( Messagebox.show(_("IMPORTANT: Don't forget to communicate to subcontractor that " +
"his contract has been cancelled"), _("Warning"), if ( Messagebox.show(
Messagebox.OK, Messagebox.EXCLAMATION) == Messagebox.OK ) { _("IMPORTANT: Don't forget to communicate to subcontractor that his contract has been cancelled"),
_(WARNING), Messagebox.OK, Messagebox.EXCLAMATION) == Messagebox.OK ) {
setStateTo(newState); setStateTo(newState);
} else { } else {
resetStateTo(ResourceAllocationTypeEnum.SUBCONTRACT); resetStateTo(ResourceAllocationTypeEnum.SUBCONTRACT);
@ -731,14 +743,12 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
return Util.getMoneyFormat(); return Util.getMoneyFormat();
} }
public void emailNotificationAddNew() { /**
/*
* Check if resources in allocation are bound by user and in what ROLE they are. * Check if resources in allocation are bound by user and in what ROLE they are.
* setUser method calling manually because, after initialization user will be null. * setUser method calling manually because, after initialization user will be null.
* Then send valid data to notification_queue table. * Then send valid data to notification_queue table.
*/ */
public void emailNotificationAddNew() {
proceedList(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE, listToAdd); proceedList(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE, listToAdd);
proceedList(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK, listToDelete); proceedList(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK, listToDelete);
listToAdd.clear(); listToAdd.clear();
@ -764,9 +774,10 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
if ( currentUser != null && if ( currentUser != null &&
(currentUser.isInRole(UserRole.ROLE_EMAIL_TASK_ASSIGNED_TO_RESOURCE) || (currentUser.isInRole(UserRole.ROLE_EMAIL_TASK_ASSIGNED_TO_RESOURCE) ||
currentUser.isInRole(UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK)) ) currentUser.isInRole(UserRole.ROLE_EMAIL_RESOURCE_REMOVED_FROM_TASK)) ) {
setEmailNotificationEntity(enumeration, currentResource); setEmailNotificationEntity(enumeration, currentResource);
}
break; break;
} }
} }
@ -777,11 +788,11 @@ public class TaskPropertiesController extends GenericForwardComposer<Component>
try { try {
emailNotificationModel.setNewObject(); emailNotificationModel.setNewObject();
if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE) ) if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE) ) {
emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE); emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_TASK_ASSIGNED_TO_RESOURCE);
} else if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK) ) {
else if ( enumeration.equals(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK) )
emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK); emailNotificationModel.setType(EmailTemplateEnum.TEMPLATE_RESOURCE_REMOVED_FROM_TASK);
}
emailNotificationModel.setUpdated(new Date()); emailNotificationModel.setUpdated(new Date());

View file

@ -35,7 +35,6 @@ import org.libreplan.web.common.BaseCRUDController;
import org.libreplan.web.common.Util; import org.libreplan.web.common.Util;
import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException; import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zul.Checkbox; import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Column; import org.zkoss.zul.Column;
import org.zkoss.zul.Constraint; import org.zkoss.zul.Constraint;
@ -53,6 +52,8 @@ import org.zkoss.zul.ext.Sortable;
*/ */
public class QualityFormCRUDController extends BaseCRUDController<QualityForm> { public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
private final String CANNOT_BE_EMPTY = "cannot be empty";
private IQualityFormModel qualityFormModel; private IQualityFormModel qualityFormModel;
private Grid gridQualityForms; private Grid gridQualityForms;
@ -64,8 +65,10 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
private Textbox txtFilter; private Textbox txtFilter;
public QualityFormCRUDController() { public QualityFormCRUDController() {
if ( qualityFormModel == null ) {
qualityFormModel = (IQualityFormModel) SpringUtil.getBean("qualityFormModel"); qualityFormModel = (IQualityFormModel) SpringUtil.getBean("qualityFormModel");
} }
}
@Override @Override
public void doAfterCompose(Component comp) throws Exception { public void doAfterCompose(Component comp) throws Exception {
@ -77,38 +80,40 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
/** /**
* Return all {@link QualityForm} * Return all {@link QualityForm}.
* @return *
* @return {@link List<QualityForm>}
*/ */
public List<QualityForm> getQualityForms() { public List<QualityForm> getQualityForms() {
return qualityFormModel.getQualityForms(predicate); return qualityFormModel.getQualityForms(predicate);
} }
/** /**
* Return current {@link QualityForm} * Return current {@link QualityForm}.
* @return *
* @return {@link QualityForm}
*/ */
public QualityForm getQualityForm() { public QualityForm getQualityForm() {
return qualityFormModel.getQualityForm(); return qualityFormModel.getQualityForm();
} }
/** /**
* Return all {@link QualityFormItem} assigned to the current * Return all {@link QualityFormItem} assigned to the current {@link QualityForm}.
* {@link QualityForm} *
* @return * @return {@link List<QualityFormItem>}
*/ */
public List<QualityFormItem> getQualityFormItems() { public List<QualityFormItem> getQualityFormItems() {
return qualityFormModel.getQualityFormItems(); return qualityFormModel.getQualityFormItems();
} }
@Override @Override
protected void beforeSaving() throws ValidationException { protected void beforeSaving() {
super.beforeSaving(); super.beforeSaving();
validateReportProgress(); validateReportProgress();
} }
@Override @Override
protected void save() throws ValidationException { protected void save() {
qualityFormModel.confirmSave(); qualityFormModel.confirmSave();
} }
@ -122,11 +127,10 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
/** /**
* Sorts {@link Grid} model by first column, respecting sort order * Sorts {@link Grid} model by first column, respecting sort order.
* *
* FIXME: This is a temporary solution, there should be a better/smarter way * FIXME: This is a temporary solution
* of preserving order in the Grid every time a new element is added to its * There should be a better/smarter way Preserving order in the Grid every time a new element is added to its model.
* model
*/ */
private void forceSortGridQualityFormItems() { private void forceSortGridQualityFormItems() {
Column column = (Column) gridQualityFormItems.getColumns().getChildren().get(2); Column column = (Column) gridQualityFormItems.getColumns().getChildren().get(2);
@ -140,19 +144,19 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
/** /**
* Pop up confirm remove dialog * Pop up confirm remove dialog.
* @param QualityFormItem *
* @param item
*/ */
public void confirmDeleteQualityFormItem(QualityFormItem item) { public void confirmDeleteQualityFormItem(QualityFormItem item) {
if (qualityFormModel.isTotalPercentage(item)) { if (qualityFormModel.isTotalPercentage(item)) {
if (Messagebox
.show( if (Messagebox.show(
_("Deleting this item will disable the report progress option. Are you sure?"), _("Deleting this item will disable the report progress option. Are you sure?"), _("Confirm"),
_("Confirm"), Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION) == Messagebox.OK) {
Messagebox.OK | Messagebox.CANCEL,
Messagebox.QUESTION) == Messagebox.OK) {
Checkbox reportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress"); Checkbox reportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress");
disabledCheckbocReportProgress(reportProgress); disabledCheckboxReportProgress(reportProgress);
} else { } else {
return; return;
} }
@ -171,7 +175,7 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
public void onChangeQualityFormItemPercentage() { public void onChangeQualityFormItemPercentage() {
// it must update the order of the items if it is necessary. // It must update the order of the items if it is necessary
getQualityForm().updateAndSortQualityFormItem(); getQualityForm().updateAndSortQualityFormItem();
Util.reloadBindings(gridQualityFormItems); Util.reloadBindings(gridQualityFormItems);
} }
@ -179,8 +183,8 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
public Constraint checkConstraintUniqueQualityFormName() { public Constraint checkConstraintUniqueQualityFormName() {
return (comp, value) -> { return (comp, value) -> {
getQualityForm().setName((String) value); getQualityForm().setName((String) value);
if((value == null) || (((String)value)).isEmpty()){ if ((value == null) || ((String)value).isEmpty()) {
throw new WrongValueException(comp, _("cannot be empty")); throw new WrongValueException(comp, _(CANNOT_BE_EMPTY));
} else if (!qualityFormModel.checkConstraintUniqueQualityFormName()) { } else if (!qualityFormModel.checkConstraintUniqueQualityFormName()) {
getQualityForm().setName(null); getQualityForm().setName(null);
throw new WrongValueException(comp, _("{0} already exists", value)); throw new WrongValueException(comp, _("{0} already exists", value));
@ -192,9 +196,9 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
return (comp, value) -> { return (comp, value) -> {
QualityFormItem item = ((Row) comp.getParent()).getValue(); QualityFormItem item = ((Row) comp.getParent()).getValue();
item.setName((String)value); item.setName((String)value);
if ((value == null) || (((String) value)).isEmpty()) { if ((value == null) || ((String) value).isEmpty()) {
item.setName(null); item.setName(null);
throw new WrongValueException(comp, _("cannot be empty")); throw new WrongValueException(comp, _(CANNOT_BE_EMPTY));
} else if (!qualityFormModel.checkConstraintUniqueQualityFormItemName()) { } else if (!qualityFormModel.checkConstraintUniqueQualityFormItemName()) {
item.setName(null); item.setName(null);
throw new WrongValueException(comp, _("{0} already exists", value)); throw new WrongValueException(comp, _("{0} already exists", value));
@ -211,7 +215,7 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
if (newPercentage == null) { if (newPercentage == null) {
item.setPercentage(null); item.setPercentage(null);
throw new WrongValueException(comp, _("cannot be empty")); throw new WrongValueException(comp, _(CANNOT_BE_EMPTY));
} }
if (qualityFormModel.checkConstraintOutOfRangeQualityFormItemPercentage(item)) { if (qualityFormModel.checkConstraintOutOfRangeQualityFormItemPercentage(item)) {
item.setPercentage(null); item.setPercentage(null);
@ -225,8 +229,7 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
public boolean isByPercentage() { public boolean isByPercentage() {
return this.getQualityForm() != null && return this.getQualityForm() != null && getQualityForm().getQualityFormType().equals(QualityFormType.BY_PERCENTAGE);
getQualityForm().getQualityFormType().equals(QualityFormType.BY_PERCENTAGE);
} }
public boolean isByItems() { public boolean isByItems() {
@ -248,10 +251,9 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
} }
/** /**
* Apply filter to quality forms * Apply filter to quality forms.
* @param event
*/ */
public void onApplyFilter(Event event) { public void onApplyFilter() {
// Filter quality forms by name // Filter quality forms by name
predicate = getSelectedName(); predicate = getSelectedName();
Util.reloadBindings(gridQualityForms); Util.reloadBindings(gridQualityForms);
@ -261,14 +263,10 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
return txtFilter.getValue(); return txtFilter.getValue();
} }
private void clearFilter() {
txtFilter.setValue("");
predicate = getSelectedName();
}
public void validateReportProgress() { public void validateReportProgress() {
if ((getQualityForm().isReportAdvance()) && (!hasItemWithTotalPercentage())) { if ((getQualityForm().isReportAdvance()) && (!hasItemWithTotalPercentage())) {
Checkbox checkBoxReportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress"); Checkbox checkBoxReportProgress = (Checkbox) editWindow.getFellowIfAny("checkBoxReportProgress");
throw new WrongValueException( throw new WrongValueException(
checkBoxReportProgress, checkBoxReportProgress,
_("Quality form should include an item with a value of 100% in order to report progress")); _("Quality form should include an item with a value of 100% in order to report progress"));
@ -279,7 +277,7 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
return this.qualityFormModel.hasItemWithTotalPercentage(); return this.qualityFormModel.hasItemWithTotalPercentage();
} }
private void disabledCheckbocReportProgress(Checkbox reportProgress) { private void disabledCheckboxReportProgress(Checkbox reportProgress) {
if (reportProgress != null) { if (reportProgress != null) {
getQualityForm().setReportAdvance(false); getQualityForm().setReportAdvance(false);
reportProgress.setChecked(false); reportProgress.setChecked(false);
@ -332,8 +330,7 @@ public class QualityFormCRUDController extends BaseCRUDController<QualityForm> {
qualityFormModel.checkHasTasks(qualityForm); qualityFormModel.checkHasTasks(qualityForm);
return false; return false;
} catch (ValidationException e) { } catch (ValidationException e) {
showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage() showCannotDeleteQualityFormDialog(e.getInvalidValue().getMessage());
);
} }
return true; return true;
} }

View file

@ -36,40 +36,38 @@ import org.libreplan.web.planner.allocation.INewAllocationsAdder;
import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Component;
/** /**
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com> * Controller for searching for {@link Resource}.
* *
* Controller for searching for {@link Resource} * @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/ */
public class NewAllocationSelectorComboController extends public class NewAllocationSelectorComboController extends AllocationSelectorController {
AllocationSelectorController {
private ResourceAllocationBehaviour behaviour; private ResourceAllocationBehaviour currentBehaviour;
private BandboxMultipleSearch bbMultipleSearch; private BandboxMultipleSearch bbMultipleSearch;
public NewAllocationSelectorComboController(ResourceAllocationBehaviour behaviour) { public NewAllocationSelectorComboController(ResourceAllocationBehaviour behaviour) {
this.behaviour = behaviour; this.currentBehaviour = behaviour;
} }
@Override @Override
public void doAfterCompose(Component comp) throws Exception { public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp); super.doAfterCompose(comp);
bbMultipleSearch.setFinder(behaviour.getFinder()); bbMultipleSearch.setFinder(currentBehaviour.getFinder());
} }
/** /**
* Does the actual search for workers * Does the actual search for workers.
* *
* @param criteria * @param criteria
*/ */
private List<? extends Resource> searchResources(List<Criterion> criteria) { private List<? extends Resource> searchResources(List<Criterion> criteria) {
return query(inferType(criteria)).byCriteria(criteria) return query(inferType(criteria)).byCriteria(criteria).byResourceType(currentBehaviour.getType()).execute();
.byResourceType(behaviour.getType()).execute();
} }
private static ResourceEnum inferType(List<Criterion> criteria) { private static ResourceEnum inferType(List<Criterion> criteria) {
if (criteria.isEmpty()) { if (criteria.isEmpty()) {
// FIXME resolve the ambiguity. One option is asking the user // FIXME resolve the ambiguity; one option is asking the user
return ResourceEnum.WORKER; return ResourceEnum.WORKER;
} }
return first(criteria).getType().getResource(); return first(criteria).getType().getResource();
@ -84,12 +82,12 @@ public class NewAllocationSelectorComboController extends
} }
/** /**
* Returns list of selected {@link Criterion}, selects only those which are * Returns list of selected {@link Criterion}, selects only those which are leaf nodes.
* leaf nodes *
* @return * @return {@link List<Criterion>}
*/ */
public List<Criterion> getSelectedCriterions() { public List<Criterion> getSelectedCriterions() {
List<Criterion> criteria = new ArrayList<Criterion>(); List<Criterion> criteria = new ArrayList<>();
for (FilterPair pair : getSelectedItems()) { for (FilterPair pair : getSelectedItems()) {
if (pair.getType().equals(ResourceAllocationFilterEnum.Criterion)) { if (pair.getType().equals(ResourceAllocationFilterEnum.Criterion)) {
criteria.add((Criterion) pair.getValue()); criteria.add((Criterion) pair.getValue());
@ -99,13 +97,11 @@ public class NewAllocationSelectorComboController extends
} }
private List<FilterPair> getSelectedItems() { private List<FilterPair> getSelectedItems() {
return ((List<FilterPair>) bbMultipleSearch return ((List<FilterPair>) bbMultipleSearch.getSelectedElements());
.getSelectedElements());
} }
private boolean isGeneric() { private boolean isGeneric() {
return ((FilterPair) getSelectedItems().get(0)).getType().equals( return getSelectedItems().get(0).getType().equals(ResourceAllocationFilterEnum.Criterion);
ResourceAllocationFilterEnum.Criterion);
} }
public void onClose() { public void onClose() {
@ -117,7 +113,7 @@ public class NewAllocationSelectorComboController extends
} }
public List<Resource> getSelectedResources() { public List<Resource> getSelectedResources() {
List<Resource> resources = new ArrayList<Resource>(); List<Resource> resources = new ArrayList<>();
for (FilterPair pair : getSelectedItems()) { for (FilterPair pair : getSelectedItems()) {
if (pair.getType().equals(ResourceAllocationFilterEnum.Resource)) { if (pair.getType().equals(ResourceAllocationFilterEnum.Resource)) {
resources.add((Resource) pair.getValue()); resources.add((Resource) pair.getValue());

View file

@ -34,7 +34,6 @@ import org.zkoss.zul.Treeitem;
/** /**
* Macro component for order elements tree and similar pages. * Macro component for order elements tree and similar pages.
* <br /> * <br />
*
* @author Óscar González Fernández <ogonzalez@igalia.com> * @author Óscar González Fernández <ogonzalez@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com> * @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
*/ */
@ -44,27 +43,21 @@ public abstract class TreeComponent extends HtmlMacroComponent {
protected Column codeColumn = new Column(_("Code"), "code") { protected Column codeColumn = new Column(_("Code"), "code") {
@Override @Override
public <T extends ITreeNode<T>> void doCell( public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addCodeCell(currentElement); renderer.addCodeCell(currentElement);
} }
}; };
protected final Column nameAndDescriptionColumn = new Column(_("Name"), "name") { protected final Column nameAndDescriptionColumn = new Column(_("Name"), "name") {
@Override @Override
public <T extends ITreeNode<T>> void doCell( public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addDescriptionCell(currentElement); renderer.addDescriptionCell(currentElement);
} }
}; };
protected final Column operationsColumn = new Column(_("Op."), "operations", _("Operations")) { protected final Column operationsColumn = new Column(_("Op."), "operations", _("Operations")) {
@Override @Override
public <T extends ITreeNode<T>> void doCell( public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addOperationsCell(item, currentElement); renderer.addOperationsCell(item, currentElement);
} }
}; };
@ -75,9 +68,7 @@ public abstract class TreeComponent extends HtmlMacroComponent {
_("Fully, Partially or Unscheduled. (Drag and drop to move tasks)")) { _("Fully, Partially or Unscheduled. (Drag and drop to move tasks)")) {
@Override @Override
public <T extends ITreeNode<T>> void doCell( public <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
TreeController<T>.Renderer renderer, Treeitem item, T currentElement) {
renderer.addSchedulingStateCell(currentElement); renderer.addSchedulingStateCell(currentElement);
} }
}; };
@ -125,34 +116,27 @@ public abstract class TreeComponent extends HtmlMacroComponent {
/* TODO remove me, if ZK Load on demand issue will be resolved */ /* TODO remove me, if ZK Load on demand issue will be resolved */
public String getHflex() { public String getHflex() {
return cssClass.equals("name") ? "1" : "min"; return "name".equals(cssClass) ? "1" : "min";
} }
/* TODO remove me, if ZK Load on demand issue will be resolved */ /* TODO remove me, if ZK Load on demand issue will be resolved */
public String getWidth() { public String getWidth() {
if (cssClass.contains("scheduling_state")) { if (cssClass.contains("scheduling_state")) {
return "135px"; return "135px";
} else if (cssClass.equals("code")) { } else if ("code".equals(cssClass)) {
return "106px"; return "106px";
} else if (cssClass.equals("name")) { } else if ("name".equals(cssClass)) {
return "950px"; return "950px";
} else if (cssClass.equals("hours")) { } else if ("hours".equals(cssClass) || "budget".equals(cssClass) || "operations".equals(cssClass)) {
return "50px"; return "50px";
} else if (cssClass.equals("budget")) { } else if ("estimated_init".equals(cssClass) || "estimated_end".equals(cssClass)) {
return "50px";
} else if (cssClass.equals("estimated_init")) {
return "100px"; return "100px";
} else if (cssClass.equals("estimated_end")) {
return "100px";
} else if (cssClass.equals("operations") ) {
return "50px";
} }
return ""; return "";
} }
public abstract <T extends ITreeNode<T>> void doCell( public abstract <T extends ITreeNode<T>> void doCell(TreeController<T>.Renderer renderer, Treeitem item, T currentElement);
TreeController<T>.Renderer renderer, Treeitem item, T currentElement);
} }
public abstract List<Column> getColumns(); public abstract List<Column> getColumns();

View file

@ -49,7 +49,6 @@ import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider; import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@ -70,7 +69,8 @@ import org.springframework.transaction.annotation.Transactional;
*/ */
// TODO resolve deprecated methods // TODO resolve deprecated methods
public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider public class LDAPCustomAuthenticationProvider
extends AbstractUserDetailsAuthenticationProvider
implements AuthenticationProvider { implements AuthenticationProvider {
@Autowired @Autowired
@ -84,7 +84,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
private LDAPConfiguration configuration; private LDAPConfiguration configuration;
// Template to search in LDAP /** Template to search in LDAP */
private LdapTemplate ldapTemplate; private LdapTemplate ldapTemplate;
private UserDetailsService userDetailsService; private UserDetailsService userDetailsService;
@ -98,21 +98,18 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
private static final Log LOG = LogFactory.getLog(LDAPCustomAuthenticationProvider.class); private static final Log LOG = LogFactory.getLog(LDAPCustomAuthenticationProvider.class);
/** /**
* LDAP role matching could be configured using an asterix (*) * LDAP role matching could be configured using an asterix (*) to specify all users or groups
* to specify all users or groups
*/ */
private static final String WILDCHAR_ALL = "*"; private static final String WILDCHAR_ALL = "*";
@Override @Override
protected void additionalAuthenticationChecks(UserDetails arg0, UsernamePasswordAuthenticationToken arg1) protected void additionalAuthenticationChecks(UserDetails arg0, UsernamePasswordAuthenticationToken arg1) {
throws AuthenticationException {
// No needed at this time // No needed at this time
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
@Override @Override
public UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) public UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) {
throws AuthenticationException {
String clearPassword = authentication.getCredentials().toString(); String clearPassword = authentication.getCredentials().toString();
@ -130,6 +127,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
} }
// If it's a LDAP or null user, then we must authenticate against LDAP // If it's a LDAP or null user, then we must authenticate against LDAP
// Load LDAPConfiguration properties // Load LDAPConfiguration properties
configuration = loadLDAPConfiguration(); configuration = loadLDAPConfiguration();
@ -191,12 +189,14 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
User user = User.create(); User user = User.create();
user.setLoginName(username); user.setLoginName(username);
String newEncodedPassword = encodedPassword;
// we must check if it is needed to save LDAP passwords in DB // we must check if it is needed to save LDAP passwords in DB
if ( !configuration.isLdapSavePasswordsDB() ) { if ( !configuration.isLdapSavePasswordsDB() ) {
encodedPassword = null; newEncodedPassword = null;
} }
user.setPassword(encodedPassword); user.setPassword(newEncodedPassword);
user.setLibrePlanUser(false); user.setLibrePlanUser(false);
user.setDisabled(false); user.setDisabled(false);
setRoles(user); setRoles(user);
@ -243,8 +243,7 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
try { try {
context.afterPropertiesSet(); context.afterPropertiesSet();
} catch (Exception e) { } catch (Exception e) {
// This exception will be never reached if the LDAP // This exception will be never reached if the LDAP properties are well-formed.
// properties are well-formed.
LOG.error("There is a problem in LDAP connection: ", e); LOG.error("There is a problem in LDAP connection: ", e);
} }
@ -259,13 +258,12 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
} }
private void saveUserOnTransaction(User user) { private void saveUserOnTransaction(User user) {
final User userLibrePlan = user; final User librePlanUser = user;
transactionService.runOnTransaction(new IOnTransaction<Void>() { transactionService.runOnTransaction(new IOnTransaction<Void>() {
@Override @Override
public Void execute() { public Void execute() {
userDAO.save(userLibrePlan); userDAO.save(librePlanUser);
return null; return null;
} }
}); });
@ -355,17 +353,14 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
try { try {
if ( !configuration.getLdapGroupStrategy() ) { if ( !configuration.getLdapGroupStrategy() ) {
// The LDAP has a node strategy for groups, // The LDAP has a node strategy for groups, we must check the roleProperty in user node
// we must check the roleProperty in user node.
return getRolesUsingNodeStrategy(rolesLdap, queryRoles, configuration); return getRolesUsingNodeStrategy(rolesLdap, queryRoles, configuration);
} else { } else {
// The LDAP has a branch strategy for groups // The LDAP has a branch strategy for groups we must check if the user is in one of the groups
// we must check if the user is in one of the groups.
return getRolesUsingBranchStrategy(rolesLdap, queryRoles, configuration); return getRolesUsingBranchStrategy(rolesLdap, queryRoles, configuration);
} }
} catch (Exception e) { } catch (Exception e) {
LOG.error("Configuration of LDAP role-matching is wrong. Please check it.", e); LOG.error("Configuration of LDAP role-matching is wrong. Please check it.", e);
return Collections.emptyList(); return Collections.emptyList();
} }
} }
@ -378,7 +373,6 @@ public class LDAPCustomAuthenticationProvider extends AbstractUserDetailsAuthent
this.passwordEncoderService = passwordEncoderService; this.passwordEncoderService = passwordEncoderService;
} }
// Getters and setters
public LdapTemplate getLdapTemplate() { public LdapTemplate getLdapTemplate() {
return ldapTemplate; return ldapTemplate;
} }

View file

@ -40,35 +40,23 @@ public final class LabelReferenceConverter {
} }
public final static Set<LabelReferenceDTO> toDTO(Set<Label> labels) { public final static Set<LabelReferenceDTO> toDTO(Set<Label> labels) {
Set<LabelReferenceDTO> labelDTOs = new HashSet<LabelReferenceDTO>(); Set<LabelReferenceDTO> labelDTOs = new HashSet<>();
for (Label label : labels) { for (Label label : labels) {
labelDTOs.add(toDTO(label)); labelDTOs.add(toDTO(label));
} }
return labelDTOs; return labelDTOs;
} }
public final static LabelReferenceDTO toDTO(Label label) { public static final LabelReferenceDTO toDTO(Label label) {
return new LabelReferenceDTO(label.getCode()); return new LabelReferenceDTO(label.getCode());
} }
public static Set<Label> toEntity(Set<LabelReferenceDTO> labels) public static Set<Label> toEntity(Set<LabelReferenceDTO> labels) throws InstanceNotFoundException {
throws InstanceNotFoundException { Set<Label> result = new HashSet<>();
Set<Label> result = new HashSet<Label>();
for (LabelReferenceDTO labelReferenceDTO : labels) { for (LabelReferenceDTO labelReferenceDTO : labels) {
result.add(toEntity(labelReferenceDTO)); result.add(Registry.getLabelDAO().findByCode(labelReferenceDTO.code));
} }
return result; return result;
} }
public final static Label toEntity(LabelReferenceDTO labelReferenceDTO)
throws InstanceNotFoundException {
// FIXME review if this check could be moved to findByCode at
// IntegrationEntityDAO
if (labelReferenceDTO.code == null) {
throw new InstanceNotFoundException(null, Label.class.getName());
}
return Registry.getLabelDAO().findByCode(labelReferenceDTO.code);
}
} }

View file

@ -87,116 +87,116 @@ public final class OrderElementConverter {
private OrderElementConverter() { private OrderElementConverter() {
} }
public final static OrderElementDTO toDTO(OrderElement orderElement, public static final OrderElementDTO toDTO(OrderElement orderElement, ConfigurationOrderElementConverter configuration) {
ConfigurationOrderElementConverter configuration) {
String name = orderElement.getName(); String name = orderElement.getName();
String code = orderElement.getCode(); String code = orderElement.getCode();
XMLGregorianCalendar initDate = DateConverter XMLGregorianCalendar initDate = DateConverter.toXMLGregorianCalendar(orderElement.getInitDate());
.toXMLGregorianCalendar(orderElement.getInitDate()); XMLGregorianCalendar deadline = DateConverter.toXMLGregorianCalendar(orderElement.getDeadline());
XMLGregorianCalendar deadline = DateConverter
.toXMLGregorianCalendar(orderElement.getDeadline());
String description = orderElement.getDescription(); String description = orderElement.getDescription();
Set<LabelReferenceDTO> labels = new HashSet<LabelReferenceDTO>(); Set<LabelReferenceDTO> labels = new HashSet<>();
if (configuration.isLabels()) { if (configuration.isLabels()) {
for (Label label : orderElement.getLabels()) { for (Label label : orderElement.getLabels()) {
labels.add(LabelReferenceConverter.toDTO(label)); labels.add(LabelReferenceConverter.toDTO(label));
} }
} }
Set<MaterialAssignmentDTO> materialAssignments = new HashSet<MaterialAssignmentDTO>(); Set<MaterialAssignmentDTO> materialAssignments = new HashSet<>();
if (configuration.isMaterialAssignments()) { if (configuration.isMaterialAssignments()) {
for (MaterialAssignment materialAssignment : orderElement for (MaterialAssignment materialAssignment : orderElement.getMaterialAssignments()) {
.getMaterialAssignments()) {
materialAssignments.add(toDTO(materialAssignment)); materialAssignments.add(toDTO(materialAssignment));
} }
} }
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<AdvanceMeasurementDTO>(); Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<>();
if (configuration.isAdvanceMeasurements()) { if (configuration.isAdvanceMeasurements()) {
advanceMeasurements = toDTO(orderElement advanceMeasurements = toDTO(orderElement.getReportGlobalAdvanceAssignment());
.getReportGlobalAdvanceAssignment());
} }
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<CriterionRequirementDTO>(); Set<CriterionRequirementDTO> criterionRequirements = new HashSet<>();
if (configuration.isCriterionRequirements()) { if (configuration.isCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : orderElement for (CriterionRequirement criterionRequirement : orderElement.getCriterionRequirements()) {
.getCriterionRequirements()) {
criterionRequirements.add(toDTO(criterionRequirement)); criterionRequirements.add(toDTO(criterionRequirement));
} }
} }
if (orderElement instanceof OrderLine) { if (orderElement instanceof OrderLine) {
Set<HoursGroupDTO> hoursGroups = new HashSet<HoursGroupDTO>(); Set<HoursGroupDTO> hoursGroups = new HashSet<>();
if (configuration.isHoursGroups()) { if (configuration.isHoursGroups()) {
for (HoursGroup hoursGroup : ((OrderLine) orderElement) for (HoursGroup hoursGroup : orderElement.getHoursGroups()) {
.getHoursGroups()) {
hoursGroups.add(toDTO(hoursGroup, configuration)); hoursGroups.add(toDTO(hoursGroup, configuration));
} }
} }
return new OrderLineDTO(name, code, initDate, deadline, return new OrderLineDTO(
description, labels, materialAssignments, name, code, initDate,
advanceMeasurements, criterionRequirements, hoursGroups); deadline, description, labels,
materialAssignments, advanceMeasurements, criterionRequirements,
hoursGroups);
} else { // orderElement instanceof OrderLineGroup } else { // orderElement instanceof OrderLineGroup
List<OrderElementDTO> children = new ArrayList<OrderElementDTO>(); List<OrderElementDTO> children = new ArrayList<>();
for (OrderElement element : orderElement.getChildren()) { for (OrderElement element : orderElement.getChildren()) {
children.add(toDTO(element, configuration)); children.add(toDTO(element, configuration));
} }
if (orderElement instanceof Order) { if (orderElement instanceof Order) {
Boolean dependenciesConstraintsHavePriority = ((Order) orderElement)
.getDependenciesConstraintsHavePriority(); Boolean dependenciesConstraintsHavePriority =
((Order) orderElement).getDependenciesConstraintsHavePriority();
BaseCalendar calendar = ((Order) orderElement).getCalendar(); BaseCalendar calendar = ((Order) orderElement).getCalendar();
String calendarName = null; String calendarName = null;
if (calendar != null) { if (calendar != null) {
calendarName = calendar.getName(); calendarName = calendar.getName();
} }
return new OrderDTO(name, code, initDate, deadline, return new OrderDTO(
description, labels, materialAssignments, name, code, initDate, deadline,
advanceMeasurements, criterionRequirements, children, description, labels, materialAssignments, advanceMeasurements,
dependenciesConstraintsHavePriority, calendarName); criterionRequirements, children, dependenciesConstraintsHavePriority, calendarName);
} else { // orderElement instanceof OrderLineGroup } else { // orderElement instanceof OrderLineGroup
return new OrderLineGroupDTO(name, code, initDate, deadline, return new OrderLineGroupDTO(
description, labels, materialAssignments, name, code,
advanceMeasurements, criterionRequirements, children); initDate, deadline,
description, labels,
materialAssignments, advanceMeasurements,
criterionRequirements, children);
} }
} }
} }
public static CriterionRequirementDTO toDTO( public static CriterionRequirementDTO toDTO(CriterionRequirement criterionRequirement) {
CriterionRequirement criterionRequirement) {
String name = criterionRequirement.getCriterion().getName(); String name = criterionRequirement.getCriterion().getName();
String type = criterionRequirement.getCriterion().getType().getName(); String type = criterionRequirement.getCriterion().getType().getName();
if (criterionRequirement instanceof IndirectCriterionRequirement) { if (criterionRequirement instanceof IndirectCriterionRequirement) {
boolean isValid = ((IndirectCriterionRequirement) criterionRequirement) boolean isValid = criterionRequirement.isValid();
.isValid();
return new IndirectCriterionRequirementDTO(name, type, isValid); return new IndirectCriterionRequirementDTO(name, type, isValid);
} else { // criterionRequirement instanceof DirectCriterionRequirement } else { // criterionRequirement instanceof DirectCriterionRequirement
return new DirectCriterionRequirementDTO(name, type); return new DirectCriterionRequirementDTO(name, type);
} }
} }
public final static Set<AdvanceMeasurementDTO> toDTO( public static final Set<AdvanceMeasurementDTO> toDTO(DirectAdvanceAssignment advanceAssignment) {
DirectAdvanceAssignment advanceAssignment) { Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<>();
Set<AdvanceMeasurementDTO> advanceMeasurements = new HashSet<AdvanceMeasurementDTO>();
if (advanceAssignment != null) { if (advanceAssignment != null) {
BigDecimal maxValue = advanceAssignment.getMaxValue(); BigDecimal maxValue = advanceAssignment.getMaxValue();
for (AdvanceMeasurement advanceMeasurement : advanceAssignment for (AdvanceMeasurement advanceMeasurement : advanceAssignment.getAdvanceMeasurements()) {
.getAdvanceMeasurements()) {
advanceMeasurements.add(toDTO(maxValue, advanceAssignment
.getAdvanceType().getPercentage(), advanceMeasurement));
}
}
advanceMeasurements.add(
toDTO(maxValue, advanceAssignment.getAdvanceType().getPercentage(), advanceMeasurement));
}
}
return advanceMeasurements; return advanceMeasurements;
} }
public final static AdvanceMeasurementDTO toDTO(BigDecimal maxValue, public static final AdvanceMeasurementDTO toDTO(
boolean isPercentage, AdvanceMeasurement advanceMeasurement) { BigDecimal maxValue, boolean isPercentage, AdvanceMeasurement advanceMeasurement) {
BigDecimal value; BigDecimal value;
if (isPercentage) { if (isPercentage) {
value = advanceMeasurement.getValue(); value = advanceMeasurement.getValue();
@ -204,59 +204,54 @@ public final class OrderElementConverter {
value = advanceMeasurement.getValue().divide(maxValue, value = advanceMeasurement.getValue().divide(maxValue,
RoundingMode.DOWN); RoundingMode.DOWN);
} }
XMLGregorianCalendar date = DateConverter
.toXMLGregorianCalendar(advanceMeasurement.getDate()); return new AdvanceMeasurementDTO(DateConverter.toXMLGregorianCalendar(advanceMeasurement.getDate()), value);
return new AdvanceMeasurementDTO(date, value);
} }
public final static MaterialAssignmentDTO toDTO( public final static MaterialAssignmentDTO toDTO(MaterialAssignment materialAssignment) {
MaterialAssignment materialAssignment) {
XMLGregorianCalendar estimatedAvailability = DateConverter XMLGregorianCalendar estimatedAvailability =
.toXMLGregorianCalendar(materialAssignment DateConverter.toXMLGregorianCalendar(materialAssignment.getEstimatedAvailability());
.getEstimatedAvailability());
return new MaterialAssignmentDTO(materialAssignment.getMaterial() return new MaterialAssignmentDTO(
.getCode(), materialAssignment.getUnits(), materialAssignment materialAssignment.getMaterial().getCode(),
.getUnitPrice(), estimatedAvailability); materialAssignment.getUnits(),
materialAssignment.getUnitPrice(),
estimatedAvailability);
} }
public final static HoursGroupDTO toDTO(HoursGroup hoursGroup, public final static HoursGroupDTO toDTO(HoursGroup hoursGroup, ConfigurationOrderElementConverter configuration) {
ConfigurationOrderElementConverter configuration) { ResourceEnumDTO resourceType = ResourceEnumConverter.toDTO(hoursGroup.getResourceType());
ResourceEnumDTO resourceType = ResourceEnumConverter.toDTO(hoursGroup
.getResourceType());
Set<CriterionRequirementDTO> criterionRequirements = new HashSet<CriterionRequirementDTO>(); Set<CriterionRequirementDTO> criterionRequirements = new HashSet<>();
if (configuration.isCriterionRequirements()) { if (configuration.isCriterionRequirements()) {
for (CriterionRequirement criterionRequirement : hoursGroup for (CriterionRequirement criterionRequirement : hoursGroup.getCriterionRequirements()) {
.getCriterionRequirements()) {
criterionRequirements.add(toDTO(criterionRequirement)); criterionRequirements.add(toDTO(criterionRequirement));
} }
} }
return new HoursGroupDTO(hoursGroup.getCode(), resourceType, hoursGroup return new HoursGroupDTO(hoursGroup.getCode(), resourceType, hoursGroup.getWorkingHours(), criterionRequirements);
.getWorkingHours(), criterionRequirements);
} }
public final static OrderElement toEntity(OrderElementDTO orderElementDTO, public final static OrderElement toEntity(OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration)
ConfigurationOrderElementConverter configuration)
throws ValidationException { throws ValidationException {
return toEntity(null, orderElementDTO, configuration); return toEntity(null, orderElementDTO, configuration);
} }
public final static OrderElement toEntity(OrderVersion orderVersion, public static final OrderElement toEntity(
OrderElementDTO orderElementDTO, OrderVersion orderVersion, OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration) {
ConfigurationOrderElementConverter configuration) {
OrderVersion newOrderVersion = orderVersion;
if (orderVersion == null) { if (orderVersion == null) {
Scenario current = Registry.getScenarioManager().getCurrent(); Scenario current = Registry.getScenarioManager().getCurrent();
orderVersion = OrderVersion.createInitialVersion(current); newOrderVersion = OrderVersion.createInitialVersion(current);
} }
OrderElement orderElement = toEntityExceptCriterionRequirements( OrderElement orderElement = toEntityExceptCriterionRequirements(newOrderVersion, orderElementDTO, configuration);
orderVersion, orderElementDTO, configuration);
// FIXME Review why this validation is needed here, it breaks the // FIXME Review why this validation is needed here, it breaks the subcontract service.
// subcontract service. This was introduced at commit 341145a5 // This was introduced in commit 341145a5
// Validate OrderElement.code and HoursGroup.code must be unique // Validate OrderElement.code and HoursGroup.code must be unique
// Order.checkConstraintOrderUniqueCode(orderElement); // Order.checkConstraintOrderUniqueCode(orderElement);
// HoursGroup.checkConstraintHoursGroupUniqueCode(orderElement); // HoursGroup.checkConstraintHoursGroupUniqueCode(orderElement);
@ -268,34 +263,26 @@ public final class OrderElementConverter {
return orderElement; return orderElement;
} }
private static void checkOrderElementDTOCode( private static void checkOrderElementDTOCode(OrderElementDTO orderElementDTO, String instance) {
OrderElementDTO orderElementDTO,
String instance) {
if (orderElementDTO.code == null) { if (orderElementDTO.code == null) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format("{0}: code not found", instance));
"{0}: code not found", instance));
} }
} }
private static void addOrCriterionRequirements(OrderElement orderElement, private static void addOrCriterionRequirements(OrderElement orderElement, OrderElementDTO orderElementDTO) {
OrderElementDTO orderElementDTO) { addOrCriterionRequirementsEntities(orderElement, orderElementDTO.criterionRequirements);
addOrCriterionRequirementsEntities(orderElement,
orderElementDTO.criterionRequirements);
if (orderElement != null) { if (orderElement != null) {
if (orderElementDTO instanceof OrderLineDTO) { if (orderElementDTO instanceof OrderLineDTO) {
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) { for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
HoursGroup hoursGroup = ((OrderLine) orderElement) HoursGroup hoursGroup = ((OrderLine) orderElement).getHoursGroup(hoursGroupDTO.code);
.getHoursGroup(hoursGroupDTO.code);
if (hoursGroup != null) { if (hoursGroup != null) {
addOrCriterionRequirementsEntities(hoursGroup, addOrCriterionRequirementsEntities(hoursGroup, hoursGroupDTO.criterionRequirements);
hoursGroupDTO.criterionRequirements);
} }
} }
} else { // orderElementDTO instanceof OrderLineGroupDTO } else { // orderElementDTO instanceof OrderLineGroupDTO
for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) { for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) {
OrderElement child = ((OrderLineGroup) orderElement) OrderElement child = orderElement.getOrderElement(childDTO.code);
.getOrderElement(childDTO.code);
addOrCriterionRequirements(child, childDTO); addOrCriterionRequirements(child, childDTO);
} }
} }
@ -303,42 +290,38 @@ public final class OrderElementConverter {
} }
private static void addOrCriterionRequirementsEntities( private static void addOrCriterionRequirementsEntities(
ICriterionRequirable criterionRequirable, ICriterionRequirable criterionRequirable, Set<CriterionRequirementDTO> criterionRequirements) {
Set<CriterionRequirementDTO> criterionRequirements) {
for (CriterionRequirementDTO criterionRequirementDTO : criterionRequirements) { for (CriterionRequirementDTO criterionRequirementDTO : criterionRequirements) {
Criterion criterion = getCriterion(criterionRequirementDTO.name, Criterion criterion = getCriterion(criterionRequirementDTO.name, criterionRequirementDTO.type);
criterionRequirementDTO.type);
if (criterion != null) { if (criterion != null) {
if (criterionRequirementDTO instanceof DirectCriterionRequirementDTO) { if (criterionRequirementDTO instanceof DirectCriterionRequirementDTO) {
DirectCriterionRequirement directCriterionRequirement = getDirectCriterionRequirementByCriterion(
criterionRequirable, criterion); DirectCriterionRequirement directCriterionRequirement =
getDirectCriterionRequirementByCriterion(criterionRequirable, criterion);
if (directCriterionRequirement == null) { if (directCriterionRequirement == null) {
try { try {
criterionRequirable criterionRequirable.addCriterionRequirement(DirectCriterionRequirement.create(criterion));
.addCriterionRequirement(DirectCriterionRequirement
.create(criterion));
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
throw new ValidationException(e.getMessage()); throw new ValidationException(e.getMessage());
} }
} }
} else { // criterionRequirementDTO instanceof } else { // criterionRequirementDTO instanceof IndirectCriterionRequirementDTO
// IndirectCriterionRequirementDTO IndirectCriterionRequirement indirectCriterionRequirement =
IndirectCriterionRequirement indirectCriterionRequirement = getIndirectCriterionRequirementByCriterion( getIndirectCriterionRequirementByCriterion(criterionRequirable, criterion);
criterionRequirable, criterion);
if (indirectCriterionRequirement != null) { if (indirectCriterionRequirement != null) {
indirectCriterionRequirement indirectCriterionRequirement.setValid(((IndirectCriterionRequirementDTO) criterionRequirementDTO).valid);
.setValid(((IndirectCriterionRequirementDTO) criterionRequirementDTO).valid);
} }
} }
} else { } else {
if (criterionRequirementDTO.name == null if (criterionRequirementDTO.name == null || criterionRequirementDTO.type == null) {
|| criterionRequirementDTO.type == null) { throw new ValidationException("the criterion format is incorrect");
throw new ValidationException(
"the criterion format is incorrect");
} else { } else {
throw new ValidationException("the criterion " throw new ValidationException("the criterion " +
+ criterionRequirementDTO.name + " which type is " criterionRequirementDTO.name + " which type is " +
+ criterionRequirementDTO.type + " not found"); criterionRequirementDTO.type + " not found");
} }
} }
} }
@ -346,8 +329,8 @@ public final class OrderElementConverter {
private static DirectCriterionRequirement getDirectCriterionRequirementByCriterion( private static DirectCriterionRequirement getDirectCriterionRequirementByCriterion(
ICriterionRequirable criterionRequirable, Criterion criterion) { ICriterionRequirable criterionRequirable, Criterion criterion) {
for (CriterionRequirement criterionRequirement : criterionRequirable
.getCriterionRequirements()) { for (CriterionRequirement criterionRequirement : criterionRequirable.getCriterionRequirements()) {
if (criterionRequirement instanceof DirectCriterionRequirement) { if (criterionRequirement instanceof DirectCriterionRequirement) {
if (criterionRequirement.getCriterion().isEquivalent(criterion)) { if (criterionRequirement.getCriterion().isEquivalent(criterion)) {
return (DirectCriterionRequirement) criterionRequirement; return (DirectCriterionRequirement) criterionRequirement;
@ -359,8 +342,8 @@ public final class OrderElementConverter {
private static IndirectCriterionRequirement getIndirectCriterionRequirementByCriterion( private static IndirectCriterionRequirement getIndirectCriterionRequirementByCriterion(
ICriterionRequirable criterionRequirable, Criterion criterion) { ICriterionRequirable criterionRequirable, Criterion criterion) {
for (CriterionRequirement criterionRequirement : criterionRequirable
.getCriterionRequirements()) { for (CriterionRequirement criterionRequirement : criterionRequirable.getCriterionRequirements()) {
if (criterionRequirement instanceof IndirectCriterionRequirement) { if (criterionRequirement instanceof IndirectCriterionRequirement) {
if (criterionRequirement.getCriterion().isEquivalent(criterion)) { if (criterionRequirement.getCriterion().isEquivalent(criterion)) {
return (IndirectCriterionRequirement) criterionRequirement; return (IndirectCriterionRequirement) criterionRequirement;
@ -370,30 +353,28 @@ public final class OrderElementConverter {
return null; return null;
} }
private final static OrderElement toEntityExceptCriterionRequirements( private static final OrderElement toEntityExceptCriterionRequirements(
OrderVersion parentOrderVersion, OrderVersion parentOrderVersion,
OrderElementDTO orderElementDTO, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration) ConfigurationOrderElementConverter configuration) {
throws ValidationException {
Validate.notNull(parentOrderVersion); Validate.notNull(parentOrderVersion);
OrderElement orderElement; OrderElement orderElement;
if (orderElementDTO instanceof OrderLineDTO) { if (orderElementDTO instanceof OrderLineDTO) {
checkOrderElementDTOCode(orderElementDTO, "OrderLineDTO"); checkOrderElementDTOCode(orderElementDTO, "OrderLineDTO");
if ((configuration.isHoursGroups())
&& (!((OrderLineDTO) orderElementDTO).hoursGroups.isEmpty())) { if ((configuration.isHoursGroups()) && (!((OrderLineDTO) orderElementDTO).hoursGroups.isEmpty())) {
orderElement = OrderLine.createUnvalidated(orderElementDTO.code); orderElement = OrderLine.createUnvalidated(orderElementDTO.code);
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) { for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
HoursGroup hoursGroup = toEntity(hoursGroupDTO, HoursGroup hoursGroup = toEntity(hoursGroupDTO);
configuration);
((OrderLine) orderElement).addHoursGroup(hoursGroup); ((OrderLine) orderElement).addHoursGroup(hoursGroup);
} }
} else { } else {
orderElement = OrderLine.createUnvalidatedWithUnfixedPercentage(orderElementDTO.code, 0); orderElement = OrderLine.createUnvalidatedWithUnfixedPercentage(orderElementDTO.code, 0);
if (!orderElement.getHoursGroups().isEmpty()) { if (!orderElement.getHoursGroups().isEmpty()) {
orderElement.getHoursGroups().get(0).setCode( orderElement.getHoursGroups().get(0).setCode(UUID.randomUUID().toString());
UUID.randomUUID().toString());
} }
} }
} else { // orderElementDTO instanceof OrderLineGroupDTO } else { // orderElementDTO instanceof OrderLineGroupDTO
@ -402,30 +383,30 @@ public final class OrderElementConverter {
checkOrderElementDTOCode(orderElementDTO, "OrderDTO"); checkOrderElementDTOCode(orderElementDTO, "OrderDTO");
orderElement = Order.createUnvalidated(orderElementDTO.code); orderElement = Order.createUnvalidated(orderElementDTO.code);
Scenario current = Registry.getScenarioManager().getCurrent(); Scenario current = Registry.getScenarioManager().getCurrent();
((Order) orderElement).setVersionForScenario(current, ((Order) orderElement).setVersionForScenario(current, parentOrderVersion);
parentOrderVersion);
((Order) orderElement) ((Order) orderElement).setDependenciesConstraintsHavePriority(
.setDependenciesConstraintsHavePriority(((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority); ((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority);
List<BaseCalendar> calendars = Registry.getBaseCalendarDAO()
.findByName(((OrderDTO) orderElementDTO).calendarName); List<BaseCalendar> calendars =
Registry.getBaseCalendarDAO().findByName(((OrderDTO) orderElementDTO).calendarName);
BaseCalendar calendar; BaseCalendar calendar;
if ((calendars != null) && (calendars.size() == 1)) { if ((calendars != null) && (calendars.size() == 1)) {
calendar = calendars.get(0); calendar = calendars.get(0);
} else { } else {
calendar = Registry.getConfigurationDAO() calendar = Registry.getConfigurationDAO().getConfiguration().getDefaultCalendar();
.getConfiguration().getDefaultCalendar();
} }
((Order) orderElement).setCalendar(calendar); ((Order) orderElement).setCalendar(calendar);
} else { // orderElementDTO instanceof OrderLineGroupDTO } else { // orderElementDTO instanceof OrderLineGroupDTO
checkOrderElementDTOCode(orderElementDTO, "OrderLineGroupDTO"); checkOrderElementDTOCode(orderElementDTO, "OrderLineGroupDTO");
orderElement = OrderLineGroup orderElement = OrderLineGroup.createUnvalidated(orderElementDTO.code);
.createUnvalidated(orderElementDTO.code);
} }
orderElement.useSchedulingDataFor(parentOrderVersion); orderElement.useSchedulingDataFor(parentOrderVersion);
List<OrderElement> children = new ArrayList<OrderElement>(); List<OrderElement> children = new ArrayList<>();
for (OrderElementDTO element : ((OrderLineGroupDTO) orderElementDTO).children) { for (OrderElementDTO element : ((OrderLineGroupDTO) orderElementDTO).children) {
children.add(toEntity(parentOrderVersion, element, children.add(toEntity(parentOrderVersion, element, configuration));
configuration));
} }
for (OrderElement child : children) { for (OrderElement child : children) {
@ -435,27 +416,23 @@ public final class OrderElementConverter {
orderElement.setName(orderElementDTO.name); orderElement.setName(orderElementDTO.name);
orderElement.setCode(orderElementDTO.code); orderElement.setCode(orderElementDTO.code);
orderElement orderElement.setInitDate(DateConverter.toDate(orderElementDTO.initDate));
.setInitDate(DateConverter.toDate(orderElementDTO.initDate)); orderElement.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
orderElement
.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
orderElement.setDescription(orderElementDTO.description); orderElement.setDescription(orderElementDTO.description);
if (configuration.isLabels()) { if (configuration.isLabels()) {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) { for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
try { try {
orderElement.addLabel(LabelReferenceConverter.toEntity(labelDTO)); orderElement.addLabel(Registry.getLabelDAO().findByCode(labelDTO.code));
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code throw new ValidationException("Label " + labelDTO.code + " not found.");
+ " not found.");
} }
} }
} }
if (configuration.isMaterialAssignments()) { if (configuration.isMaterialAssignments()) {
for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) { for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) {
orderElement orderElement.addMaterialAssignment(toEntity(materialAssignmentDTO));
.addMaterialAssignment(toEntity(materialAssignmentDTO));
} }
} }
@ -467,113 +444,87 @@ public final class OrderElementConverter {
} }
private static Criterion getCriterion(String name, String type) { private static Criterion getCriterion(String name, String type) {
List<Criterion> criterions = Registry.getCriterionDAO() List<Criterion> criterions = Registry.getCriterionDAO().findByNameAndType(name, type);
.findByNameAndType(name, type); return criterions.size() != 1 ? null : criterions.get(0);
if (criterions.size() != 1) {
return null;
}
return criterions.get(0);
} }
public static DirectCriterionRequirement toEntity( public static DirectCriterionRequirement toEntity(DirectCriterionRequirementDTO criterionRequirementDTO) {
DirectCriterionRequirementDTO criterionRequirementDTO) { Criterion criterion = getCriterion(criterionRequirementDTO.name, criterionRequirementDTO.type);
Criterion criterion = getCriterion(criterionRequirementDTO.name, return criterion == null ? null : DirectCriterionRequirement.create(criterion);
criterionRequirementDTO.type);
if (criterion == null) {
return null;
} }
return DirectCriterionRequirement.create(criterion); public static final MaterialAssignment toEntity(MaterialAssignmentDTO materialAssignmentDTO) {
} Material material;
public final static MaterialAssignment toEntity(
MaterialAssignmentDTO materialAssignmentDTO) {
Material material = null;
try { try {
material = Registry.getMaterialDAO() material = Registry.getMaterialDAO().findUniqueByCodeInAnotherTransaction(materialAssignmentDTO.materialCode);
.findUniqueByCodeInAnotherTransaction(
materialAssignmentDTO.materialCode);
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
material = Material.create(materialAssignmentDTO.materialCode); material = Material.create(materialAssignmentDTO.materialCode);
material.setDescription("material-" material.setDescription("material-" + materialAssignmentDTO.materialCode);
+ materialAssignmentDTO.materialCode);
MaterialCategory defaultMaterialCategory =
PredefinedMaterialCategories.IMPORTED_MATERIALS_WITHOUT_CATEGORY.getMaterialCategory();
MaterialCategory defaultMaterialCategory = PredefinedMaterialCategories.IMPORTED_MATERIALS_WITHOUT_CATEGORY
.getMaterialCategory();
material.setCategory(defaultMaterialCategory); material.setCategory(defaultMaterialCategory);
/* /* "validate" method avoids that "material" goes to the Hibernate's session if "material" is not valid */
* "validate" method avoids that "material" goes to the Hibernate's
* session if "material" is not valid.
*/
material.validate(); material.validate();
Registry.getMaterialDAO().save(material); Registry.getMaterialDAO().save(material);
material.dontPoseAsTransientObjectAnymore(); material.dontPoseAsTransientObjectAnymore();
} }
MaterialAssignment materialAssignment = MaterialAssignment MaterialAssignment materialAssignment = MaterialAssignment.create(material);
.create(material); materialAssignment.setUnitsWithoutNullCheck(materialAssignmentDTO.units);
materialAssignment materialAssignment.setUnitPriceWithoutNullCheck(materialAssignmentDTO.unitPrice);
.setUnitsWithoutNullCheck(materialAssignmentDTO.units);
materialAssignment
.setUnitPriceWithoutNullCheck(materialAssignmentDTO.unitPrice);
Date estimatedAvailability = DateConverter Date estimatedAvailability = DateConverter.toDate(materialAssignmentDTO.estimatedAvailability);
.toDate(materialAssignmentDTO.estimatedAvailability);
materialAssignment.setEstimatedAvailability(estimatedAvailability); materialAssignment.setEstimatedAvailability(estimatedAvailability);
return materialAssignment; return materialAssignment;
} }
public final static HoursGroup toEntity(HoursGroupDTO hoursGroupDTO, public static final HoursGroup toEntity(HoursGroupDTO hoursGroupDTO) {
ConfigurationOrderElementConverter configuration) { ResourceEnum resourceType = ResourceEnumConverter.fromDTO(hoursGroupDTO.resourceType);
ResourceEnum resourceType = ResourceEnumConverter return HoursGroup.createUnvalidated(hoursGroupDTO.code, resourceType, hoursGroupDTO.workingHours);
.fromDTO(hoursGroupDTO.resourceType);
HoursGroup hoursGroup = HoursGroup.createUnvalidated(
hoursGroupDTO.code, resourceType, hoursGroupDTO.workingHours);
return hoursGroup;
} }
public final static void update(OrderElement orderElement, public static final void update(
OrderElementDTO orderElementDTO, OrderElement orderElement, OrderElementDTO orderElementDTO, ConfigurationOrderElementConverter configuration) {
ConfigurationOrderElementConverter configuration)
throws ValidationException {
update(null, orderElement, orderElementDTO, configuration); update(null, orderElement, orderElementDTO, configuration);
} }
private final static void update(OrderVersion orderVersion, private static final void update(
OrderElement orderElement, OrderElementDTO orderElementDTO, OrderVersion orderVersion, OrderElement orderElement, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration) ConfigurationOrderElementConverter configuration) {
throws ValidationException {
updateExceptCriterionRequirements(orderVersion, orderElement, updateExceptCriterionRequirements(orderVersion, orderElement, orderElementDTO, configuration);
orderElementDTO, configuration);
if (configuration.isCriterionRequirements()) { if (configuration.isCriterionRequirements()) {
addOrCriterionRequirements(orderElement, orderElementDTO); addOrCriterionRequirements(orderElement, orderElementDTO);
} }
} }
private final static void updateExceptCriterionRequirements( private static final void updateExceptCriterionRequirements(
OrderVersion orderVersion, OrderVersion orderVersion,
OrderElement orderElement, OrderElementDTO orderElementDTO, OrderElement orderElement,
ConfigurationOrderElementConverter configuration) OrderElementDTO orderElementDTO,
throws ValidationException { ConfigurationOrderElementConverter configuration) {
OrderVersion newOrderVersion = orderVersion;
if (orderElementDTO instanceof OrderLineDTO) { if (orderElementDTO instanceof OrderLineDTO) {
if (!(orderElement instanceof OrderLine)) { if (!(orderElement instanceof OrderLine)) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Task {0}: Task group is incompatible type with {1}", "Task {0}: Task group is incompatible type with {1}",
orderElement.getCode(), orderElement.getClass() orderElement.getCode(), orderElement.getClass().getName()));
.getName()));
} }
if (configuration.isHoursGroups()) { if (configuration.isHoursGroups()) {
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) { for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
if ( ((OrderLine) orderElement).containsHoursGroup(hoursGroupDTO.code) ) { if ( ((OrderLine) orderElement).containsHoursGroup(hoursGroupDTO.code) ) {
update( ((OrderLine) orderElement) update( ((OrderLine) orderElement).getHoursGroup(hoursGroupDTO.code), hoursGroupDTO);
.getHoursGroup(hoursGroupDTO.code), hoursGroupDTO, configuration);
} else { } else {
((OrderLine) orderElement).addHoursGroup(toEntity(hoursGroupDTO, configuration)); ((OrderLine) orderElement).addHoursGroup(toEntity(hoursGroupDTO));
} }
} }
} }
@ -582,64 +533,51 @@ public final class OrderElementConverter {
if (!(orderElement instanceof Order)) { if (!(orderElement instanceof Order)) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Task {0}: Project is incompatible type with {1}", "Task {0}: Project is incompatible type with {1}",
orderElement.getCode(), orderElement.getClass() orderElement.getCode(), orderElement.getClass().getName()));
.getName()));
} }
Order order = (Order) orderElement; Order order = (Order) orderElement;
orderVersion = order.getOrderVersionFor(Registry newOrderVersion = order.getOrderVersionFor(Registry.getScenarioManager().getCurrent());
.getScenarioManager() order.useSchedulingDataFor(newOrderVersion);
.getCurrent());
order.useSchedulingDataFor(orderVersion);
Boolean dependenciesConstraintsHavePriority = ((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority; Boolean dependenciesConstraintsHavePriority = ((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority;
if (dependenciesConstraintsHavePriority != null) { if (dependenciesConstraintsHavePriority != null) {
((Order) orderElement) ((Order) orderElement).setDependenciesConstraintsHavePriority(dependenciesConstraintsHavePriority);
.setDependenciesConstraintsHavePriority(dependenciesConstraintsHavePriority);
} }
String calendarName = ((OrderDTO) orderElementDTO).calendarName; String calendarName = ((OrderDTO) orderElementDTO).calendarName;
if (calendarName != null) { if (calendarName != null && !((Order) orderElement).getCalendar().getName().equals(calendarName)) {
if (!((Order) orderElement).getCalendar().getName().equals(
calendarName)) { List<BaseCalendar> calendars =
List<BaseCalendar> calendars = Registry Registry.getBaseCalendarDAO().findByName(((OrderDTO) orderElementDTO).calendarName);
.getBaseCalendarDAO()
.findByName(
((OrderDTO) orderElementDTO).calendarName);
if (calendars.size() == 1) { if (calendars.size() == 1) {
((Order) orderElement) ((Order) orderElement).setCalendar(calendars.get(0));
.setCalendar(calendars.get(0));
}
} }
} }
} else { // orderElementDTO instanceof OrderLineGroupDTO } else { // orderElementDTO instanceof OrderLineGroupDTO
if (!(orderElement instanceof OrderLineGroup)) { if (!(orderElement instanceof OrderLineGroup)) {
throw new ValidationException(
MessageFormat throw new ValidationException(MessageFormat.format(
.format("Task {0}: Task group is incompatible type with {1}", "Task {0}: Task group is incompatible type with {1}",
orderElement.getCode(), orderElement.getCode(), orderElement.getClass().getName()));
orderElement.getClass().getName()));
} }
} }
for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) { for (OrderElementDTO childDTO : ((OrderLineGroupDTO) orderElementDTO).children) {
if (orderElement.containsOrderElement(childDTO.code)) { if (orderElement.containsOrderElement(childDTO.code)) {
update(orderVersion, update(newOrderVersion, orderElement.getOrderElement(childDTO.code), childDTO, configuration);
orderElement.getOrderElement(childDTO.code),
childDTO, configuration);
} else { } else {
if (checkConstraintUniqueOrderCode(childDTO)) { if (checkConstraintUniqueOrderCode(childDTO)) {
throw new ValidationException( throw new ValidationException(MessageFormat.format(
MessageFormat.format( "Task {0}: Duplicate code in DB", childDTO.code));
"Task {0}: Duplicate code in DB",
childDTO.code));
} }
if (checkConstraintUniqueHoursGroupCode(childDTO)) { if (checkConstraintUniqueHoursGroupCode(childDTO)) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Hours Group {0}: Duplicate code in DB", "Hours Group {0}: Duplicate code in DB", childDTO.code));
childDTO.code));
} }
((OrderLineGroup) orderElement).add(toEntity(orderVersion, ((OrderLineGroup) orderElement).add(toEntity(newOrderVersion, childDTO, configuration));
childDTO, configuration));
} }
} }
@ -649,11 +587,9 @@ public final class OrderElementConverter {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) { for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
if (!orderElement.containsLabel(labelDTO.code)) { if (!orderElement.containsLabel(labelDTO.code)) {
try { try {
orderElement.addLabel(LabelReferenceConverter orderElement.addLabel(Registry.getLabelDAO().findByCode(labelDTO.code));
.toEntity(labelDTO));
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code throw new ValidationException("Label " + labelDTO.code + " not found");
+ " not found");
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ValidationException(e.getMessage()); throw new ValidationException(e.getMessage());
} }
@ -663,15 +599,10 @@ public final class OrderElementConverter {
if (configuration.isMaterialAssignments()) { if (configuration.isMaterialAssignments()) {
for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) { for (MaterialAssignmentDTO materialAssignmentDTO : orderElementDTO.materialAssignments) {
if (orderElement if (orderElement.containsMaterialAssignment(materialAssignmentDTO.materialCode)) {
.containsMaterialAssignment(materialAssignmentDTO.materialCode)) { update(orderElement.getMaterialAssignment(materialAssignmentDTO.materialCode), materialAssignmentDTO);
update(
orderElement
.getMaterialAssignment(materialAssignmentDTO.materialCode),
materialAssignmentDTO);
} else { } else {
orderElement orderElement.addMaterialAssignment(toEntity(materialAssignmentDTO));
.addMaterialAssignment(toEntity(materialAssignmentDTO));
} }
} }
} }
@ -685,13 +616,11 @@ public final class OrderElementConverter {
} }
if (orderElementDTO.initDate != null) { if (orderElementDTO.initDate != null) {
orderElement.setInitDate(DateConverter orderElement.setInitDate(DateConverter.toDate(orderElementDTO.initDate));
.toDate(orderElementDTO.initDate));
} }
if (orderElementDTO.deadline != null) { if (orderElementDTO.deadline != null) {
orderElement.setDeadline(DateConverter orderElement.setDeadline(DateConverter.toDate(orderElementDTO.deadline));
.toDate(orderElementDTO.deadline));
} }
if (orderElementDTO.description != null) { if (orderElementDTO.description != null) {
@ -701,15 +630,14 @@ public final class OrderElementConverter {
} }
/** /**
* Returns true is there's another {@link OrderElement} in DB with the same code * Returns true is there's another {@link OrderElement} in DB with the same code.
* *
* @param orderElement * @param orderElement
* @return * @return boolean
*/ */
private static boolean checkConstraintUniqueOrderCode(OrderElementDTO orderElement) { private static boolean checkConstraintUniqueOrderCode(OrderElementDTO orderElement) {
try { try {
OrderElement existsByCode = Registry.getOrderElementDAO() OrderElement existsByCode = Registry.getOrderElementDAO().findByCode(orderElement.code);
.findByCode(orderElement.code);
return existsByCode != null; return existsByCode != null;
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
return false; return false;
@ -717,16 +645,13 @@ public final class OrderElementConverter {
} }
/** /**
* Returns true if there's another {@link HoursGroup} in DB with the same code * Returns true if there's another {@link HoursGroup} in DB with the same code.
* *
* @param orderElement * @param orderElement
* @return * @return boolean
*/ */
private static boolean checkConstraintUniqueHoursGroupCode(OrderElementDTO orderElement) { private static boolean checkConstraintUniqueHoursGroupCode(OrderElementDTO orderElement) {
if (orderElement instanceof OrderLineDTO) { return orderElement instanceof OrderLineDTO && checkConstraintUniqueHoursGroupCode((OrderLineDTO) orderElement);
return checkConstraintUniqueHoursGroupCode((OrderLineDTO) orderElement);
}
return false;
} }
private static boolean checkConstraintUniqueHoursGroupCode(OrderLineDTO orderLine) { private static boolean checkConstraintUniqueHoursGroupCode(OrderLineDTO orderLine) {
@ -739,18 +664,15 @@ public final class OrderElementConverter {
return true; return true;
} }
} }
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException ignored) {
// Do nothing // Do nothing
} }
return false; return false;
} }
public final static void update(HoursGroup hoursGroup, public final static void update(HoursGroup hoursGroup, HoursGroupDTO hoursGroupDTO) {
HoursGroupDTO hoursGroupDTO,
ConfigurationOrderElementConverter configuration) {
if (!hoursGroup.getCode().equals(hoursGroupDTO.code)) { if (!hoursGroup.getCode().equals(hoursGroupDTO.code)) {
throw new ValidationException( throw new ValidationException("Not the same hours group, impossible to update");
"Not the same hours group, impossible to update");
} }
if (hoursGroupDTO.workingHours != null) { if (hoursGroupDTO.workingHours != null) {
@ -758,34 +680,30 @@ public final class OrderElementConverter {
} }
if (hoursGroupDTO.resourceType != null) { if (hoursGroupDTO.resourceType != null) {
hoursGroup.setResourceType(ResourceEnumConverter hoursGroup.setResourceType(ResourceEnumConverter.fromDTO(hoursGroupDTO.resourceType));
.fromDTO(hoursGroupDTO.resourceType));
} }
} }
public final static void update(MaterialAssignment materialAssignment, public static final void update(MaterialAssignment materialAssignment, MaterialAssignmentDTO materialAssignmentDTO) {
MaterialAssignmentDTO materialAssignmentDTO) { if (!materialAssignment.getMaterial().getCode().equals(materialAssignmentDTO.materialCode)) {
if (!materialAssignment.getMaterial().getCode().equals( throw new ValidationException("Not the same material, impossible to update");
materialAssignmentDTO.materialCode)) {
throw new ValidationException(
"Not the same material, impossible to update");
} }
if (materialAssignmentDTO.units != null) { if (materialAssignmentDTO.units != null) {
materialAssignment.setUnits(materialAssignmentDTO.units); materialAssignment.setUnits(materialAssignmentDTO.units);
} }
if (materialAssignmentDTO.unitPrice != null) { if (materialAssignmentDTO.unitPrice != null) {
materialAssignment.setUnitPrice(materialAssignmentDTO.unitPrice); materialAssignment.setUnitPrice(materialAssignmentDTO.unitPrice);
} }
if (materialAssignmentDTO.estimatedAvailability != null) { if (materialAssignmentDTO.estimatedAvailability != null) {
Date estimatedAvailability = DateConverter Date estimatedAvailability = DateConverter.toDate(materialAssignmentDTO.estimatedAvailability);
.toDate(materialAssignmentDTO.estimatedAvailability);
materialAssignment.setEstimatedAvailability(estimatedAvailability); materialAssignment.setEstimatedAvailability(estimatedAvailability);
} }
} }
private static void addAdvanceMeasurements(OrderElement orderElement, private static void addAdvanceMeasurements(OrderElement orderElement, OrderElementDTO orderElementDTO) {
OrderElementDTO orderElementDTO) {
if (!orderElementDTO.advanceMeasurements.isEmpty()) { if (!orderElementDTO.advanceMeasurements.isEmpty()) {
DirectAdvanceAssignment directAdvanceAssignment = getDirectAdvanceAssignmentSubcontractor(orderElement); DirectAdvanceAssignment directAdvanceAssignment = getDirectAdvanceAssignmentSubcontractor(orderElement);
@ -793,17 +711,13 @@ public final class OrderElementConverter {
AdvanceMeasurement advanceMeasurement = null; AdvanceMeasurement advanceMeasurement = null;
LocalDate date = null; LocalDate date = null;
if (advanceMeasurementDTO.date != null) { if (advanceMeasurementDTO.date != null) {
date = new LocalDate(DateConverter date = new LocalDate(DateConverter.toLocalDate(advanceMeasurementDTO.date));
.toLocalDate(advanceMeasurementDTO.date)); advanceMeasurement = directAdvanceAssignment.getAdvanceMeasurementAtExactDate(date);
advanceMeasurement = directAdvanceAssignment
.getAdvanceMeasurementAtExactDate(date);
} }
if (advanceMeasurement == null) { if (advanceMeasurement == null) {
advanceMeasurement = AdvanceMeasurement.create(date, advanceMeasurement = AdvanceMeasurement.create(date, advanceMeasurementDTO.value);
advanceMeasurementDTO.value); directAdvanceAssignment.addAdvanceMeasurements(advanceMeasurement);
directAdvanceAssignment
.addAdvanceMeasurements(advanceMeasurement);
} else { } else {
advanceMeasurement.setValue(advanceMeasurementDTO.value); advanceMeasurement.setValue(advanceMeasurementDTO.value);
} }
@ -811,63 +725,49 @@ public final class OrderElementConverter {
} }
} }
private static DirectAdvanceAssignment getDirectAdvanceAssignmentSubcontractor( private static DirectAdvanceAssignment getDirectAdvanceAssignmentSubcontractor(OrderElement orderElement) {
OrderElement orderElement) { DirectAdvanceAssignment directAdvanceAssignment = orderElement.getDirectAdvanceAssignmentSubcontractor();
DirectAdvanceAssignment directAdvanceAssignment = orderElement
.getDirectAdvanceAssignmentSubcontractor();
if (directAdvanceAssignment == null) { if (directAdvanceAssignment == null) {
try { try {
directAdvanceAssignment = orderElement directAdvanceAssignment = orderElement.addSubcontractorAdvanceAssignment();
.addSubcontractorAdvanceAssignment();
} catch (DuplicateValueTrueReportGlobalAdvanceException e) { } catch (DuplicateValueTrueReportGlobalAdvanceException e) {
throw new ValidationException(
MessageFormat throw new ValidationException(MessageFormat.format(
.format("More than one progress marked as report global for task {0}", "More than one progress marked as report global for task {0}", orderElement.getCode()));
orderElement.getCode()));
} catch (DuplicateAdvanceAssignmentForOrderElementException e) { } catch (DuplicateAdvanceAssignmentForOrderElementException e) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Duplicate progress assignment for task {0}", "Duplicate progress assignment for task {0}", orderElement.getCode()));
orderElement.getCode()));
} }
} }
return directAdvanceAssignment; return directAdvanceAssignment;
} }
public static AdvanceMeasurement toEntity( public static AdvanceMeasurement toEntity(AdvanceMeasurementDTO advanceMeasurementDTO) {
AdvanceMeasurementDTO advanceMeasurementDTO) { return AdvanceMeasurement.create(DateConverter.toLocalDate(advanceMeasurementDTO.date), advanceMeasurementDTO.value);
LocalDate date = DateConverter.toLocalDate(advanceMeasurementDTO.date);
AdvanceMeasurement advanceMeasurement = AdvanceMeasurement.create(date,
advanceMeasurementDTO.value);
return advanceMeasurement;
} }
public static AdvanceMeasurementDTO toDTO( public static AdvanceMeasurementDTO toDTO(AdvanceMeasurement advanceMeasurement) {
AdvanceMeasurement advanceMeasurement) { return new AdvanceMeasurementDTO(
XMLGregorianCalendar date = DateConverter DateConverter.toXMLGregorianCalendar(advanceMeasurement.getDate()),
.toXMLGregorianCalendar(advanceMeasurement.getDate()); advanceMeasurement.getValue());
return new AdvanceMeasurementDTO(date, advanceMeasurement
.getValue());
} }
public static EndDateCommunication toEntity( public static EndDateCommunication toEntity(EndDateCommunicationToCustomerDTO endDateCommunicationToCustomerDTO) {
EndDateCommunicationToCustomerDTO endDateCommunicationToCustomerDTO) {
Date endDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.endDate); Date endDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.endDate);
Date communicationDate = DateConverter Date communicationDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.communicationDate);
.toDate(endDateCommunicationToCustomerDTO.communicationDate);
Date saveDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.saveDate); Date saveDate = DateConverter.toDate(endDateCommunicationToCustomerDTO.saveDate);
EndDateCommunication endDateCommunicationToCustomer = EndDateCommunication
.create(saveDate, endDate, communicationDate); return EndDateCommunication.create(saveDate, endDate, communicationDate);
return endDateCommunicationToCustomer;
} }
public static EndDateCommunicationToCustomerDTO toDTO( public static EndDateCommunicationToCustomerDTO toDTO(EndDateCommunication endDateCommunicationToCustomer) {
EndDateCommunication endDateCommunicationToCustomer) { XMLGregorianCalendar endDate = DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getEndDate());
XMLGregorianCalendar endDate = DateConverter XMLGregorianCalendar saveDate = DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getSaveDate());
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getEndDate());
XMLGregorianCalendar saveDate = DateConverter XMLGregorianCalendar communicationDate =
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getSaveDate()); DateConverter.toXMLGregorianCalendar(endDateCommunicationToCustomer.getCommunicationDate());
XMLGregorianCalendar communicationDate = DateConverter
.toXMLGregorianCalendar(endDateCommunicationToCustomer.getCommunicationDate());
return new EndDateCommunicationToCustomerDTO(saveDate, endDate, communicationDate); return new EndDateCommunicationToCustomerDTO(saveDate, endDate, communicationDate);
} }

View file

@ -42,7 +42,7 @@ import org.libreplan.ws.calendars.api.BaseCalendarDTO;
import org.libreplan.ws.calendars.impl.CalendarConverter; import org.libreplan.ws.calendars.impl.CalendarConverter;
import org.libreplan.ws.common.impl.DateConverter; import org.libreplan.ws.common.impl.DateConverter;
import org.libreplan.ws.common.impl.InstanceNotFoundRecoverableErrorException; import org.libreplan.ws.common.impl.InstanceNotFoundRecoverableErrorException;
import org.libreplan.ws.common.impl.RecoverableErrorException; import org.libreplan.ws.costcategories.api.CostCategoryDTO;
import org.libreplan.ws.resources.api.CalendarAvailabilityDTO; import org.libreplan.ws.resources.api.CalendarAvailabilityDTO;
import org.libreplan.ws.resources.api.CriterionSatisfactionDTO; import org.libreplan.ws.resources.api.CriterionSatisfactionDTO;
import org.libreplan.ws.resources.api.MachineDTO; import org.libreplan.ws.resources.api.MachineDTO;
@ -55,23 +55,16 @@ import org.libreplan.ws.resources.criterion.api.CriterionTypeDTO;
/** /**
* Converter from/to resource-related entities to/from DTOs. * Converter from/to resource-related entities to/from DTOs.
*
* @author Fernando Bellas Permuy <fbellas@udc.es> * @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com> * @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/ */
public class ResourceConverter { public class ResourceConverter {
/* private ResourceConverter() {
* These constants should probably be moved to XxxDTO.ENTITY_TYPE }
* if the corresponding DTOs are created in the future.
*/
private final static String RESOURCE_CALENDAR_ENTITY_TYPE =
"resource-calendar";
private final static String COST_CATEGORY_ENTITY_TYPE = "cost-category";
private ResourceConverter() {} public static final Resource toEntity(ResourceDTO resourceDTO) {
public final static Resource toEntity(ResourceDTO resourceDTO)
throws ValidationException, RecoverableErrorException {
checkResourceDTOType(resourceDTO); checkResourceDTOType(resourceDTO);
@ -83,19 +76,14 @@ public class ResourceConverter {
resource = createResourceWithBasicData((WorkerDTO) resourceDTO); resource = createResourceWithBasicData((WorkerDTO) resourceDTO);
} }
addCriterionSatisfactions(resource, addCriterionSatisfactions(resource, resourceDTO.criterionSatisfactions);
resourceDTO.criterionSatisfactions);
setResourceCalendar(resource, resourceDTO.calendar); setResourceCalendar(resource, resourceDTO.calendar);
addResourcesCostCategoryAssignments(resource, addResourcesCostCategoryAssignments(resource, resourceDTO.resourcesCostCategoryAssignments);
resourceDTO.resourcesCostCategoryAssignments);
return resource; return resource;
} }
public final static void updateResource(Resource resource, public static final void updateResource(Resource resource, ResourceDTO resourceDTO) {
ResourceDTO resourceDTO)
throws ValidationException, RecoverableErrorException {
checkResourceDTOType(resourceDTO); checkResourceDTOType(resourceDTO);
@ -103,26 +91,22 @@ public class ResourceConverter {
updateResourceCalendar(resource, resourceDTO.calendar); updateResourceCalendar(resource, resourceDTO.calendar);
updateCriterionSatisfactions(resource, updateCriterionSatisfactions(resource, resourceDTO.criterionSatisfactions);
resourceDTO.criterionSatisfactions);
updateResourcesCostCategoryAssignments(resource, updateResourcesCostCategoryAssignments(resource, resourceDTO.resourcesCostCategoryAssignments);
resourceDTO.resourcesCostCategoryAssignments);
} }
private final static Machine createResourceWithBasicData( private static final Machine createResourceWithBasicData(MachineDTO machineDTO) {
MachineDTO machineDTO) {
return Machine.createUnvalidated return Machine.createUnvalidated(
(StringUtils.trim(machineDTO.code), StringUtils.trim(machineDTO.code),
StringUtils.trim(machineDTO.name), StringUtils.trim(machineDTO.name),
StringUtils.trim(machineDTO.description)); StringUtils.trim(machineDTO.description));
} }
private final static Worker createResourceWithBasicData( private static final Worker createResourceWithBasicData(WorkerDTO workerDTO) {
WorkerDTO workerDTO) {
return Worker.createUnvalidated( return Worker.createUnvalidated(
StringUtils.trim(workerDTO.code), StringUtils.trim(workerDTO.code),
@ -132,23 +116,17 @@ public class ResourceConverter {
} }
private static void addCriterionSatisfactions(Resource resource, private static void addCriterionSatisfactions(Resource resource, List<CriterionSatisfactionDTO> criterionSatisfactions) {
List<CriterionSatisfactionDTO> criterionSatisfactions) {
for (CriterionSatisfactionDTO criterionSatisfactionDTO : for (CriterionSatisfactionDTO criterionSatisfactionDTO : criterionSatisfactions) {
criterionSatisfactions) {
CriterionSatisfaction criterionSatisfaction = CriterionSatisfaction criterionSatisfaction = toEntity(criterionSatisfactionDTO, resource);
toEntity(criterionSatisfactionDTO, resource);
resource.addUnvalidatedSatisfaction(criterionSatisfaction); resource.addUnvalidatedSatisfaction(criterionSatisfaction);
}
} }
} private static CriterionSatisfaction toEntity(CriterionSatisfactionDTO criterionSatisfactionDTO, Resource resource) {
private static CriterionSatisfaction toEntity(
CriterionSatisfactionDTO criterionSatisfactionDTO, Resource resource) {
if (StringUtils.isBlank(criterionSatisfactionDTO.criterionTypeName)) { if (StringUtils.isBlank(criterionSatisfactionDTO.criterionTypeName)) {
throw new ValidationException("criterion type name not specified"); throw new ValidationException("criterion type name not specified");
@ -171,19 +149,16 @@ public class ResourceConverter {
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
if (e.getClassName().equals(CriterionType.class.getName())) { if (e.getClassName().equals(CriterionType.class.getName())) {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
} else { } else {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CriterionDTO.ENTITY_TYPE, e.getKey().toString());
CriterionDTO.ENTITY_TYPE, e.getKey().toString());
} }
} }
} }
private static void setResourceCalendar(Resource resource, private static void setResourceCalendar(Resource resource, ResourceCalendarDTO calendar) {
ResourceCalendarDTO calendar) {
String calendarCode = null; String calendarCode = null;
if (calendar != null) { if (calendar != null) {
calendarCode = calendar.parent; calendarCode = calendar.parent;
@ -193,21 +168,17 @@ public class ResourceConverter {
resource.setResourceCalendar(StringUtils.trim(calendarCode)); resource.setResourceCalendar(StringUtils.trim(calendarCode));
// Copy the data of the resource calendar DTO // Copy the data of the resource calendar DTO
updateBasicPropertiesResourceCalendar(calendar, resource updateBasicPropertiesResourceCalendar(calendar, resource.getCalendar());
.getCalendar());
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(ResourceCalendarDTO.ENTITY_TYPE, e.getKey().toString());
RESOURCE_CALENDAR_ENTITY_TYPE, e.getKey().toString());
} catch (MultipleInstancesException e) { } catch (MultipleInstancesException e) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"there exist multiple resource calendars with name {0}", "there exist multiple resource calendars with name {0}", calendarCode));
calendarCode));
} }
} }
private static void updateBasicPropertiesResourceCalendar( private static void updateBasicPropertiesResourceCalendar(ResourceCalendarDTO calendarDTO, ResourceCalendar calendar) {
ResourceCalendarDTO calendarDTO, ResourceCalendar calendar) {
if (calendarDTO != null) { if (calendarDTO != null) {
if (!StringUtils.isBlank(calendarDTO.name)) { if (!StringUtils.isBlank(calendarDTO.name)) {
@ -217,8 +188,7 @@ public class ResourceConverter {
if (!StringUtils.isBlank(calendarDTO.code)) { if (!StringUtils.isBlank(calendarDTO.code)) {
calendar.setCode(calendarDTO.code); calendar.setCode(calendarDTO.code);
} else { } else {
throw new ValidationException( throw new ValidationException("missing code in the resource calendar");
"missing code in the resource calendar");
} }
if (calendarDTO.capacity != null) { if (calendarDTO.capacity != null) {
@ -229,18 +199,12 @@ public class ResourceConverter {
} }
private static void addResourcesCostCategoryAssignments( private static void addResourcesCostCategoryAssignments(
Resource resource, List<ResourcesCostCategoryAssignmentDTO> Resource resource, List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
resourcesCostCategoryAssignments) {
for (ResourcesCostCategoryAssignmentDTO assignmentDTO : for (ResourcesCostCategoryAssignmentDTO assignmentDTO : resourcesCostCategoryAssignments) {
resourcesCostCategoryAssignments) { ResourcesCostCategoryAssignment assignment = toEntity(assignmentDTO, resource);
ResourcesCostCategoryAssignment assignment = toEntity(assignmentDTO,
resource);
resource.addUnvalidatedResourcesCostCategoryAssignment(assignment); resource.addUnvalidatedResourcesCostCategoryAssignment(assignment);
} }
} }
private static ResourcesCostCategoryAssignment toEntity( private static ResourcesCostCategoryAssignment toEntity(
@ -256,9 +220,9 @@ public class ResourceConverter {
StringUtils.trim(assignmentDTO.costCategoryName), resource, StringUtils.trim(assignmentDTO.costCategoryName), resource,
DateConverter.toLocalDate(assignmentDTO.startDate), DateConverter.toLocalDate(assignmentDTO.startDate),
DateConverter.toLocalDate(assignmentDTO.endDate)); DateConverter.toLocalDate(assignmentDTO.endDate));
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CostCategoryDTO.ENTITY_TYPE, e.getKey().toString());
COST_CATEGORY_ENTITY_TYPE, e.getKey().toString());
} }
} }
@ -271,12 +235,9 @@ public class ResourceConverter {
Machine machine = (Machine) resource; Machine machine = (Machine) resource;
MachineDTO machineDTO = (MachineDTO) resourceDTO; MachineDTO machineDTO = (MachineDTO) resourceDTO;
machine.updateUnvalidated( machine.updateUnvalidated(StringUtils.trim(machineDTO.name), StringUtils.trim(machineDTO.description));
StringUtils.trim(machineDTO.name),
StringUtils.trim(machineDTO.description));
} else if (resource instanceof Worker && } else if (resource instanceof Worker && resourceDTO instanceof WorkerDTO) {
resourceDTO instanceof WorkerDTO) {
Worker worker = (Worker) resource; Worker worker = (Worker) resource;
WorkerDTO workerDTO = (WorkerDTO) resourceDTO; WorkerDTO workerDTO = (WorkerDTO) resourceDTO;
@ -289,38 +250,28 @@ public class ResourceConverter {
} else { } else {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Incompatible update: stored resource is not of type: {0}", "Incompatible update: stored resource is not of type: {0}", resourceDTO.getEntityType()));
resourceDTO.getEntityType()));
} }
} }
/** Do not remove parameters */
private static void updateResourceCalendar(Resource resource, private static void updateResourceCalendar(Resource resource, ResourceCalendarDTO calendarDTO) {
ResourceCalendarDTO calendarDTO) { // TODO Decide policy to update calendar
// (e.g. previous calendar must be removed?, if new calendar is the same as previous, must be reinitialized again?, etc.)
// TODO. Decide policy to update calendar (e.g. previous calendar must
// be removed?, if new calendar is the same as previous, must be
// reinitialized again?, etc.)
} }
private static void updateCriterionSatisfactions(Resource resource, private static void updateCriterionSatisfactions(
List<CriterionSatisfactionDTO> criterionSatisfactions) { Resource resource, List<CriterionSatisfactionDTO> criterionSatisfactions) {
for (CriterionSatisfactionDTO i : criterionSatisfactions) { for (CriterionSatisfactionDTO i : criterionSatisfactions) {
try { try {
CriterionSatisfaction criterionSatisfaction = resource.getCriterionSatisfactionByCode(i.code);
CriterionSatisfaction criterionSatisfaction =
resource.getCriterionSatisfactionByCode(i.code);
updateCriterionSatisfaction(criterionSatisfaction, i); updateCriterionSatisfaction(criterionSatisfaction, i);
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
CriterionSatisfaction criterionSatisfaction = toEntity(i, resource);
CriterionSatisfaction criterionSatisfaction =
toEntity(i, resource);
resource.addUnvalidatedSatisfaction(criterionSatisfaction); resource.addUnvalidatedSatisfaction(criterionSatisfaction);
} }
@ -329,8 +280,7 @@ public class ResourceConverter {
} }
private static void updateCriterionSatisfaction( private static void updateCriterionSatisfaction(
CriterionSatisfaction criterionSatisfaction, CriterionSatisfaction criterionSatisfaction, CriterionSatisfactionDTO criterionSatisfactionDTO) {
CriterionSatisfactionDTO criterionSatisfactionDTO) {
try { try {
@ -343,11 +293,9 @@ public class ResourceConverter {
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
if (e.getClassName().equals(CriterionType.class.getName())) { if (e.getClassName().equals(CriterionType.class.getName())) {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
CriterionTypeDTO.ENTITY_TYPE, e.getKey().toString());
} else { } else {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CriterionDTO.ENTITY_TYPE, e.getKey().toString());
CriterionDTO.ENTITY_TYPE, e.getKey().toString());
} }
} }
@ -355,35 +303,27 @@ public class ResourceConverter {
} }
private static void updateResourcesCostCategoryAssignments( private static void updateResourcesCostCategoryAssignments(
Resource resource, Resource resource, List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignments) {
for (ResourcesCostCategoryAssignmentDTO i : for (ResourcesCostCategoryAssignmentDTO i : resourcesCostCategoryAssignments) {
resourcesCostCategoryAssignments) {
try { try {
ResourcesCostCategoryAssignment assignment = ResourcesCostCategoryAssignment assignment = resource.getResourcesCostCategoryAssignmentByCode(i.code);
resource.getResourcesCostCategoryAssignmentByCode(i.code);
updateResourcesCostCategoryAssignment(assignment, i); updateResourcesCostCategoryAssignment(assignment, i);
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
ResourcesCostCategoryAssignment assignment = ResourcesCostCategoryAssignment assignment = toEntity(i, resource);
toEntity(i, resource);
resource.addUnvalidatedResourcesCostCategoryAssignment( resource.addUnvalidatedResourcesCostCategoryAssignment(assignment);
assignment);
} }
} }
} }
private static void updateResourcesCostCategoryAssignment( private static void updateResourcesCostCategoryAssignment(
ResourcesCostCategoryAssignment assignment, ResourcesCostCategoryAssignment assignment, ResourcesCostCategoryAssignmentDTO i) {
ResourcesCostCategoryAssignmentDTO i) {
try { try {
assignment.updateUnvalidated( assignment.updateUnvalidated(
@ -391,23 +331,16 @@ public class ResourceConverter {
DateConverter.toLocalDate(i.startDate), DateConverter.toLocalDate(i.startDate),
DateConverter.toLocalDate(i.endDate)); DateConverter.toLocalDate(i.endDate));
} catch (InstanceNotFoundException e) { } catch (InstanceNotFoundException e) {
throw new InstanceNotFoundRecoverableErrorException( throw new InstanceNotFoundRecoverableErrorException(CostCategoryDTO.ENTITY_TYPE, e.getKey().toString());
COST_CATEGORY_ENTITY_TYPE, e.getKey().toString());
} }
} }
private static void checkResourceDTOType(ResourceDTO resourceDTO) { private static void checkResourceDTOType(ResourceDTO resourceDTO) {
if (!(resourceDTO instanceof MachineDTO) && if (!(resourceDTO instanceof MachineDTO) && !(resourceDTO instanceof WorkerDTO)) {
!(resourceDTO instanceof WorkerDTO)) {
throw new ValidationException(MessageFormat.format( throw new ValidationException(MessageFormat.format(
"Service does not manage resource of type: {0}", "Service does not manage resource of type: {0}", resourceDTO.getEntityType()));
resourceDTO.getEntityType()));
} }
} }
public static ResourceDTO toDTO(Resource resource) { public static ResourceDTO toDTO(Resource resource) {
@ -420,94 +353,81 @@ public class ResourceConverter {
return null; return null;
} }
List<CriterionSatisfactionDTO> criterionSatisfactionDTOs = new ArrayList<CriterionSatisfactionDTO>(); List<CriterionSatisfactionDTO> criterionSatisfactionDTOs = new ArrayList<>();
for (CriterionSatisfaction criterionSatisfaction : resource for (CriterionSatisfaction criterionSatisfaction : resource.getCriterionSatisfactions()) {
.getCriterionSatisfactions()) {
criterionSatisfactionDTOs.add(toDTO(criterionSatisfaction)); criterionSatisfactionDTOs.add(toDTO(criterionSatisfaction));
} }
resourceDTO.criterionSatisfactions = criterionSatisfactionDTOs; resourceDTO.criterionSatisfactions = criterionSatisfactionDTOs;
List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignmentDTOs = new ArrayList<ResourcesCostCategoryAssignmentDTO>(); List<ResourcesCostCategoryAssignmentDTO> resourcesCostCategoryAssignmentDTOs = new ArrayList<>();
for (ResourcesCostCategoryAssignment resourcesCostCategoryAssignment : resource for (ResourcesCostCategoryAssignment resourcesCostCategoryAssignment : resource.getResourcesCostCategoryAssignments()) {
.getResourcesCostCategoryAssignments()) { resourcesCostCategoryAssignmentDTOs.add(toDTO(resourcesCostCategoryAssignment));
resourcesCostCategoryAssignmentDTOs
.add(toDTO(resourcesCostCategoryAssignment));
} }
resourceDTO.resourcesCostCategoryAssignments = resourcesCostCategoryAssignmentDTOs; resourceDTO.resourcesCostCategoryAssignments = resourcesCostCategoryAssignmentDTOs;
ResourceCalendarDTO resourceCalendarDTO = toDTO(resource.getCalendar()); resourceDTO.calendar = toDTO(resource.getCalendar());
resourceDTO.calendar = resourceCalendarDTO;
return resourceDTO; return resourceDTO;
} }
private static WorkerDTO toDTO(Worker worker) { private static WorkerDTO toDTO(Worker worker) {
return new WorkerDTO(worker.getCode(), worker.getFirstName(), worker return new WorkerDTO(worker.getCode(), worker.getFirstName(), worker.getSurname(), worker.getNif());
.getSurname(), worker.getNif());
} }
private static MachineDTO toDTO(Machine machine) { private static MachineDTO toDTO(Machine machine) {
return new MachineDTO(machine.getCode(), machine.getName(), machine return new MachineDTO(machine.getCode(), machine.getName(), machine.getDescription());
.getDescription());
} }
private static CriterionSatisfactionDTO toDTO( private static CriterionSatisfactionDTO toDTO(CriterionSatisfaction criterionSatisfaction) {
CriterionSatisfaction criterionSatisfaction) { return new CriterionSatisfactionDTO(
return new CriterionSatisfactionDTO(criterionSatisfaction.getCode(), criterionSatisfaction.getCode(),
criterionSatisfaction.getCriterion().getType().getName(), criterionSatisfaction.getCriterion().getType().getName(),
criterionSatisfaction.getCriterion().getName(), DateConverter criterionSatisfaction.getCriterion().getName(),
.toXMLGregorianCalendar(criterionSatisfaction DateConverter.toXMLGregorianCalendar(criterionSatisfaction.getStartDate()),
.getStartDate()), DateConverter DateConverter.toXMLGregorianCalendar(criterionSatisfaction.getEndDate()));
.toXMLGregorianCalendar(criterionSatisfaction
.getEndDate()));
} }
private static ResourcesCostCategoryAssignmentDTO toDTO( private static ResourcesCostCategoryAssignmentDTO toDTO(ResourcesCostCategoryAssignment resourcesCostCategoryAssignment) {
ResourcesCostCategoryAssignment resourcesCostCategoryAssignment) { Date initDate = (resourcesCostCategoryAssignment.getInitDate() == null)
Date initDate = (resourcesCostCategoryAssignment.getInitDate() == null) ? null ? null
: resourcesCostCategoryAssignment.getInitDate() : resourcesCostCategoryAssignment.getInitDate().toDateTimeAtStartOfDay().toDate();
.toDateTimeAtStartOfDay().toDate();
Date endDate = (resourcesCostCategoryAssignment.getEndDate() == null) ? null Date endDate = (resourcesCostCategoryAssignment.getEndDate() == null)
: resourcesCostCategoryAssignment.getEndDate() ? null
.toDateTimeAtStartOfDay().toDate(); : resourcesCostCategoryAssignment.getEndDate().toDateTimeAtStartOfDay().toDate();
return new ResourcesCostCategoryAssignmentDTO( return new ResourcesCostCategoryAssignmentDTO(
resourcesCostCategoryAssignment.getCode(), resourcesCostCategoryAssignment.getCode(),
resourcesCostCategoryAssignment.getCostCategory().getName(), resourcesCostCategoryAssignment.getCostCategory().getName(),
DateConverter.toXMLGregorianCalendar(initDate), DateConverter DateConverter.toXMLGregorianCalendar(initDate),
.toXMLGregorianCalendar(endDate)); DateConverter.toXMLGregorianCalendar(endDate));
} }
public static ResourceCalendarDTO toDTO(ResourceCalendar calendar) { public static ResourceCalendarDTO toDTO(ResourceCalendar calendar) {
BaseCalendarDTO baseCalendarDTO = CalendarConverter.toDTO(calendar); BaseCalendarDTO baseCalendarDTO = CalendarConverter.toDTO(calendar);
List<CalendarAvailabilityDTO> calendarAvailabilityDTOs = new ArrayList<CalendarAvailabilityDTO>(); List<CalendarAvailabilityDTO> calendarAvailabilityDTOs = new ArrayList<>();
for (CalendarAvailability calendarAvailability : calendar for (CalendarAvailability calendarAvailability : calendar.getCalendarAvailabilities()) {
.getCalendarAvailabilities()) {
calendarAvailabilityDTOs.add(toDTO(calendarAvailability)); calendarAvailabilityDTOs.add(toDTO(calendarAvailability));
} }
return new ResourceCalendarDTO(baseCalendarDTO.code, return new ResourceCalendarDTO(
baseCalendarDTO.name, baseCalendarDTO.parent, calendar baseCalendarDTO.code, baseCalendarDTO.name, baseCalendarDTO.parent,
.getCapacity(), baseCalendarDTO.calendarExceptions, calendar.getCapacity(), baseCalendarDTO.calendarExceptions, baseCalendarDTO.calendarData,
baseCalendarDTO.calendarData, calendarAvailabilityDTOs); calendarAvailabilityDTOs);
} }
private static CalendarAvailabilityDTO toDTO( private static CalendarAvailabilityDTO toDTO(CalendarAvailability calendarAvailability) {
CalendarAvailability calendarAvailability) {
Date startDate = calendarAvailability.getStartDate() Date startDate = calendarAvailability.getStartDate().toDateTimeAtStartOfDay().toDate();
.toDateTimeAtStartOfDay().toDate();
Date endDate = null; Date endDate = null;
if (calendarAvailability.getEndDate() != null) { if (calendarAvailability.getEndDate() != null) {
endDate = calendarAvailability.getEndDate() endDate = calendarAvailability.getEndDate().toDateTimeAtStartOfDay().toDate();
.toDateTimeAtStartOfDay().toDate();
} }
return new CalendarAvailabilityDTO(calendarAvailability.getCode(), return new CalendarAvailabilityDTO(calendarAvailability.getCode(), startDate, endDate);
startDate, endDate);
} }
} }

View file

@ -172,7 +172,7 @@ public class SubcontractServiceTest {
@Test @Test
@Transactional @Transactional
/** TODO Test could fail sometimes */ /** FIXME Test could fail sometimes */
public void validSubcontractedTaskData() { public void validSubcontractedTaskData() {
int previous = orderDAO.getOrders().size(); int previous = orderDAO.getOrders().size();