Merge branch 'master' into scenarios

This commit is contained in:
Manuel Rego Casasnovas 2010-04-09 11:16:31 +02:00
commit e6d6cc02b8
185 changed files with 4536 additions and 802 deletions

View file

@ -40,14 +40,6 @@ Database creation
Compilation
-----------
* Download Spring Framework 2.5.6 (http://www.springsource.org/download).
* Execute the following commands::
mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta \
-Dversion=1.0.1B -Dpackaging=jar \
-Dfile=<<spring-framework-2.5.6>>/lib/j2ee/jta.jar
cd xestion-producion
mvn install

View file

@ -5,12 +5,12 @@ Documentación de usuario da aplicación
.. image:: images/logo.png
:align: left
No seguinte documento proporciónase a documentación de axuda necesaria para utilizar a aplicación de xestión da produción do auxiliar do naval Navalpro.
No seguinte documento proporciónase a documentación de axuda necesaria para utilizar a aplicación de xestión da produción do auxiliar do naval NavalPlan.
Esta documentación estó organizada do seguinte modo:
En primeiro lugar descrébense os obxectivos fundamentais da aplicación e o comportamento global da mesma a modo introductorio e como contextualización xeral do uso da mesma.
A continuación introdúcense as entidades básicas que será necesario administrar para poder empregar todas as funcionalidades de Navalpro e que se mencionarán nas seguintes seccións da documentación.
A continuación introdúcense as entidades básicas que será necesario administrar para poder empregar todas as funcionalidades de NavalPlan e que se mencionarán nas seguintes seccións da documentación.
Posteriormente, detállanse os procesos completos de creación de pedidos e proxectos, planificación, asignación de recursos, imputación de avances e extración de resultados.

View file

@ -5,12 +5,12 @@ Documentación de usuario da aplicación
.. image:: images/logo.png
:align: left
No seguinte documento proporciónase a documentación de axuda necesaria para utilizar a aplicación de xestión da produción do auxiliar do naval Navalpro.
No seguinte documento proporciónase a documentación de axuda necesaria para utilizar a aplicación de xestión da produción do auxiliar do naval NavalPlan.
Esta documentación estó organizada do seguinte modo:
En primeiro lugar descrébense os obxectivos fundamentais da aplicación e o comportamento global da mesma a modo introductorio e como contextualización xeral do uso da mesma.
A continuación introdúcense as entidades básicas que será necesario administrar para poder empregar todas as funcionalidades de Navalpro e que se mencionarán nas seguintes seccións da documentación.
A continuación introdúcense as entidades básicas que será necesario administrar para poder empregar todas as funcionalidades de NavalPlan e que se mencionarán nas seguintes seccións da documentación.
Posteriormente, detállanse os procesos completos de creación de pedidos e proxectos, planificación, asignación de recursos, imputación de avances e extración de resultados.

View file

@ -18,7 +18,7 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<?page title="Navalpro: Scheduling"?>
<?page title="NavalPlan: Scheduling"?>
<?init class="org.zkoss.zkplus.databind.AnnotateDataBinderInit" ?>
<?init class="org.zkoss.zk.ui.util.Composition" arg0="/common/layout/template_ganttzk_demo.zul"?>
<?taglib uri="/WEB-INF/tld/i18n.tld" prefix="i18n"?>

View file

@ -54,6 +54,9 @@ import org.zkoss.ganttz.util.script.IScriptsRegister;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.HtmlMacroComponent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.Button;
import org.zkoss.zul.ListModel;
@ -247,6 +250,7 @@ public class Planner extends HtmlMacroComponent {
if (configuration == null) {
return;
}
this.diagramGraph = new GanttDiagramGraph(configuration
.getStartConstraints(), configuration.getEndConstraints(),
configuration.isDependenciesConstraintsHavePriority());
@ -296,6 +300,7 @@ public class Planner extends HtmlMacroComponent {
flattenTree.setVisible(false);
}
listZoomLevels.setSelectedIndex(getZoomLevel().ordinal());
}
private void resettingPreviousComponentsToNull() {
@ -415,6 +420,18 @@ public class Planner extends HtmlMacroComponent {
public void afterCompose() {
super.afterCompose();
listZoomLevels = (Listbox) getFellow("listZoomLevels");
Component westContainer = getFellow("taskdetailsContainer");
westContainer.addEventListener(Events.ON_SIZE, new EventListener() {
@Override
public void onEvent(Event event) throws Exception {
Clients.evalJavaScript("zkTaskContainer.legendResize();");
}
});
}
public TimeTracker getTimeTracker() {

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 227 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 191 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 186 B

View file

@ -52,7 +52,8 @@ planner = self;
<center border="0">
<borderlayout sclass="plannerlayout_center">
<west flex="false" collapsible="true" splittable="true" autoscroll="true" width="300px">
<west flex="false" collapsible="true" splittable="true" autoscroll="true" width="300px"
id="taskdetailsContainer" sclass="taskdetailsContainer">
<div sclass="leftpanelgap" id="insertionPointLeftPanel"></div>
</west>
<center sclass="taskspanel">

View file

@ -47,6 +47,8 @@ DRAGABLE_PADDING = 20; // Drag padding for dependency creation
PERSPECTIVES_WIDTH = 90;
LEGEND_CONTAINER_OFFSET = 75; // Taskdetail width - legend container width
zkTasklist.tooltipTimeout = "";
zkTasklist.showTooltip = function(elem) {
@ -630,6 +632,7 @@ initConstraints : function() {
}
});
/**
*
* taskContainer.js
@ -699,5 +702,11 @@ zkTaskContainer.setClass = function(cmp, newclass) {
cmp.className = newclass;
};
zkTaskContainer.legendResize = function(cmp) {
var taskdetailsContainer = YAHOO.util.Selector.query('.taskdetailsContainer')[0];
var legendContainer = YAHOO.util.Selector.query('.legend-container')[0];
legendContainer.style["width"] = (taskdetailsContainer.clientWidth - LEGEND_CONTAINER_OFFSET )+"px";
};
zkTaskContainer.resizeCompletionAdvance = zkTask.resizeCompletionAdvance;
zkTaskContainer.resizeCompletion2Advance = zkTask.resizeCompletion2Advance;

View file

@ -37,6 +37,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jta_1.0.1B_spec</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>

View file

@ -77,7 +77,7 @@ public class AdvanceMeasurement extends BaseEntity {
public void setValue(BigDecimal value) {
this.value = value;
if (value != null) {
this.value.setScale(2);
this.value.setScale(2, BigDecimal.ROUND_DOWN);
}
resetCommunicationDate();
}

View file

@ -29,7 +29,7 @@ import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.calendars.entities.ResourceCalendar;
import org.navalplanner.business.common.daos.GenericDAOHibernate;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
@ -44,7 +44,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class BaseCalendarDAO extends GenericDAOHibernate<BaseCalendar, Long>
public class BaseCalendarDAO extends IntegrationEntityDAO<BaseCalendar>
implements IBaseCalendarDAO {
@Override

View file

@ -0,0 +1,40 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.calendars.daos;
import org.navalplanner.business.calendars.entities.CalendarData;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* DAO for {@link CalendarData}
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class CalendarDataDAO extends
IntegrationEntityDAO<CalendarData>
implements ICalendarDataDAO {
}

View file

@ -0,0 +1,40 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.calendars.daos;
import org.navalplanner.business.calendars.entities.CalendarException;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
/**
* DAO for {@link CalendarException}
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class CalendarExceptionDAO extends
IntegrationEntityDAO<CalendarException> implements
ICalendarExceptionDAO {
}

View file

@ -23,14 +23,15 @@ package org.navalplanner.business.calendars.daos;
import java.util.List;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.common.daos.IGenericDAO;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
/**
* Contract for {@link BaseCalendarDAO}
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public interface IBaseCalendarDAO extends IGenericDAO<BaseCalendar, Long> {
public interface IBaseCalendarDAO extends
IIntegrationEntityDAO<BaseCalendar> {
List<BaseCalendar> getBaseCalendars();

View file

@ -0,0 +1,34 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.calendars.daos;
import org.navalplanner.business.calendars.entities.CalendarData;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
/**
* Contract for {@link CalendarDataDAO}
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public interface ICalendarDataDAO extends
IIntegrationEntityDAO<CalendarData> {
}

View file

@ -0,0 +1,34 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.calendars.daos;
import org.navalplanner.business.calendars.entities.CalendarException;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
/**
* Contract for {@link CalendarExceptionDAO}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public interface ICalendarExceptionDAO extends
IIntegrationEntityDAO<CalendarException> {
}

View file

@ -30,8 +30,9 @@ import java.util.Set;
import org.hibernate.validator.NotEmpty;
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
import org.navalplanner.business.calendars.daos.IBaseCalendarDAO;
import org.navalplanner.business.calendars.entities.CalendarData.Days;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.planner.entities.ResourcesPerDay;
/**
@ -41,14 +42,12 @@ import org.navalplanner.business.planner.entities.ResourcesPerDay;
* some exceptions of its parent calendar.
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class BaseCalendar extends BaseEntity implements IWorkHours {
public class BaseCalendar extends IntegrationEntity implements IWorkHours {
private static final Integer DEFAULT_VALUE = 0;
public static BaseCalendar create() {
BaseCalendar baseCalendar = new BaseCalendar(CalendarData.create());
baseCalendar.setNewObject(true);
return baseCalendar;
return create(new BaseCalendar(CalendarData.create()));
}
@NotEmpty
@ -938,4 +937,9 @@ public class BaseCalendar extends BaseEntity implements IWorkHours {
return each.getHours() != 0 || each.getType().isOverAssignable();
}
@Override
protected IBaseCalendarDAO getIntegrationEntityDAO() {
return org.navalplanner.business.common.Registry.getBaseCalendarDAO();
}
}

View file

@ -25,19 +25,19 @@ import java.util.HashMap;
import java.util.Map;
import org.joda.time.LocalDate;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.calendars.daos.ICalendarDataDAO;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
/**
* Represents the information about the calendar that can change through time.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class CalendarData extends BaseEntity {
public class CalendarData extends IntegrationEntity {
public static CalendarData create() {
CalendarData calendarData = new CalendarData();
calendarData.setNewObject(true);
return calendarData;
return create(new CalendarData());
}
private Map<Integer, Integer> hoursPerDay;
@ -159,4 +159,9 @@ public class CalendarData extends BaseEntity {
return true;
}
@Override
protected ICalendarDataDAO getIntegrationEntityDAO() {
return Registry.getCalendarDataDAO();
}
}

View file

@ -24,7 +24,9 @@ import java.util.Date;
import org.hibernate.validator.NotNull;
import org.joda.time.LocalDate;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.calendars.daos.ICalendarExceptionDAO;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
/**
* Represents an exceptional day that has a different number of hours. For
@ -34,22 +36,16 @@ import org.navalplanner.business.common.BaseEntity;
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class CalendarException extends BaseEntity {
public class CalendarException extends IntegrationEntity {
public static CalendarException create(Date date, Integer hours,
CalendarExceptionType type) {
CalendarException exceptionDay = new CalendarException(new LocalDate(
date), hours, type);
exceptionDay.setNewObject(true);
return exceptionDay;
return create(new CalendarException(new LocalDate(date), hours, type));
}
public static CalendarException create(LocalDate date, Integer hours,
CalendarExceptionType type) {
CalendarException exceptionDay = new CalendarException(date, hours,
type);
exceptionDay.setNewObject(true);
return exceptionDay;
return create(new CalendarException(date, hours, type));
}
private LocalDate date;
@ -85,4 +81,9 @@ public class CalendarException extends BaseEntity {
return type;
}
@Override
protected ICalendarExceptionDAO getIntegrationEntityDAO() {
return Registry.getCalendarExceptionDAO();
}
}

View file

@ -22,6 +22,8 @@ package org.navalplanner.business.common;
import org.navalplanner.business.advance.daos.IAdvanceTypeDAO;
import org.navalplanner.business.calendars.daos.IBaseCalendarDAO;
import org.navalplanner.business.calendars.daos.ICalendarDataDAO;
import org.navalplanner.business.calendars.daos.ICalendarExceptionDAO;
import org.navalplanner.business.calendars.daos.ICalendarExceptionTypeDAO;
import org.navalplanner.business.common.daos.IConfigurationDAO;
import org.navalplanner.business.costcategories.daos.ICostCategoryDAO;
@ -33,6 +35,7 @@ import org.navalplanner.business.labels.daos.ILabelDAO;
import org.navalplanner.business.labels.daos.ILabelTypeDAO;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
import org.navalplanner.business.materials.daos.IMaterialDAO;
import org.navalplanner.business.materials.daos.IUnitTypeDAO;
import org.navalplanner.business.orders.daos.IHoursGroupDAO;
import org.navalplanner.business.orders.daos.IOrderDAO;
import org.navalplanner.business.orders.daos.IOrderElementDAO;
@ -157,6 +160,12 @@ public class Registry {
@Autowired
private IHourCostDAO hourCostDAO;
@Autowired
private ICalendarExceptionDAO calendarExceptionDAO;
@Autowired
private ICalendarDataDAO calendarDataDAO;
@Autowired
private ICalendarExceptionTypeDAO calendarExceptionTypeDAO;
@ -166,6 +175,9 @@ public class Registry {
@Autowired
private IScenarioManager scenarioManager;
@Autowired
private IUnitTypeDAO unitTypeDAO;
private Registry() {
}
@ -173,6 +185,10 @@ public class Registry {
return singleton;
}
public static IUnitTypeDAO getUnitTypeDAO() {
return getInstance().unitTypeDAO;
}
public static IAdvanceTypeDAO getAdvanceTypeDao() {
return getInstance().advanceTypeDao;
}
@ -299,4 +315,12 @@ public class Registry {
return getInstance().scenarioManager;
}
}
public static ICalendarExceptionDAO getCalendarExceptionDAO() {
return getInstance().calendarExceptionDAO;
}
public static ICalendarDataDAO getCalendarDataDAO() {
return getInstance().calendarDataDAO;
}
}

View file

@ -18,9 +18,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.entities;
package org.navalplanner.business.materials.bootstrap;
import org.navalplanner.business.IDataBootstrap;
import org.navalplanner.business.materials.entities.MaterialCategory;
/**
* Contratct for {@link MaterialCategory}.

View file

@ -18,7 +18,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.entities;
package org.navalplanner.business.materials.bootstrap;
import org.navalplanner.business.calendars.entities.CalendarExceptionType;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;

View file

@ -18,10 +18,11 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.entities;
package org.navalplanner.business.materials.bootstrap;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.MaterialCategory;
/**

View file

@ -1,3 +1,5 @@
/*
* This file is part of NavalPlan
*
@ -18,9 +20,17 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.entities;
package org.navalplanner.business.materials.bootstrap;
import org.navalplanner.business.materials.entities.UnitType;
/**
* Defines the default {@link UnitType}.
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public enum PredefinedUnitTypes {
public enum UnitTypeEnum {
UNITS("units"),
KILOGRAMS("kg"),
KILOMETERS("km"),
@ -32,10 +42,18 @@ public enum UnitTypeEnum {
private String measure;
private UnitTypeEnum(String measure) {
private PredefinedUnitTypes(String measure) {
this.measure = measure;
}
public UnitType createUnitType() {
return UnitType.create(measure);
}
public String getMeasure() {
return measure;
}
public String toString() {
return measure;
}

View file

@ -0,0 +1,56 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.bootstrap;
import org.navalplanner.business.IDataBootstrap;
import org.navalplanner.business.materials.daos.IUnitTypeDAO;
import org.navalplanner.business.materials.entities.UnitType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* Creates the bootstrap of the predefined {@link UnitType}.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@Component
@Scope("singleton")
public class UnitTypeBootstrap implements IDataBootstrap {
@Autowired
private IUnitTypeDAO unitTypeDAO;
@Transactional
@Override
public void loadRequiredData() {
for (PredefinedUnitTypes predefinedUnitType : PredefinedUnitTypes
.values()) {
if (!unitTypeDAO
.existsUnitTypeByNameInAnotherTransaction(predefinedUnitType
.getMeasure())) {
unitTypeDAO.save(predefinedUnitType.createUnitType());
}
}
}
}

View file

@ -22,7 +22,7 @@ package org.navalplanner.business.materials.daos;
import java.util.List;
import org.navalplanner.business.common.daos.IGenericDAO;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
@ -33,7 +33,8 @@ import org.navalplanner.business.materials.entities.MaterialCategory;
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
* @author Diego Pino Garcia <dpino@igalia.com>
*/
public interface IMaterialCategoryDAO extends IGenericDAO<MaterialCategory, Long> {
public interface IMaterialCategoryDAO extends
IIntegrationEntityDAO<MaterialCategory> {
/**
* Returns true if {@link MaterialCategory} exists

View file

@ -23,7 +23,7 @@ package org.navalplanner.business.materials.daos;
import java.util.List;
import java.util.Set;
import org.navalplanner.business.common.daos.IGenericDAO;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
@ -37,7 +37,7 @@ import org.navalplanner.business.orders.entities.Order;
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
* @author Diego Pino Garcia <dpino@igalia.com>
*/
public interface IMaterialDAO extends IGenericDAO<Material, Long> {
public interface IMaterialDAO extends IIntegrationEntityDAO<Material> {
/**
* Returns true if {@link Material} exits

View file

@ -0,0 +1,42 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.daos;
import java.util.List;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.UnitType;
/**
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public interface IUnitTypeDAO extends IIntegrationEntityDAO<UnitType> {
List<UnitType> getAll();
UnitType findByName(String measure) throws InstanceNotFoundException;
UnitType findUniqueByNameInAnotherTransaction(String measure)
throws InstanceNotFoundException;
boolean existsUnitTypeByNameInAnotherTransaction(String measure);
}

View file

@ -23,8 +23,9 @@ package org.navalplanner.business.materials.daos;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.navalplanner.business.common.daos.GenericDAOHibernate;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.springframework.beans.factory.config.BeanDefinition;
@ -40,7 +41,8 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MaterialCategoryDAO extends GenericDAOHibernate<MaterialCategory, Long> implements
public class MaterialCategoryDAO extends IntegrationEntityDAO<MaterialCategory>
implements
IMaterialCategoryDAO {
@Override
@ -87,4 +89,10 @@ public class MaterialCategoryDAO extends GenericDAOHibernate<MaterialCategory, L
return findUniqueByName(name);
}
@Override
public List<MaterialCategory> findAll() {
return getSession().createCriteria(MaterialCategory.class).add(
Restrictions.isNull("parent")).addOrder(Order.asc("code"))
.list();
}
}

View file

@ -28,7 +28,7 @@ import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.navalplanner.business.common.daos.GenericDAOHibernate;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
@ -50,7 +50,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class MaterialDAO extends GenericDAOHibernate<Material, Long> implements
public class MaterialDAO extends IntegrationEntityDAO<Material> implements
IMaterialDAO {
@Override

View file

@ -0,0 +1,87 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.daos;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Restrictions;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.entities.UnitType;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* DAO for {@link UnitType}
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class UnitTypeDAO extends IntegrationEntityDAO<UnitType> implements
IUnitTypeDAO {
@Override
public List<UnitType> getAll() {
return list(UnitType.class);
}
@Override
public UnitType findByName(String measure) throws InstanceNotFoundException {
if (StringUtils.isBlank(measure)) {
throw new InstanceNotFoundException(null, getEntityClass()
.getName());
}
UnitType unitType = (UnitType) getSession().createCriteria(
UnitType.class).add(
Restrictions.eq("measure", measure)).uniqueResult();
if (unitType == null) {
throw new InstanceNotFoundException(measure, getEntityClass()
.getName());
} else {
return unitType;
}
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public UnitType findUniqueByNameInAnotherTransaction(String measure)
throws InstanceNotFoundException {
return findByName(measure);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public boolean existsUnitTypeByNameInAnotherTransaction(String measure) {
try {
findByName(measure);
} catch (InstanceNotFoundException e) {
return false;
}
return true;
}
}

View file

@ -22,32 +22,26 @@ package org.navalplanner.business.materials.entities;
import java.math.BigDecimal;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.NotEmpty;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.NotNull;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.daos.IMaterialDAO;
/**
* Material entity
*
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
*
*/
public class Material extends BaseEntity implements Comparable {
@NotEmpty(message = "code not specified")
private String code;
public class Material extends IntegrationEntity implements Comparable {
private String description;
private BigDecimal defaultUnitPrice = new BigDecimal(0);
private UnitTypeEnum unitType;
private UnitType unitType;
private boolean disabled;
private Boolean disabled;
@NotNull
private MaterialCategory category = null;
@ -58,11 +52,38 @@ public class Material extends BaseEntity implements Comparable {
}
public static Material create(String code) {
return (Material) create(new Material(code));
return (Material) create(new Material(), code);
}
public static Material createUnvalidated(String code, String description,
BigDecimal defaultPrice, Boolean disabled) {
Material material = create(new Material(), code);
material.description = description;
material.defaultUnitPrice = defaultPrice;
material.disabled = disabled;
return material;
}
public void updateUnvalidated(String description,
BigDecimal defaultUnitPrice,
Boolean disabled) {
if (!StringUtils.isBlank(description)) {
this.description = description;
}
if (defaultUnitPrice != null) {
this.defaultUnitPrice = defaultUnitPrice;
}
if (disabled != null) {
this.disabled = disabled;
}
}
protected Material(String code) {
this.code = code;
this.setCode(code);
}
public MaterialCategory getCategory() {
@ -73,14 +94,6 @@ public class Material extends BaseEntity implements Comparable {
this.category = category;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDescription() {
return description;
}
@ -89,11 +102,11 @@ public class Material extends BaseEntity implements Comparable {
this.description = description;
}
public boolean getDisabled() {
return disabled;
public Boolean getDisabled() {
return disabled == null ? false : disabled;
}
public void setDisabled(boolean disabled) {
public void setDisabled(Boolean disabled) {
this.disabled = disabled;
}
@ -105,45 +118,23 @@ public class Material extends BaseEntity implements Comparable {
this.defaultUnitPrice = defaultUnitPrice;
}
public UnitTypeEnum getUnitType() {
public UnitType getUnitType() {
return unitType;
}
public void setUnitType(UnitTypeEnum unitType) {
public void setUnitType(UnitType unitType) {
this.unitType = unitType;
}
@Override
public int compareTo(Object arg0) {
final Material material = (Material) arg0;
return code.compareTo(material.getCode());
return getCode().compareTo(material.getCode());
}
@AssertTrue(message="materialcode has to be unique. It is already used")
public boolean checkConstraintUniqueCode() {
boolean result;
if (isNewObject()) {
result = !existsMaterialWithTheCode();
} else {
result = isIfExistsTheExistentMaterialThisOne();
}
return result;
}
private boolean existsMaterialWithTheCode() {
IMaterialDAO materialDAO = Registry.getMaterialDAO();
return materialDAO.existsMaterialWithCodeInAnotherTransaction(code);
}
private boolean isIfExistsTheExistentMaterialThisOne() {
IMaterialDAO materialDAO = Registry.getMaterialDAO();
try {
Material material =
materialDAO.findUniqueByCodeInAnotherTransaction(code);
return material.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
}
@Override
protected IMaterialDAO getIntegrationEntityDAO() {
return Registry.getMaterialDAO();
}
}

View file

@ -26,10 +26,12 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.Valid;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
@ -40,7 +42,7 @@ import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
*
*/
public class MaterialCategory extends BaseEntity {
public class MaterialCategory extends IntegrationEntity {
public static List<Material> getAllMaterialsFrom(
Collection<? extends MaterialCategory> categories) {
@ -71,6 +73,20 @@ public class MaterialCategory extends BaseEntity {
return (MaterialCategory) create(new MaterialCategory(name));
}
public static MaterialCategory createUnvalidated(String code, String name) {
MaterialCategory materialCategory = create(new MaterialCategory(), code);
materialCategory.name = name;
return materialCategory;
}
public void updateUnvalidated(String name) {
if (!StringUtils.isBlank(name)) {
this.name = name;
}
}
protected MaterialCategory(String name) {
this.name = name;
}
@ -144,4 +160,91 @@ public class MaterialCategory extends BaseEntity {
}
}
public Material getMaterialByCode(String code)
throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(code, Material.class.getName());
}
for (Material m : this.materials) {
if (m.getCode().equalsIgnoreCase(StringUtils.trim(code))) {
return m;
}
}
throw new InstanceNotFoundException(code, Material.class.getName());
}
public MaterialCategory getSubcategoryByCode(String code)
throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(code, MaterialCategory.class
.getName());
}
for (MaterialCategory s : this.subcategories) {
if (s.getCode().equalsIgnoreCase(StringUtils.trim(code))) {
return s;
}
}
throw new InstanceNotFoundException(code, MaterialCategory.class
.getName());
}
@Override
protected IMaterialCategoryDAO getIntegrationEntityDAO() {
return Registry.getMaterialCategoryDAO();
}
@SuppressWarnings("unused")
@AssertTrue(message = "The subcategories names must be unique.")
public boolean checkConstraintUniqueSubcategoryName() {
Set<String> subcategoriesNames = new HashSet<String>();
for (MaterialCategory mc : this.getAllSubcategories()) {
if (!StringUtils.isBlank(mc.getName())) {
String name = StringUtils.deleteWhitespace(mc.getName()
.toLowerCase());
if (subcategoriesNames.contains(name)) {
return false;
} else {
subcategoriesNames.add(name);
}
}
}
return true;
}
@AssertTrue
public boolean checkConstraintNonRepeatedMaterialCategoryCodes() {
Set<MaterialCategory> allSubcategories = getAllSubcategories();
allSubcategories.add(this);
return getFirstRepeatedCode(allSubcategories) == null;
}
private Set<MaterialCategory> getAllSubcategories() {
Set<MaterialCategory> result = new HashSet<MaterialCategory>(subcategories);
for (MaterialCategory subcategory : subcategories) {
result.addAll(subcategory.getAllSubcategories());
}
return result;
}
@AssertTrue
public boolean checkConstraintNonRepeatedMaterialCodes() {
Set<Material> allMaterials = getAllMaterials();
return getFirstRepeatedCode(allMaterials) == null;
}
private Set<Material> getAllMaterials() {
Set<Material> result = new HashSet<Material>(materials);
for (MaterialCategory subcategory : subcategories) {
result.addAll(subcategory.getAllMaterials());
}
return result;
}
}

View file

@ -0,0 +1,104 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.business.materials.entities;
import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.AssertTrue;
import org.hibernate.validator.NotEmpty;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.materials.daos.IUnitTypeDAO;
/**
* UnitType entity
*
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*
*/
public class UnitType extends IntegrationEntity{
public static UnitType create(String code, String measure) {
return (UnitType) create(new UnitType(measure), code);
}
public static UnitType create(String measure) {
return (UnitType) create(new UnitType(measure));
}
public void updateUnvalidated(String measure) {
if (!StringUtils.isBlank(measure)) {
this.measure = measure;
}
}
private String measure;
// Default constructor, needed by Hibernate
protected UnitType() {
}
private UnitType(String measure) {
this.measure = measure;
}
@NotEmpty(message = "measure not specified")
public String getMeasure() {
return measure;
}
public void setMeasure(String measure) {
this.measure = measure;
}
@AssertTrue(message = "the measure unit type has to be unique. It is already used")
public boolean checkConstraintUniqueName() {
boolean result;
if (isNewObject()) {
result = !existsUnitTypeWithTheName();
} else {
result = isIfExistsTheExistentUnitTypeThisOne();
}
return result;
}
private boolean existsUnitTypeWithTheName() {
IUnitTypeDAO unitTypeDAO = Registry.getUnitTypeDAO();
return unitTypeDAO.existsUnitTypeByNameInAnotherTransaction(measure);
}
private boolean isIfExistsTheExistentUnitTypeThisOne() {
IUnitTypeDAO unitTypeDAO = Registry.getUnitTypeDAO();
try {
UnitType unitType = unitTypeDAO
.findUniqueByNameInAnotherTransaction(measure);
return unitType.getId().equals(getId());
} catch (InstanceNotFoundException e) {
return true;
}
}
@Override
protected IUnitTypeDAO getIntegrationEntityDAO() {
return Registry.getUnitTypeDAO();
}
}

View file

@ -23,11 +23,11 @@ package org.navalplanner.business.orders.daos;
import java.util.Date;
import java.util.List;
import org.navalplanner.business.common.daos.IGenericDAO;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.planner.entities.Task;
import org.navalplanner.business.reports.dtos.OrderCostsPerResourceDTO;
import org.navalplanner.business.users.entities.User;
import org.navalplanner.business.planner.entities.Task;
/**
* Contract for {@link OrderDAO}
@ -36,7 +36,7 @@ import org.navalplanner.business.planner.entities.Task;
* @author Diego Pino Garcia <dpino@igalia.com>
* @author Jacobo Aragunde Pérez <jaragunde@igalia.com>
*/
public interface IOrderDAO extends IGenericDAO<Order, Long> {
public interface IOrderDAO extends IIntegrationEntityDAO<Order> {
/**
* Gets all the orders.

View file

@ -23,7 +23,7 @@ package org.navalplanner.business.orders.daos;
import java.math.BigDecimal;
import java.util.List;
import org.navalplanner.business.common.daos.IGenericDAO;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
@ -35,12 +35,10 @@ import org.navalplanner.business.templates.entities.OrderElementTemplate;
* @author Diego Pino García <dpino@igalia.com>
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public interface IOrderElementDAO extends IGenericDAO<OrderElement, Long> {
public interface IOrderElementDAO extends IIntegrationEntityDAO<OrderElement> {
public List<OrderElement> findWithoutParent();
public List<OrderElement> findByCode(String code);
public OrderElement findUniqueByCode(String code)
throws InstanceNotFoundException;

View file

@ -25,9 +25,11 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.joda.time.LocalDate;
import org.navalplanner.business.common.daos.GenericDAOHibernate;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.costcategories.daos.CostCategoryDAO;
import org.navalplanner.business.costcategories.daos.ITypeOfWorkHoursDAO;
@ -48,7 +50,6 @@ import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Dao for {@link Order}
*
@ -58,7 +59,7 @@ import org.springframework.transaction.annotation.Transactional;
*/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class OrderDAO extends GenericDAOHibernate<Order, Long> implements
public class OrderDAO extends IntegrationEntityDAO<Order> implements
IOrderDAO {
@Autowired
@ -230,4 +231,32 @@ public class OrderDAO extends GenericDAOHibernate<Order, Long> implements
}
}
@Override
public List<Order> findAll() {
return getSession().createCriteria(getEntityClass()).addOrder(
org.hibernate.criterion.Order.asc("infoComponent.code")).list();
}
@SuppressWarnings("unchecked")
@Override
public Order findByCode(String code) throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(null, getEntityClass()
.getName());
}
Order entity = (Order) getSession().createCriteria(getEntityClass())
.add(
Restrictions.eq("infoComponent.code", code.trim())
.ignoreCase()).uniqueResult();
if (entity == null) {
throw new InstanceNotFoundException(code, getEntityClass()
.getName());
} else {
return entity;
}
}
}

View file

@ -27,12 +27,13 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.navalplanner.business.common.IAdHocTransactionService;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.common.daos.GenericDAOHibernate;
import org.navalplanner.business.common.daos.IntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.orders.entities.Order;
import org.navalplanner.business.orders.entities.OrderElement;
@ -59,7 +60,7 @@ import org.springframework.transaction.annotation.Transactional;
**/
@Repository
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class OrderElementDAO extends GenericDAOHibernate<OrderElement, Long>
public class OrderElementDAO extends IntegrationEntityDAO<OrderElement>
implements IOrderElementDAO {
@Autowired
@ -209,10 +210,34 @@ public class OrderElementDAO extends GenericDAOHibernate<OrderElement, Long>
}
@Override
public List<OrderElement> findByCode(String code) {
Criteria c = getSession().createCriteria(OrderElement.class);
c.add(Restrictions.eq("infoComponent.code", code).ignoreCase());
return (List<OrderElement>) c.list();
public List<OrderElement> findAll() {
return getSession().createCriteria(getEntityClass()).addOrder(
org.hibernate.criterion.Order.asc("infoComponent.code")).list();
}
@SuppressWarnings("unchecked")
@Override
public OrderElement findByCode(String code)
throws InstanceNotFoundException {
if (StringUtils.isBlank(code)) {
throw new InstanceNotFoundException(null, getEntityClass()
.getName());
}
OrderElement entity = (OrderElement) getSession().createCriteria(
getEntityClass())
.add(
Restrictions.eq("infoComponent.code", code.trim())
.ignoreCase()).uniqueResult();
if (entity == null) {
throw new InstanceNotFoundException(code, getEntityClass()
.getName());
} else {
return entity;
}
}
public List<OrderElement> findByTemplate(OrderElementTemplate template) {

View file

@ -59,6 +59,13 @@ public class Order extends OrderLineGroup {
return order;
}
public static Order createUnvalidated(String code) {
Order order = create(new Order(), code);
OrderLineGroup.setupOrderLineGroup(order);
return order;
}
/**
* Constructor for hibernate. Do not use!
*/
@ -72,7 +79,6 @@ public class Order extends OrderLineGroup {
private Boolean dependenciesConstraintsHavePriority;
@NotNull(message = "order calendar not specified")
private BaseCalendar calendar;
private Boolean codeAutogenerated = false;
@ -285,6 +291,7 @@ public class Order extends OrderLineGroup {
this.calendar = calendar;
}
@NotNull(message = "order calendar not specified")
public BaseCalendar getCalendar() {
return calendar;
}

View file

@ -42,8 +42,9 @@ import org.navalplanner.business.advance.entities.DirectAdvanceAssignment;
import org.navalplanner.business.advance.entities.IndirectAdvanceAssignment;
import org.navalplanner.business.advance.exceptions.DuplicateAdvanceAssignmentForOrderElementException;
import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlobalAdvanceException;
import org.navalplanner.business.common.BaseEntity;
import org.navalplanner.business.common.IntegrationEntity;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.labels.entities.Label;
@ -62,7 +63,7 @@ import org.navalplanner.business.requirements.entities.IndirectCriterionRequirem
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.navalplanner.business.trees.ITreeNode;
public abstract class OrderElement extends BaseEntity implements
public abstract class OrderElement extends IntegrationEntity implements
ICriterionRequirable, ITreeNode<OrderElement> {
private InfoComponent infoComponent = new InfoComponent();
@ -1023,4 +1024,8 @@ public abstract class OrderElement extends BaseEntity implements
return (measuredProgress.compareTo(new BigDecimal(100)) == 0);
}
@Override
protected IIntegrationEntityDAO<OrderElement> getIntegrationEntityDAO() {
return Registry.getOrderElementDAO();
}
}

View file

@ -51,6 +51,17 @@ public class OrderLine extends OrderElement {
return result;
}
public static OrderLine createUnvalidated(String code) {
OrderLine orderLine = create(new OrderLine(), code);
return orderLine;
}
public static OrderLine createUnvalidatedWithUnfixedPercentage(String code,
int hours) {
OrderLine orderLine = createOrderLineWithUnfixedPercentage(hours);
return create(orderLine, code);
}
public static OrderLine createOrderLineWithUnfixedPercentage(int hours) {
OrderLine result = create();
HoursGroup hoursGroup = HoursGroup.create(result);

View file

@ -109,6 +109,12 @@ public class OrderLineGroup extends OrderElement implements
return result;
}
public static OrderLineGroup createUnvalidated(String code) {
OrderLineGroup orderLineGroup = create(new OrderLineGroup(), code);
setupOrderLineGroup(orderLineGroup);
return orderLineGroup;
}
protected static void setupOrderLineGroup(OrderLineGroup result) {
IndirectAdvanceAssignment indirectAdvanceAssignment = IndirectAdvanceAssignment
.create(true);

View file

@ -21,6 +21,7 @@
package org.navalplanner.business.planner.entities;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.SortedMap;
import java.util.SortedSet;
@ -119,8 +120,7 @@ public class HoursCostCalculator implements ICostCalculator {
}
for (WorkReportLine workReportLine : workReportLines) {
LocalDate day = new LocalDate(workReportLine.getWorkReport()
.getDate());
LocalDate day = new LocalDate(workReportLine.getDate());
BigDecimal cost = new BigDecimal(workReportLine.getNumHours());
if (!result.containsKey(day)) {

View file

@ -19,6 +19,9 @@
*/
package org.navalplanner.business.resources.entities;
import static org.navalplanner.business.i18n.I18nHelper._;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -91,6 +94,8 @@ public abstract class Resource extends IntegrationEntity {
private Set<ResourcesCostCategoryAssignment> resourcesCostCategoryAssignments =
new HashSet<ResourcesCostCategoryAssignment>();
private Boolean limitingResource = Boolean.FALSE;
private void clearCachedData() {
assignmentsByDayCached = null;
}
@ -1041,4 +1046,16 @@ public abstract class Resource extends IntegrationEntity {
return Registry.getResourceDAO();
}
public Boolean isLimitingResource() {
return limitingResource;
}
public void setLimitingResource(Boolean limitingResource) {
this.limitingResource = limitingResource;
}
public String getLimitingResourceAsString() {
return (Boolean.TRUE.equals(isLimitingResource())) ? _("yes") : _("no");
}
}

View file

@ -93,4 +93,9 @@ public class VirtualWorker extends Worker {
}
}
@Override
public Boolean isLimitingResource() {
return false;
}
}

View file

@ -12,6 +12,8 @@
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" access="field"/>
<set name="exceptions" access="field" cascade="all-delete-orphan">
@ -49,6 +51,8 @@
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="date" access="field"
type="org.joda.time.contrib.hibernate.PersistentLocalDate"/>
<property name="hours" access="field"/>
@ -83,6 +87,8 @@
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<map name="hoursPerDay">
<key column="BASE_CALENDAR_ID"/>
<index column="DAY_ID" type="integer" />

View file

@ -17,11 +17,7 @@
<property name="defaultUnitPrice" column="default_unit_price" />
<property name="unitType" column="unit_type" >
<type name="org.hibernate.type.EnumType">
<param name="enumClass">org.navalplanner.business.materials.entities.UnitTypeEnum</param>
</type>
</property>
<many-to-one name="unitType" class="UnitType" column="unit_type" />
<property name="disabled"/>
@ -29,6 +25,21 @@
</class>
<!-- UnitType -->
<class name="UnitType" table="UNIT_TYPE">
<id name="id" type="long" access="property">
<generator class="hilo">
<param name="max_lo">100</param>
</generator>
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="measure" access="field"/>
</class>
<!-- MaterialCategory -->
<class name="MaterialCategory" table="MATERIAL_CATEGORY">
<id name="id" type="long" access="property">
@ -38,6 +49,8 @@
</id>
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="name" />
<set name="subcategories" inverse="true" cascade="all-delete-orphan">

View file

@ -12,7 +12,11 @@
Hibernate infers type="integer".
-->
<version name="version" access="property" type="long" />
<property name="code" access="property" not-null="true" unique="true"/>
<property name="limitingResource" column="LIMITED_RESOURCE" not-null="true"/>
<set access="field" cascade="all-delete-orphan" inverse="true" name="criterionSatisfactions">
<key column="resource" not-null="true"/>
<one-to-many class="CriterionSatisfaction"/>
@ -167,4 +171,4 @@
<many-to-one access="field" name="worker" class="Worker" column="worker_id" />
</class>
</hibernate-mapping>
</hibernate-mapping>

View file

@ -166,6 +166,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</dependency>
<dependency>
<groupId>org.apache.geronimo.specs</groupId>
<artifactId>geronimo-jta_1.0.1B_spec</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>

View file

@ -33,12 +33,22 @@ public interface IMultipleFiltersFinder {
void init();
/**
* Return the FilterPair list match with filter.
* @param filter
* @return List<FilterPair>
*/
List<FilterPair> getMatching(String filter);
List<FilterPair> getFirstTenFilters();
String objectToString(Object obj);
/**
* Return the new filter that is lower case and without white spaces.
* @param inputText
* @return
*/
String getNewFilterText(String inputText);
boolean isValidNewFilter(Object obj);

View file

@ -25,6 +25,7 @@ import static org.navalplanner.web.I18nHelper._;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.common.IAdHocTransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.zkoss.zul.Listcell;
@ -72,11 +73,8 @@ public abstract class MultipleFiltersFinder implements IMultipleFiltersFinder {
}
public String getNewFilterText(String inputText) {
String newFilterText = new String("");
String[] filtersText = inputText.split(",");
newFilterText = getLastText(filtersText);
newFilterText = newFilterText.replace(" ", "");
newFilterText = newFilterText.trim();
String newFilterText = getLastText(filtersText);
return newFilterText;
}
@ -85,7 +83,7 @@ public abstract class MultipleFiltersFinder implements IMultipleFiltersFinder {
if (texts.length > 0) {
return texts[last];
} else {
return "";
return new String("");
}
}
@ -103,7 +101,7 @@ public abstract class MultipleFiltersFinder implements IMultipleFiltersFinder {
}
filterValues = updateDeletedFilters(filterValues, value);
value = value.replace(" ", "");
value = StringUtils.deleteWhitespace(value);
String[] values = value.split(",");
if (values.length != filterValues.size()) {
return false;
@ -142,7 +140,7 @@ public abstract class MultipleFiltersFinder implements IMultipleFiltersFinder {
private boolean isFilterAdded(String[] values, String filter) {
for (int i = 0; i < values.length; i++) {
String value = values[i].replace(" ", "");
filter = filter.replace(" ", "");
filter = StringUtils.deleteWhitespace(filter);
if (filter.equals(value)) {
return true;

View file

@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.labels.daos.ILabelDAO;
import org.navalplanner.business.labels.daos.ILabelTypeDAO;
@ -151,7 +152,7 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
public List<FilterPair> getMatching(String filter) {
getListMatching().clear();
if ((filter != null) && (!filter.isEmpty())) {
filter = filter.toLowerCase();
filter = StringUtils.deleteWhitespace(filter.toLowerCase());
searchInCriterionTypes(filter);
searchInLabelTypes(filter);
}
@ -163,7 +164,9 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterionTypes(String filter) {
boolean limited = (filter.length() < 3);
for (CriterionType type : mapCriterions.keySet()) {
if (type.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
setFilterPairCriterionType(type, limited);
} else {
searchInCriterions(type, filter);
@ -173,7 +176,9 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterions(CriterionType type, String filter) {
for (Criterion criterion : mapCriterions.get(type)) {
if (criterion.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(criterion.getName()
.toLowerCase());
if (name.contains(filter)) {
addCriterion(type, criterion);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -194,7 +199,9 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabelTypes(String filter) {
boolean limited = (filter.length() < 3);
for (LabelType type : mapLabels.keySet()) {
if (type.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
setFilterPairLabelType(type, limited);
} else {
searchInLabels(type, filter);
@ -204,7 +211,9 @@ public class OrderElementsMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabels(LabelType type, String filter) {
for (Label label : mapLabels.get(type)) {
if (label.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(label.getName()
.toLowerCase());
if (name.contains(filter)) {
addLabel(type, label);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;

View file

@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.externalcompanies.daos.IExternalCompanyDAO;
import org.navalplanner.business.externalcompanies.entities.ExternalCompany;
@ -235,7 +236,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
public List<FilterPair> getMatching(String filter) {
getListMatching().clear();
if ((filter != null) && (!filter.isEmpty())) {
filter = filter.toLowerCase();
filter = StringUtils.deleteWhitespace(filter.toLowerCase());
if (filter.indexOf("rc:") == 0) {
searchInCustomerReferences(filter);
} else if (filter.indexOf("cod:") == 0) {
@ -255,7 +258,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterionTypes(String filter) {
boolean limited = (filter.length() < 3);
for (CriterionType type : mapCriterions.keySet()) {
if (type.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
setFilterPairCriterionType(type, limited);
} else {
searchInCriterions(type, filter);
@ -265,7 +270,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterions(CriterionType type, String filter) {
for (Criterion criterion : mapCriterions.get(type)) {
if (criterion.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(criterion.getName()
.toLowerCase());
if (name.contains(filter)) {
addCriterion(type, criterion);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -286,7 +293,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabelTypes(String filter) {
boolean limited = (filter.length() < 3);
for (LabelType type : mapLabels.keySet()) {
if (type.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
setFilterPairLabelType(type, limited);
} else {
searchInLabels(type, filter);
@ -296,7 +305,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInLabels(LabelType type, String filter) {
for (Label label : mapLabels.get(type)) {
if (label.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(label.getName()
.toLowerCase());
if (name.contains(filter)) {
addLabel(type, label);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -316,8 +327,11 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInExternalCompanies(String filter){
for(ExternalCompany externalCompany : externalCompanies){
if ((externalCompany.getName().toLowerCase().contains(filter))
|| (externalCompany.getNif().toLowerCase().contains(filter))) {
String name = StringUtils.deleteWhitespace(externalCompany
.getName().toLowerCase());
String nif = StringUtils.deleteWhitespace(externalCompany.getNif()
.toLowerCase());
if ((name.contains(filter)) || (nif.contains(filter))) {
addExternalCompany(externalCompany);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -328,7 +342,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInOrderStatus(String filter) {
for (OrderStatusEnum state : ordersStatusEnums) {
if (state.name().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(state.name()
.toLowerCase());
if (name.contains(filter)) {
addState(state);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -340,9 +356,9 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInOrderCodes(String filter) {
if (filter.indexOf("cod:") == 0) {
String codeFilter = filter.replaceFirst("cod:", "");
codeFilter = codeFilter.replace(" ", "");
for (String code : ordersCodes) {
if (code.toLowerCase().equals(codeFilter)) {
code = StringUtils.deleteWhitespace(code.toLowerCase());
if (code.equals(codeFilter)) {
addCode(code);
return;
}
@ -353,9 +369,10 @@ public class OrdersMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCustomerReferences(String filter) {
if (filter.indexOf("rc:") == 0) {
String referenceFilter = filter.replaceFirst("rc:", "");
referenceFilter = referenceFilter.replace(" ", "");
for (String reference : customerReferences) {
if (reference.toLowerCase().equals(referenceFilter)) {
reference = StringUtils.deleteWhitespace(reference
.toLowerCase());
if (reference.equals(referenceFilter)) {
addCustomerReference(reference);
return;
}

View file

@ -26,6 +26,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.common.IOnTransaction;
import org.navalplanner.business.costcategories.daos.ICostCategoryDAO;
import org.navalplanner.business.costcategories.entities.CostCategory;
@ -131,7 +132,7 @@ public class ResourcesMultipleFiltersFinder extends MultipleFiltersFinder {
public List<FilterPair> getMatching(String filter) {
getListMatching().clear();
if ((filter != null) && (!filter.isEmpty())) {
filter = filter.toLowerCase();
filter = StringUtils.deleteWhitespace(filter.toLowerCase());
searchInCriterionTypes(filter);
searchInCostCategories(filter);
}
@ -142,7 +143,9 @@ public class ResourcesMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterionTypes(String filter) {
boolean limited = (filter.length() < 3);
for (CriterionType type : mapCriterions.keySet()) {
if (type.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(type.getName()
.toLowerCase());
if (name.contains(filter)) {
setFilterPairCriterionType(type, limited);
} else {
searchInCriterions(type, filter);
@ -152,7 +155,9 @@ public class ResourcesMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCriterions(CriterionType type, String filter) {
for (Criterion criterion : mapCriterions.get(type)) {
if (criterion.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(criterion.getName()
.toLowerCase());
if (name.contains(filter)) {
addCriterion(type, criterion);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;
@ -172,7 +177,9 @@ public class ResourcesMultipleFiltersFinder extends MultipleFiltersFinder {
private void searchInCostCategories(String filter) {
for (CostCategory costCategory : costCategories) {
if (costCategory.getName().toLowerCase().contains(filter)) {
String name = StringUtils.deleteWhitespace(costCategory.getName()
.toLowerCase());
if (name.contains(filter)) {
addCostCategory(costCategory);
if ((filter.length() < 3) && (getListMatching().size() > 9)) {
return;

View file

@ -26,6 +26,7 @@ import java.util.List;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.zkoss.ganttz.util.MutableTreeModel;
/**
@ -53,4 +54,7 @@ public interface IMaterialsModel {
void removeMaterial(Material material);
List<UnitType> getUnitTypes();
void loadUnitTypes();
}

View file

@ -32,6 +32,7 @@ import org.hibernate.validator.InvalidValue;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.web.common.ConstraintChecker;
import org.navalplanner.web.common.IMessagesForUser;
import org.navalplanner.web.common.Level;
@ -47,6 +48,10 @@ import org.zkoss.zk.ui.event.InputEvent;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;
@ -86,6 +91,7 @@ public class MaterialsController extends
private Component messagesContainer;
private UnitTypeListRenderer unitTypeListRenderer = new UnitTypeListRenderer();
@Override
public void doAfterCompose(Component comp) throws Exception {
@ -93,6 +99,9 @@ public class MaterialsController extends
comp.setVariable("materialsController", this, true);
messagesForUser = new MessagesForUser(messagesContainer);
// load the unit types
loadUnitTypes();
// Renders grid and enables delete button is material is new
gridMaterials.addEventListener("onInitRender", new EventListener() {
@ -115,6 +124,21 @@ public class MaterialsController extends
});
}
private void loadUnitTypes() {
materialsModel.loadUnitTypes();
}
public List<UnitType> getUnitTypes() {
return materialsModel.getUnitTypes();
}
public void selectUnitType(Component self) {
Listitem selectedItem = ((Listbox) self).getSelectedItem();
UnitType unitType = (UnitType) selectedItem.getValue();
Material material = (Material) ((Row) self.getParent()).getValue();
material.setUnitType(unitType);
}
public TreeModel getMaterialCategories() {
return materialsModel.getMaterialCategories();
}
@ -410,4 +434,29 @@ public class MaterialsController extends
Util.reloadBindings(gridMaterials);
}
public UnitTypeListRenderer getRenderer() {
return unitTypeListRenderer;
}
/**
* RowRenderer for a @{UnitType} element
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class UnitTypeListRenderer implements ListitemRenderer {
@Override
public void render(Listitem listItem, Object data) throws Exception {
final UnitType unitType = (UnitType) data;
listItem.setValue(unitType);
Listcell listCell = new Listcell(unitType.getMeasure());
listItem.appendChild(listCell);
Material material = (Material) ((Row) listItem.getListbox()
.getParent()).getValue();
if ((material.getUnitType() != null)
&& (unitType.getId().equals(material.getUnitType().getId()))) {
listItem.getListbox().setSelectedItem(listItem);
}
}
}
}

View file

@ -29,14 +29,17 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.hibernate.validator.InvalidValue;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
import org.navalplanner.business.materials.daos.IMaterialDAO;
import org.navalplanner.business.materials.daos.IUnitTypeDAO;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.web.common.concurrentdetection.OnConcurrentModification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
@ -56,9 +59,14 @@ public class MaterialsModel implements IMaterialsModel {
@Autowired
IMaterialDAO materialDAO;
@Autowired
IUnitTypeDAO unitTypeDAO;
MutableTreeModel<MaterialCategory> materialCategories = MutableTreeModel
.create(MaterialCategory.class);
private List<UnitType> unitTypes = new ArrayList<UnitType>();
@Override
@Transactional(readOnly=true)
public MutableTreeModel<MaterialCategory> getMaterialCategories() {
@ -87,6 +95,9 @@ public class MaterialsModel implements IMaterialsModel {
private void initializeMaterials(Set<Material> materials) {
for (Material each: materials) {
each.getDescription();
if (each.getUnitType() != null) {
each.getUnitType().getMeasure();
}
}
}
@ -113,7 +124,7 @@ public class MaterialsModel implements IMaterialsModel {
public void addMaterialCategory(MaterialCategory parent, MaterialCategory child) throws ValidationException {
Validate.notNull(child);
final MaterialCategory materialCategory = findMaterialCategory(parent, child);
final MaterialCategory materialCategory = findMaterialCategory(child);
if (materialCategory != null) {
final InvalidValue invalidValue = new InvalidValue(_("{0} already exists", materialCategory.getName()),
MaterialCategory.class, "name", materialCategory.getName(), materialCategory);
@ -128,18 +139,22 @@ public class MaterialsModel implements IMaterialsModel {
}
}
private MaterialCategory findMaterialCategory(final MaterialCategory parent, final MaterialCategory category) {
for (int i = 0; i < materialCategories.getChildCount(parent); i++) {
final MaterialCategory each = materialCategories.getChild(parent, i);
if (equalsMaterialCategory(each, category)) {
return each;
private MaterialCategory findMaterialCategory(
final MaterialCategory category) {
for (MaterialCategory mc : materialCategories.asList()) {
if (equalsMaterialCategory(mc, category)) {
return mc;
}
}
return null;
}
private boolean equalsMaterialCategory(MaterialCategory obj1, MaterialCategory obj2) {
return obj1.getName().equals(obj2.getName());
String name1 = StringUtils.deleteWhitespace(obj1.getName()
.toLowerCase());
String name2 = StringUtils.deleteWhitespace(obj2.getName()
.toLowerCase());
return name1.equals(name2);
}
@Override
@ -231,4 +246,18 @@ public class MaterialsModel implements IMaterialsModel {
return result;
}
@Override
@Transactional(readOnly = true)
public void loadUnitTypes() {
List<UnitType> result = new ArrayList<UnitType>();
for (UnitType each : unitTypeDAO.findAll()) {
each.getMeasure();
result.add(each);
}
this.unitTypes = result;
}
public List<UnitType> getUnitTypes() {
return this.unitTypes;
}
}

View file

@ -554,6 +554,12 @@ public class ManageOrderElementAdvancesController extends
}
});
if (advance instanceof IndirectAdvanceAssignment) {
removeButton.setDisabled(true);
removeButton
.setTooltiptext(_("Calculated advances can not be removed"));
}
Listcell listCell = new Listcell();
listCell.appendChild(removeButton);
listItem.appendChild(listCell);

View file

@ -33,6 +33,7 @@ import org.apache.commons.logging.LogFactory;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.business.orders.entities.OrderElement;
import org.navalplanner.web.common.Util;
import org.zkoss.zk.ui.Component;
@ -45,7 +46,9 @@ import org.zkoss.zul.Doublebox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.SimpleListModel;
@ -88,6 +91,7 @@ public abstract class AssignedMaterialsController<T, A> extends GenericForwardCo
@Override
public void doAfterCompose(Component comp) throws Exception {
super.doAfterCompose(comp);
getModel().loadUnitTypes();
createAssignmentsBoxComponent(assignmentsBox);
}
@ -508,6 +512,63 @@ public abstract class AssignedMaterialsController<T, A> extends GenericForwardCo
protected abstract double getUnits(A assignment);
private UnitTypeListRenderer unitTypeListRenderer = new UnitTypeListRenderer();
public List<UnitType> getUnitTypes() {
return getModel().getUnitTypes();
}
public void selectUnitType(Component self) {
Listitem selectedItem = ((Listbox) self).getSelectedItem();
UnitType unitType = (UnitType) selectedItem.getValue();
Material material = (Material) ((Row) self.getParent()).getValue();
material.setUnitType(unitType);
}
public UnitTypeListRenderer getRenderer() {
return unitTypeListRenderer;
}
/**
* RowRenderer for a @{UnitType} element
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class UnitTypeListRenderer implements ListitemRenderer {
@Override
public void render(Listitem listItem, Object data) throws Exception {
final UnitType unitType = (UnitType) data;
listItem.setValue(unitType);
Listcell listCell = new Listcell(unitType.getMeasure());
listItem.appendChild(listCell);
Listbox listbox = listItem.getListbox();
Component parent = listbox.getParent();
if (parent instanceof Row) {
Object assigment = (Object) ((Row) parent).getValue();
if (getModel().isCurrentUnitType(assigment, unitType)) {
listItem.getListbox().setSelectedItem(listItem);
}
return;
}
if (parent instanceof Listcell) {
Material material = (Material) ((Listitem) (parent.getParent()))
.getValue();
if (isCurrentUnitType(material, unitType)) {
listItem.getListbox().setSelectedItem(listItem);
}
}
}
}
private boolean isCurrentUnitType(Material material, UnitType unitType) {
return ((material != null)
&& (material.getUnitType() != null)
&& (unitType
.getId().equals(material.getUnitType().getId())));
}
}

View file

@ -26,8 +26,10 @@ import java.util.List;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
import org.navalplanner.business.materials.daos.IMaterialDAO;
import org.navalplanner.business.materials.daos.IUnitTypeDAO;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zkoss.ganttz.util.MutableTreeModel;
@ -46,6 +48,9 @@ public abstract class AssignedMaterialsModel<T, A> implements
@Autowired
private IMaterialDAO materialDAO;
@Autowired
private IUnitTypeDAO unitTypeDAO;
private MutableTreeModel<MaterialCategory> materialCategories = MutableTreeModel
.create(MaterialCategory.class);
@ -54,6 +59,8 @@ public abstract class AssignedMaterialsModel<T, A> implements
private List<Material> matchingMaterials = new ArrayList<Material>();
private List<UnitType> unitTypes = new ArrayList<UnitType>();
@Transactional(readOnly = true)
public void initEdit(T element) {
assignAndReattach(element);
@ -246,4 +253,14 @@ public abstract class AssignedMaterialsModel<T, A> implements
protected abstract BigDecimal getTotalPrice(A each);
@Override
@Transactional(readOnly = true)
public void loadUnitTypes() {
unitTypes = unitTypeDAO.findAll();
}
@Override
public List<UnitType> getUnitTypes() {
return unitTypes;
}
}

View file

@ -28,6 +28,7 @@ import java.util.Set;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.business.orders.daos.IOrderElementDAO;
import org.navalplanner.business.orders.entities.OrderElement;
import org.springframework.beans.factory.annotation.Autowired;
@ -139,4 +140,12 @@ public class AssignedMaterialsToOrderElementModel extends
return orderElement != null;
}
@Override
public boolean isCurrentUnitType(Object assigment, UnitType unitType) {
MaterialAssignment material = (MaterialAssignment) assigment;
return ((material != null)
&& (material.getMaterial().getUnitType() != null) && (unitType
.getId().equals(material.getMaterial().getUnitType().getId())));
}
}

View file

@ -24,6 +24,7 @@ import java.util.List;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.zkoss.zul.TreeModel;
/**
@ -42,6 +43,8 @@ public interface IAssignedMaterialsModel<T, A> {
List<A> getAssignedMaterials(MaterialCategory materialCategory);
abstract boolean isCurrentUnitType(Object assigment, UnitType unitType);
List<Material> getMatchingMaterials();
TreeModel getMaterialCategories();
@ -54,4 +57,8 @@ public interface IAssignedMaterialsModel<T, A> {
void searchMaterials(String text, MaterialCategory materialCategory);
void loadUnitTypes();
List<UnitType> getUnitTypes();
}

View file

@ -21,6 +21,7 @@
package org.navalplanner.web.orders.materials;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.business.orders.entities.OrderElement;
@ -30,6 +31,8 @@ import org.navalplanner.business.orders.entities.OrderElement;
public interface IAssignedMaterialsToOrderElementModel extends
IAssignedMaterialsModel<OrderElement, MaterialAssignment> {
boolean isCurrentUnitType(Object assigment, UnitType unitType);
OrderElement getOrderElement();
void initEdit(OrderElement orderElement);

View file

@ -149,33 +149,39 @@ public class ResourceAllocationModel implements IResourceAllocationModel {
@Override
public void cancel() {
task.setStartDate(currentStartDate);
if (currentStartDate != null) {
task.setStartDate(currentStartDate);
}
allocationRowsHandler = null;
currentStartDate = null;
}
@Override
public void accept() {
applyAllocationWithDateChangesNotification(new IOnTransaction<Void>() {
@Override
public Void execute() {
stepsBeforeDoingAllocation();
allocationRowsHandler.doAllocation().applyTo(task);
return null;
}
});
if (context != null) {
applyAllocationWithDateChangesNotification(new IOnTransaction<Void>() {
@Override
public Void execute() {
stepsBeforeDoingAllocation();
allocationRowsHandler.doAllocation().applyTo(task);
return null;
}
});
}
}
@Override
public void accept(final AllocationResult modifiedAllocationResult) {
applyAllocationWithDateChangesNotification(new IOnTransaction<Void>() {
@Override
public Void execute() {
stepsBeforeDoingAllocation();
modifiedAllocationResult.applyTo(task);
return null;
}
});
if (context != null) {
applyAllocationWithDateChangesNotification(new IOnTransaction<Void>() {
@Override
public Void execute() {
stepsBeforeDoingAllocation();
modifiedAllocationResult.applyTo(task);
return null;
}
});
}
}
private void applyAllocationWithDateChangesNotification(

View file

@ -873,8 +873,7 @@ public abstract class CompanyPlanningModel implements ICompanyPlanningModel {
}
for (WorkReportLine workReportLine : workReportLines) {
LocalDate day = new LocalDate(workReportLine.getWorkReport()
.getDate());
LocalDate day = new LocalDate(workReportLine.getDate());
BigDecimal cost = new BigDecimal(workReportLine.getNumHours());
if (!result.containsKey(day)) {

View file

@ -130,9 +130,6 @@ public class OrderPlanningController implements Composer {
@Override
public void doAfterCompose(org.zkoss.zk.ui.Component comp) throws Exception {
if (order == null) {
throw new IllegalStateException("an order should have been set");
}
this.planner = (Planner) comp;
String zoomLevelParameter = null;
if ((parameters != null) && (parameters.get("zoom") != null)
@ -166,9 +163,12 @@ public class OrderPlanningController implements Composer {
}
private void updateConfiguration() {
model.setConfigurationToPlanner(planner, order, viewSwitcher,
editTaskController, calendarAllocationController, additional);
planner.updateSelectedZoomLevel();
if (order != null) {
model.setConfigurationToPlanner(planner, order, viewSwitcher,
editTaskController, calendarAllocationController,
additional);
planner.updateSelectedZoomLevel();
}
}
public EditTaskController getEditTaskController() {

View file

@ -74,7 +74,6 @@ import org.navalplanner.business.users.entities.OrderAuthorizationType;
import org.navalplanner.business.users.entities.User;
import org.navalplanner.business.users.entities.UserRole;
import org.navalplanner.business.workreports.daos.IWorkReportLineDAO;
import org.navalplanner.business.workreports.entities.WorkReportLine;
import org.navalplanner.web.calendars.BaseCalendarModel;
import org.navalplanner.web.common.ViewSwitcher;
import org.navalplanner.web.planner.ITaskElementAdapter;
@ -1178,7 +1177,18 @@ public abstract class OrderPlanningModel implements IOrderPlanningModel {
}
protected void calculateActualCostWorkPerformed(Interval interval) {
SortedMap<LocalDate, BigDecimal> workReportCost = getWorkReportCost();
List<TaskElement> list = order
.getAllChildrenAssociatedTaskElements();
list.add(order.getAssociatedTaskElement());
SortedMap<LocalDate, BigDecimal> workReportCost = new TreeMap<LocalDate, BigDecimal>();
for (TaskElement taskElement : list) {
if (taskElement instanceof Task) {
addCost(workReportCost, hoursCostCalculator
.getWorkReportCost((Task) taskElement));
}
}
workReportCost = accumulateResult(workReportCost);
addZeroBeforeTheFirstValue(workReportCost);
@ -1186,30 +1196,6 @@ public abstract class OrderPlanningModel implements IOrderPlanningModel {
workReportCost, interval.getStart(), interval.getFinish()));
}
public SortedMap<LocalDate, BigDecimal> getWorkReportCost() {
SortedMap<LocalDate, BigDecimal> result = new TreeMap<LocalDate, BigDecimal>();
List<WorkReportLine> workReportLines = workReportLineDAO
.findByOrderElementAndChildren(order);
if (workReportLines.isEmpty()) {
return result;
}
for (WorkReportLine workReportLine : workReportLines) {
LocalDate day = new LocalDate(workReportLine.getWorkReport()
.getDate());
BigDecimal cost = new BigDecimal(workReportLine.getNumHours());
if (!result.containsKey(day)) {
result.put(day, BigDecimal.ZERO);
}
result.put(day, result.get(day).add(cost));
}
return result;
}
protected void calculateBudgetedCostWorkPerformed(Interval interval) {
List<TaskElement> list = order
.getAllChildrenAssociatedTaskElements();

View file

@ -175,7 +175,6 @@ public class PlanningTabCreator {
public org.zkoss.zk.ui.Component create(
org.zkoss.zk.ui.Component parent) {
Map<String, Object> arguments = new HashMap<String, Object>();
orderPlanningController.setOrder(mode.getOrder());
arguments.put("orderPlanningController",
orderPlanningController);
orderPlanningController.setURLParameters(parameters);

View file

@ -0,0 +1,47 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.web.print;
import static org.zkoss.ganttz.i18n.I18nHelper._;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CutyCaptTimeout extends Thread {
long timeout;
private static final Log LOG = LogFactory.getLog(CutyPrint.class);
CutyCaptTimeout(int timeout) {
this.timeout = timeout;
}
public void run() {
try {
sleep(timeout);
Runtime.getRuntime().exec("killall CutyCapt");
} catch (Exception e) {
LOG.error(_("CutycaptTimeout thread exception"), e);
}
}
}

View file

@ -53,6 +53,8 @@ public class CutyPrint {
private static final Log LOG = LogFactory.getLog(CutyPrint.class);
private static final String CUTYCAPT_COMMAND = "/usr/bin/CutyCapt ";
// Estimated maximum execution time (ms)
private static final int CUTYCAPT_TIMEOUT = 20000;
// Taskdetails left padding
private static int TASKDETAILS_WIDTH = 310;
@ -183,34 +185,36 @@ public class CutyPrint {
// Destination complete absolute path
captureString += " --out=" + absolutePath + filename;
try {
// CutyCapt command execution
LOG.warn(captureString);
Process print;
Process server = null;
// Ensure cleanup of unfinished CutyCapt processes and CSS
Runtime.getRuntime().exec("killall CutyCapt");
Process printProcess;
Process serverProcess = null;
// If there is a not real X server environment then use Xvfb
if ((System.getenv("DISPLAY") == null)
|| (System.getenv("DISPLAY").equals(""))) {
String[] serverEnvironment = { "PATH=$PATH" };
server = Runtime.getRuntime().exec("env - Xvfb :99",
serverProcess = Runtime.getRuntime().exec("env - Xvfb :99",
serverEnvironment);
String[] environment = { "DISPLAY=:99.0" };
print = Runtime.getRuntime().exec(captureString, environment);
printProcess = Runtime.getRuntime().exec(captureString,
environment);
} else {
print = Runtime.getRuntime().exec(captureString);
printProcess = Runtime.getRuntime().exec(captureString);
}
try {
print.waitFor();
print.destroy();
// Ensure CutyCapt process finalization
CutyCaptTimeout timeoutThread = new CutyCaptTimeout( CUTYCAPT_TIMEOUT );
new Thread(timeoutThread).start();
printProcess.waitFor();
printProcess.destroy();
if ((System.getenv("DISPLAY") == null)
|| (System.getenv("DISPLAY").equals(""))) {
server.destroy();
serverProcess.destroy();
}
Executions.getCurrent().sendRedirect(filename, "_blank");
} catch (Exception e) {
@ -278,4 +282,4 @@ public class CutyPrint {
} else
return srFile;
}
}
}

View file

@ -24,6 +24,7 @@ import static org.navalplanner.web.I18nHelper._;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -48,6 +49,7 @@ import org.navalplanner.web.costcategories.ResourcesCostCategoryAssignmentContro
import org.navalplanner.web.resources.search.ResourcePredicate;
import org.navalplanner.web.resources.worker.CriterionsController;
import org.navalplanner.web.resources.worker.CriterionsMachineController;
import org.navalplanner.web.resources.worker.WorkerCRUDController.LimitingResourceEnum;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.util.GenericForwardComposer;
@ -57,6 +59,8 @@ import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;
@ -97,6 +101,8 @@ public class MachineCRUDController extends GenericForwardComposer {
private Datebox filterFinishDate;
private Listbox filterLimitingResource;
private Textbox txtfilter;
private BandboxMultipleSearch bdFilters;
@ -139,6 +145,8 @@ public class MachineCRUDController extends GenericForwardComposer {
.getFellowIfAny("filterFinishDate");
this.filterStartDate = (Datebox) listWindow
.getFellowIfAny("filterStartDate");
this.filterLimitingResource = (Listbox) listWindow
.getFellowIfAny("filterLimitingResource");
this.bdFilters = (BandboxMultipleSearch) listWindow
.getFellowIfAny("bdFilters");
this.txtfilter = (Textbox) listWindow.getFellowIfAny("txtfilter");
@ -512,13 +520,18 @@ public class MachineCRUDController extends GenericForwardComposer {
.getValue());
}
final Listitem item = filterLimitingResource.getSelectedItem();
Boolean isLimitingResource = (item != null) ? LimitingResourceEnum
.valueOf((LimitingResourceEnum) item.getValue()) : null;
if (listFilters.isEmpty()
&& (personalFilter == null || personalFilter.isEmpty())
&& startDate == null && finishDate == null) {
&& startDate == null && finishDate == null
&& isLimitingResource == null) {
return null;
}
return new ResourcePredicate(listFilters, personalFilter, startDate,
finishDate);
finishDate, isLimitingResource);
}
private void filterByPredicate(ResourcePredicate predicate) {
@ -538,4 +551,31 @@ public class MachineCRUDController extends GenericForwardComposer {
.toArray()));
listing.invalidate();
}
}
public Set<LimitingResourceEnum> getLimitingResourceFilterOptionList() {
return LimitingResourceEnum.getLimitingResourceFilterOptionList();
}
public Set<LimitingResourceEnum> getLimitingResourceOptionList() {
return LimitingResourceEnum.getLimitingResourceOptionList();
}
public Object getLimitingResource() {
final Machine machine = getMachine();
return (machine != null) ? LimitingResourceEnum.valueOf(machine
.isLimitingResource())
: LimitingResourceEnum.NON_LIMITING_RESOURCE; // Default option
}
public void setLimitingResource(LimitingResourceEnum option) {
Machine machine = getMachine();
if (machine != null) {
machine.setLimitingResource(LimitingResourceEnum.LIMITING_RESOURCE.equals(option));
}
}
public boolean isEditing() {
return (getMachine() != null && !getMachine().isNewObject());
}
}

View file

@ -52,14 +52,18 @@ public class ResourcePredicate implements IPredicate {
private String[] personalFilters;
private Boolean isLimitingResource;
private List<Resource> assignedResourcesInIntervalDates;
public ResourcePredicate(List<FilterPair> filters, String personalFilters,
LocalDate startDate,
LocalDate finishDate) {
LocalDate finishDate,
Boolean isLimitingResource) {
this.filters = filters;
this.startDate = startDate;
this.finishDate = finishDate;
this.isLimitingResource = isLimitingResource;
this.personalFilters = personalFilters.split(" ");
}
@ -74,12 +78,16 @@ public class ResourcePredicate implements IPredicate {
return false;
}
if (acceptFilters(resource) && acceptPersonalFilters(resource)
&& acceptFiltersDates(resource)) {
&& acceptFiltersDates(resource) && acceptFilterIsLimitingResource(resource)) {
return true;
}
return false;
}
private boolean acceptFilterIsLimitingResource(Resource resource) {
return (isLimitingResource != null) ? isLimitingResource.equals(resource.isLimitingResource()) : true;
}
private boolean acceptFilters(Resource resource) {
if ((filters == null) || (filters.isEmpty())) {
return true;

View file

@ -23,7 +23,9 @@ package org.navalplanner.web.resources.worker;
import static org.navalplanner.web.I18nHelper._;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.joda.time.LocalDate;
import org.navalplanner.business.calendars.entities.BaseCalendar;
@ -54,6 +56,8 @@ import org.zkoss.zul.ComboitemRenderer;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;
@ -107,6 +111,8 @@ public class WorkerCRUDController extends GenericForwardComposer implements
private Datebox filterFinishDate;
private Listbox filterLimitingResource;
private BandboxMultipleSearch bdFilters;
private Textbox txtfilter;
@ -291,6 +297,8 @@ public class WorkerCRUDController extends GenericForwardComposer implements
.getFellowIfAny("filterFinishDate");
this.filterStartDate = (Datebox) listWindow
.getFellowIfAny("filterStartDate");
this.filterLimitingResource = (Listbox) listWindow
.getFellowIfAny("filterLimitingResource");
this.bdFilters = (BandboxMultipleSearch) listWindow
.getFellowIfAny("bdFilters");
this.txtfilter = (Textbox) listWindow.getFellowIfAny("txtfilter");
@ -599,13 +607,18 @@ public class WorkerCRUDController extends GenericForwardComposer implements
finishDate = LocalDate.fromDateFields(filterFinishDate.getValue());
}
final Listitem item = filterLimitingResource.getSelectedItem();
Boolean isLimitingResource = (item != null) ? LimitingResourceEnum
.valueOf((LimitingResourceEnum) item.getValue()) : null;
if (listFilters.isEmpty()
&& (personalFilter == null || personalFilter.isEmpty())
&& startDate == null && finishDate == null) {
&& startDate == null && finishDate == null
&& isLimitingResource == null) {
return null;
}
return new ResourcePredicate(listFilters, personalFilter, startDate,
finishDate);
finishDate, isLimitingResource);
}
private void filterByPredicate(ResourcePredicate predicate) {
@ -625,4 +638,74 @@ public class WorkerCRUDController extends GenericForwardComposer implements
.toArray()));
listing.invalidate();
}
public enum LimitingResourceEnum {
ALL(_("ALL")),
LIMITING_RESOURCE(_("LIMITING RESOURCE")),
NON_LIMITING_RESOURCE(_("NON LIMITING RESOURCE"));
private String option;
private LimitingResourceEnum(String option) {
this.option = option;
}
public String toString() {
return option;
}
public static LimitingResourceEnum valueOf(Boolean isLimitingResource) {
return (Boolean.TRUE.equals(isLimitingResource)) ? LIMITING_RESOURCE : NON_LIMITING_RESOURCE;
}
public static Boolean valueOf(LimitingResourceEnum option) {
if (LIMITING_RESOURCE.equals(option)) {
return true;
} else if (NON_LIMITING_RESOURCE.equals(option)) {
return false;
} else {
return null;
}
}
public static Set<LimitingResourceEnum> getLimitingResourceOptionList() {
return EnumSet.of(
LimitingResourceEnum.LIMITING_RESOURCE,
LimitingResourceEnum.NON_LIMITING_RESOURCE);
}
public static Set<LimitingResourceEnum> getLimitingResourceFilterOptionList() {
return EnumSet.of(LimitingResourceEnum.ALL,
LimitingResourceEnum.LIMITING_RESOURCE,
LimitingResourceEnum.NON_LIMITING_RESOURCE);
}
}
public Set<LimitingResourceEnum> getLimitingResourceFilterOptionList() {
return LimitingResourceEnum.getLimitingResourceFilterOptionList();
}
public Set<LimitingResourceEnum> getLimitingResourceOptionList() {
return LimitingResourceEnum.getLimitingResourceOptionList();
}
public Object getLimitingResource() {
final Worker worker = getWorker();
return (worker != null) ? LimitingResourceEnum.valueOf(worker
.isLimitingResource())
: LimitingResourceEnum.NON_LIMITING_RESOURCE; // Default option
}
public void setLimitingResource(LimitingResourceEnum option) {
Worker worker = getWorker();
if (worker != null) {
worker.setLimitingResource(LimitingResourceEnum.LIMITING_RESOURCE.equals(option));
}
}
public boolean isEditing() {
return (getWorker() != null && !getWorker().isNewObject());
}
}

View file

@ -27,6 +27,7 @@ import java.util.List;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignmentTemplate;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.business.templates.daos.IOrderElementTemplateDAO;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.navalplanner.web.orders.materials.AssignedMaterialsModel;
@ -130,4 +131,12 @@ public class AssignedMaterialsToOrderElementTemplateModel extends
template.removeMaterialAssignment(materialAssignment);
}
@Override
public boolean isCurrentUnitType(Object assigment, UnitType unitType) {
MaterialAssignmentTemplate material = (MaterialAssignmentTemplate) assigment;
return ((material != null)
&& (material.getMaterial().getUnitType() != null) && (unitType
.getId().equals(material.getMaterial().getUnitType().getId())));
}
}

View file

@ -20,6 +20,7 @@
package org.navalplanner.web.templates.materials;
import org.navalplanner.business.materials.entities.MaterialAssignmentTemplate;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.business.templates.entities.OrderElementTemplate;
import org.navalplanner.web.orders.materials.IAssignedMaterialsModel;
@ -30,6 +31,8 @@ import org.navalplanner.web.orders.materials.IAssignedMaterialsModel;
public interface IAssignedMaterialsToOrderElementTemplateModel extends
IAssignedMaterialsModel<OrderElementTemplate, MaterialAssignmentTemplate> {
public boolean isCurrentUnitType(Object assigment, UnitType unitType);
OrderElementTemplate getTemplate();
}

View file

@ -343,11 +343,11 @@ public class WorkReportCRUDController extends GenericForwardComposer implements
return false;
}
} else if (workReportLine.getOrderElement() == null) {
Textbox txtOrder = getTextboxOrder(row);
if (txtOrder != null) {
BandboxSearch bandboxOrder = getTextboxOrder(row);
if (bandboxOrder != null) {
String message = _("The order element code cannot be null");
txtOrder.setValue("");
showInvalidMessage(txtOrder, message);
bandboxOrder.clear();
showInvalidMessage(bandboxOrder, message);
}
return false;
}
@ -520,7 +520,7 @@ public class WorkReportCRUDController extends GenericForwardComposer implements
* @param row
* @return
*/
private Textbox getTextboxOrder(Row row) {
private BandboxSearch getTextboxOrder(Row row) {
int position = 0;
if (!getWorkReportType().getDateIsSharedByLines()) {
position++;
@ -529,7 +529,7 @@ public class WorkReportCRUDController extends GenericForwardComposer implements
position++;
}
try {
return (Textbox) row.getChildren().get(position);
return (BandboxSearch) row.getChildren().get(position);
} catch (Exception e) {
return null;
}

View file

@ -0,0 +1,76 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.ws.common.api.IntegrationEntityDTO;
/**
* DTO for {@link BaseCalendar} entity.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class BaseCalendarDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "base-calendar";
@XmlAttribute
public String name;
@XmlElementWrapper(name = "calendar-exception-list")
@XmlElement(name = "calendar-exception")
public List<CalendarExceptionDTO> calendarExceptions = new ArrayList<CalendarExceptionDTO>();
@XmlElementWrapper(name = "calendar-data-list")
@XmlElement(name = "calendar-data")
public List<CalendarDataDTO> calendarDatas = new ArrayList<CalendarDataDTO>();
public BaseCalendarDTO() {
}
public BaseCalendarDTO(String code, String name,
List<CalendarExceptionDTO> calendarExceptions,
List<CalendarDataDTO> calendarDatas) {
super(code);
this.name = name;
this.calendarExceptions = calendarExceptions;
this.calendarDatas = calendarDatas;
}
public BaseCalendarDTO(String name,
List<CalendarExceptionDTO> calendarExceptions,
List<CalendarDataDTO> calendarDatas) {
this(generateCode(), name, calendarExceptions, calendarDatas);
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.navalplanner.business.calendars.entities.BaseCalendar;
/**
* DTO for a list of {@link BaseCalendar} entities.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@XmlRootElement(name = "base-calendar-list")
public class BaseCalendarListDTO {
@XmlElement(name = "base-calendar")
public List<BaseCalendarDTO> baseCalendars = new ArrayList<BaseCalendarDTO>();
public BaseCalendarListDTO() {}
public BaseCalendarListDTO(List<BaseCalendarDTO> baseCalendars) {
this.baseCalendars = baseCalendars;
}
}

View file

@ -0,0 +1,74 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import org.navalplanner.business.calendars.entities.CalendarData;
import org.navalplanner.ws.common.api.IntegrationEntityDTO;
/**
* DTO for {@link CalendarData} entity.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class CalendarDataDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "calendar-data";
@XmlElementWrapper(name = "hors-per-day-list")
@XmlElement(name = "hors-per-day")
public List<HoursPerDayDTO> hoursPerDays = new ArrayList<HoursPerDayDTO>();
@XmlAttribute(name = "expiring-date")
public Date expiringDate;
@XmlAttribute(name = "parent-calendar")
public String parentCalendar;
public CalendarDataDTO() {
}
public CalendarDataDTO(String code, List<HoursPerDayDTO> hoursPerDays,
Date expiringDate, String parentCalendar) {
super(code);
this.hoursPerDays = hoursPerDays;
this.expiringDate = expiringDate;
this.parentCalendar = parentCalendar;
}
public CalendarDataDTO(List<HoursPerDayDTO> hoursPerDays,
Date expiringDate, String parentCalendar) {
this(generateCode(), hoursPerDays, expiringDate, parentCalendar);
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -0,0 +1,69 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import org.navalplanner.business.calendars.entities.CalendarException;
import org.navalplanner.ws.common.api.IntegrationEntityDTO;
/**
* DTO for {@link CalendarException} entity.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class CalendarExceptionDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "calendar-exception";
@XmlAttribute
public Date date;
@XmlAttribute
public Integer hours;
@XmlAttribute(name = "calendar-exception-type-name")
public String calendarExceptionTypeName;
public CalendarExceptionDTO() {
}
public CalendarExceptionDTO(String code, Date date, Integer hours,
String calendarExceptionTypeName) {
super(code);
this.date = date;
this.hours = hours;
this.calendarExceptionTypeName = calendarExceptionTypeName;
}
public CalendarExceptionDTO(Date date, Integer hours,
String calendarExceptionTypeName) {
this(generateCode(), date, hours, calendarExceptionTypeName);
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -0,0 +1,48 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import javax.xml.bind.annotation.XmlAttribute;
import org.navalplanner.business.calendars.entities.CalendarData;
/**
* DTO for represent hours per day of {@link CalendarData} entity.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public class HoursPerDayDTO {
@XmlAttribute
public String day;
@XmlAttribute
public Integer hours;
public HoursPerDayDTO() {
}
public HoursPerDayDTO(String day, Integer hours) {
this.day = day;
this.hours = hours;
}
}

View file

@ -0,0 +1,34 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.api;
import org.navalplanner.business.calendars.entities.BaseCalendar;
/**
* Service for managing {@link BaseCalendar} entities.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public interface ICalendarService {
BaseCalendarListDTO getBaseCalendars();
}

View file

@ -0,0 +1,29 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Specification of namespace for REST-based services.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@javax.xml.bind.annotation.XmlSchema(elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, namespace = WSCommonGlobalNames.REST_NAMESPACE)
package org.navalplanner.ws.calendars.api;
import org.navalplanner.ws.common.api.WSCommonGlobalNames;

View file

@ -0,0 +1,89 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.calendars.entities.CalendarData;
import org.navalplanner.business.calendars.entities.CalendarException;
import org.navalplanner.business.calendars.entities.CalendarData.Days;
import org.navalplanner.ws.calendars.api.BaseCalendarDTO;
import org.navalplanner.ws.calendars.api.CalendarDataDTO;
import org.navalplanner.ws.calendars.api.CalendarExceptionDTO;
import org.navalplanner.ws.calendars.api.HoursPerDayDTO;
/**
* Converter from/to {@link BaseCalendar} related entities to/from DTOs.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
public final class CalendarConverter {
private CalendarConverter() {
}
public final static BaseCalendarDTO toDTO(BaseCalendar baseCalendar) {
List<CalendarExceptionDTO> calendarExceptionDTOs = new ArrayList<CalendarExceptionDTO>();
for (CalendarException calendarException : baseCalendar.getExceptions()) {
calendarExceptionDTOs.add(toDTO(calendarException));
}
List<CalendarDataDTO> calendarDataDTOs = new ArrayList<CalendarDataDTO>();
for (CalendarData calendarData : baseCalendar.getCalendarDataVersions()) {
calendarDataDTOs.add(toDTO(calendarData));
}
return new BaseCalendarDTO(baseCalendar.getCode(), baseCalendar
.getName(), calendarExceptionDTOs, calendarDataDTOs);
}
private final static CalendarExceptionDTO toDTO(
CalendarException calendarException) {
return new CalendarExceptionDTO(calendarException.getCode(),
calendarException.getDate().toDateTimeAtStartOfDay().toDate(),
calendarException.getHours(), calendarException.getType()
.getName());
}
private final static CalendarDataDTO toDTO(CalendarData calendarData) {
List<HoursPerDayDTO> hoursPerDayDTOs = new ArrayList<HoursPerDayDTO>();
Days[] days = CalendarData.Days.values();
for (Integer day : calendarData.getHoursPerDay().keySet()) {
String dayName = days[day].name();
Integer hours = calendarData.getHoursPerDay().get(day);
hoursPerDayDTOs.add(new HoursPerDayDTO(dayName, hours));
}
Date expiringDate = (calendarData.getExpiringDate() != null) ? calendarData
.getExpiringDate().toDateTimeAtStartOfDay().toDate()
: null;
String parentCalendar = (calendarData.getParent() != null) ? calendarData
.getParent().getCode()
: null;
return new CalendarDataDTO(hoursPerDayDTOs, expiringDate,
parentCalendar);
}
}

View file

@ -0,0 +1,91 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.calendars.impl;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.navalplanner.business.calendars.daos.IBaseCalendarDAO;
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.ws.calendars.api.BaseCalendarDTO;
import org.navalplanner.ws.calendars.api.BaseCalendarListDTO;
import org.navalplanner.ws.calendars.api.ICalendarService;
import org.navalplanner.ws.common.impl.GenericRESTService;
import org.navalplanner.ws.common.impl.RecoverableErrorException;
import org.navalplanner.ws.labels.api.ILabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* REST-based implementation of {@link ILabelService}.
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@Path("/calendars/")
@Produces("application/xml")
@Service("calendarServiceREST")
public class CalendarServiceREST extends
GenericRESTService<BaseCalendar, BaseCalendarDTO> implements
ICalendarService {
@Autowired
private IBaseCalendarDAO baseCalendarDAO;
@Override
protected IBaseCalendarDAO getIntegrationEntityDAO() {
return baseCalendarDAO;
}
@Override
protected BaseCalendarDTO toDTO(BaseCalendar entity) {
return CalendarConverter.toDTO(entity);
}
@Override
protected BaseCalendar toEntity(BaseCalendarDTO entityDTO)
throws ValidationException, RecoverableErrorException {
// TODO Auto-generated method stub
return null;
}
@Override
protected void updateEntity(BaseCalendar entity, BaseCalendarDTO entityDTO)
throws ValidationException, RecoverableErrorException {
// TODO Auto-generated method stub
}
@Override
@GET
@Transactional(readOnly = true)
public BaseCalendarListDTO getBaseCalendars() {
// Avoid ResourceCalendar entities
List<BaseCalendar> justBaseCalendars = getIntegrationEntityDAO()
.getBaseCalendars();
return new BaseCalendarListDTO(toDTO(justBaseCalendars));
}
}

View file

@ -25,7 +25,6 @@ import java.util.List;
import java.util.Set;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.navalplanner.business.orders.entities.Order;
@ -34,9 +33,11 @@ import org.navalplanner.business.orders.entities.Order;
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@XmlRootElement(name = "order")
public class OrderDTO extends OrderLineGroupDTO {
public final static String ENTITY_TYPE = "order";
@XmlAttribute(name = "dependencies-constraints-have-priority")
public Boolean dependenciesConstraintsHavePriority;

View file

@ -28,7 +28,6 @@ import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import org.navalplanner.business.orders.entities.OrderElement;
@ -37,15 +36,14 @@ import org.navalplanner.business.orders.entities.OrderElement;
*
* @author Manuel Rego Casasnovas <mrego@igalia.com>
*/
@XmlRootElement(name = "order-element")
public class OrderElementDTO {
public class OrderElementDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "order-element";
@XmlAttribute
public String name;
@XmlAttribute
public String code;
@XmlAttribute(name = "init-date")
public Date initDate;
@ -92,4 +90,9 @@ public class OrderElementDTO {
this.criterionRequirements = criterionRequirements;
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -1,75 +0,0 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.common.impl;
import java.util.Date;
import javax.xml.datatype.XMLGregorianCalendar;
import org.joda.time.LocalDate;
/**
* A converter from <code>java.util.Date</code> to/from
* <code>javax.xml.datatype.XMLGregorianCalendar</code>.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
*/
public class DateConverter {
private DateConverter() {}
/**
* It converts a <code>XMLGregorianCalendar</code> representing a
* <code>xsd:date</code> XML type to a <code>Date</code>.<br/><br/>
*
* If the date passed as a parameter is <code>null</code>, it also returns
* <code>null</code>.
*/
public final static Date toDate(XMLGregorianCalendar date) {
if (date == null) {
return null;
} else {
return date.toGregorianCalendar().getTime();
}
}
/**
* It converts a <code>XMLGregorianCalendar</code> representing a
* <code>xsd:date</code> XML type to a Joda's <code>LocalDate</code>.
* <br/><br/>
*
* If the date passed as a parameter is <code>null</code>, it also returns
* <code>null</code>.
*/
public final static LocalDate toLocalDate(XMLGregorianCalendar date) {
if (date == null) {
return null;
} else {
return new LocalDate(date.getYear(), date.getMonth(),
date.getDay());
}
}
}

View file

@ -38,11 +38,12 @@ import org.navalplanner.business.advance.exceptions.DuplicateValueTrueReportGlob
import org.navalplanner.business.calendars.entities.BaseCalendar;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.labels.entities.Label;
import org.navalplanner.business.materials.bootstrap.PredefinedMaterialCategories;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialAssignment;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.PredefinedMaterialCategories;
import org.navalplanner.business.orders.entities.HoursGroup;
import org.navalplanner.business.orders.entities.ICriterionRequirable;
import org.navalplanner.business.orders.entities.Order;
@ -58,7 +59,6 @@ import org.navalplanner.ws.common.api.AdvanceMeasurementDTO;
import org.navalplanner.ws.common.api.CriterionRequirementDTO;
import org.navalplanner.ws.common.api.DirectCriterionRequirementDTO;
import org.navalplanner.ws.common.api.HoursGroupDTO;
import org.navalplanner.ws.common.api.IncompatibleTypeException;
import org.navalplanner.ws.common.api.IndirectCriterionRequirementDTO;
import org.navalplanner.ws.common.api.LabelReferenceDTO;
import org.navalplanner.ws.common.api.MaterialAssignmentDTO;
@ -225,7 +225,7 @@ public final class OrderElementConverter {
public final static OrderElement toEntity(OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws InstanceNotFoundException {
throws ValidationException {
OrderElement orderElement = toEntityExceptCriterionRequirements(
orderElementDTO, configuration);
if (configuration.isCriterionRequirements()) {
@ -316,13 +316,14 @@ public final class OrderElementConverter {
private final static OrderElement toEntityExceptCriterionRequirements(
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws InstanceNotFoundException {
throws ValidationException {
OrderElement orderElement;
if (orderElementDTO instanceof OrderLineDTO) {
if ((configuration.isHoursGroups())
&& (!((OrderLineDTO) orderElementDTO).hoursGroups.isEmpty())) {
orderElement = OrderLine.create();
orderElement = OrderLine
.createUnvalidated(orderElementDTO.code);
for (HoursGroupDTO hoursGroupDTO : ((OrderLineDTO) orderElementDTO).hoursGroups) {
HoursGroup hoursGroup = toEntity(hoursGroupDTO,
@ -331,7 +332,8 @@ public final class OrderElementConverter {
}
} else {
orderElement = OrderLine
.createOrderLineWithUnfixedPercentage(0);
.createUnvalidatedWithUnfixedPercentage(
orderElementDTO.code, 0);
}
} else { // orderElementDTO instanceof OrderLineGroupDTO
List<OrderElement> children = new ArrayList<OrderElement>();
@ -340,11 +342,9 @@ public final class OrderElementConverter {
}
if (orderElementDTO instanceof OrderDTO) {
orderElement = Order.create();
orderElement = Order.createUnvalidated(orderElementDTO.code);
((Order) orderElement)
.setDependenciesConstraintsHavePriority(((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority);
List<BaseCalendar> calendars = Registry.getBaseCalendarDAO()
.findByName(((OrderDTO) orderElementDTO).calendarName);
BaseCalendar calendar;
@ -356,7 +356,8 @@ public final class OrderElementConverter {
}
((Order) orderElement).setCalendar(calendar);
} else { // orderElementDTO instanceof OrderLineGroupDTO
orderElement = OrderLineGroup.create();
orderElement = OrderLineGroup
.createUnvalidated(orderElementDTO.code);
}
for (OrderElement child : children) {
@ -372,7 +373,12 @@ public final class OrderElementConverter {
if (configuration.isLabels()) {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
try {
orderElement.addLabel(LabelReferenceConverter.toEntity(labelDTO));
} catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code
+ " not found.");
}
}
}
@ -456,7 +462,7 @@ public final class OrderElementConverter {
public final static void update(OrderElement orderElement,
OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws IncompatibleTypeException, InstanceNotFoundException {
throws ValidationException {
updateExceptCriterionRequirements(orderElement, orderElementDTO,
configuration);
if (configuration.isCriterionRequirements()) {
@ -467,12 +473,14 @@ public final class OrderElementConverter {
private final static void updateExceptCriterionRequirements(
OrderElement orderElement, OrderElementDTO orderElementDTO,
ConfigurationOrderElementConverter configuration)
throws IncompatibleTypeException, InstanceNotFoundException {
throws ValidationException {
if (orderElementDTO instanceof OrderLineDTO) {
if (!(orderElement instanceof OrderLine)) {
throw new IncompatibleTypeException(orderElement.getCode(),
OrderLine.class, orderElement.getClass());
throw new ValidationException(_(
"Order element {0} : OrderLineGroup is incompatible type with {1}"
+ orderElement.getCode(), orderElement
.getClass().getName()));
}
if (configuration.isHoursGroups()) {
@ -492,8 +500,11 @@ public final class OrderElementConverter {
} else { // orderElementDTO instanceof OrderLineGroupDTO
if (orderElementDTO instanceof OrderDTO) {
if (!(orderElement instanceof Order)) {
throw new IncompatibleTypeException(orderElement.getCode(),
Order.class, orderElement.getClass());
throw new ValidationException(_(
"Order element {0} : Order is incompatible type with {1}"
+ orderElement.getCode(), orderElement
.getClass().getName()));
}
Boolean dependenciesConstraintsHavePriority = ((OrderDTO) orderElementDTO).dependenciesConstraintsHavePriority;
@ -518,8 +529,10 @@ public final class OrderElementConverter {
}
} else { // orderElementDTO instanceof OrderLineGroupDTO
if (!(orderElement instanceof OrderLineGroup)) {
throw new IncompatibleTypeException(orderElement.getCode(),
OrderLineGroup.class, orderElement.getClass());
throw new ValidationException(_(
"Order element {0} : OrderLineGroup is incompatible type with {1}"
+ orderElement.getCode(), orderElement
.getClass().getName()));
}
}
@ -538,7 +551,12 @@ public final class OrderElementConverter {
if (configuration.isLabels()) {
for (LabelReferenceDTO labelDTO : orderElementDTO.labels) {
if (!orderElement.containsLabel(labelDTO.code)) {
try {
orderElement.addLabel(LabelReferenceConverter.toEntity(labelDTO));
} catch (InstanceNotFoundException e) {
throw new ValidationException("Label " + labelDTO.code
+ " not found");
}
}
}
}
@ -584,7 +602,7 @@ public final class OrderElementConverter {
HoursGroupDTO hoursGroupDTO,
ConfigurationOrderElementConverter configuration) {
if (!hoursGroup.getCode().equals(hoursGroupDTO.code)) {
throw new RuntimeException(
throw new ValidationException(
_("Not the same hours group, impossible to update"));
}
@ -602,7 +620,8 @@ public final class OrderElementConverter {
MaterialAssignmentDTO materialAssignmentDTO) {
if (!materialAssignment.getMaterial().getCode().equals(
materialAssignmentDTO.materialCode)) {
throw new RuntimeException(_("Not the same material, impossible to update"));
throw new ValidationException(
_("Not the same material, impossible to update"));
}
if (materialAssignmentDTO.units != null) {
@ -652,9 +671,13 @@ public final class OrderElementConverter {
directAdvanceAssignment = orderElement
.addSubcontractorAdvanceAssignment();
} catch (DuplicateValueTrueReportGlobalAdvanceException e) {
throw new RuntimeException(e);
throw new ValidationException(
_("Duplicate value true report global Advance for order element "
+ orderElement.getCode()));
} catch (DuplicateAdvanceAssignmentForOrderElementException e) {
throw new RuntimeException(e);
throw new ValidationException(
_("Duplicate advance assignment for order element "
+ orderElement.getCode()));
}
}
return directAdvanceAssignment;

View file

@ -0,0 +1,36 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.api;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsListDTO;
/**
* Service for managing material-related entities.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public interface IMaterialService {
public MaterialCategoryListDTO getMaterials();
public InstanceConstraintViolationsListDTO addMaterials(
MaterialCategoryListDTO materialCategoryListDTO);
}

View file

@ -0,0 +1,84 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import org.navalplanner.ws.common.api.IntegrationEntityDTO;
/**
* DTO for <code>MaterialCategory</code> entity.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class MaterialCategoryDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "material-category";
@XmlAttribute
public String name;
@XmlAttribute
public String parent;
@XmlElement
public MaterialCategoryListDTO subcategories;
@XmlElementWrapper(name = "material-list")
@XmlElement(name = "material")
public List<MaterialDTO> materials = new ArrayList<MaterialDTO>();
public MaterialCategoryDTO() {
}
public MaterialCategoryDTO(String code, String name, String parent,
MaterialCategoryListDTO subcategories, List<MaterialDTO> materials) {
super(code);
this.name = name;
this.parent = parent;
this.subcategories = subcategories;
this.materials = materials;
}
/**
* This constructor automatically generates a unique code. It is intended to
* facilitate the implementation of test cases that add new instances (such
* instances will have a unique code).
*/
public MaterialCategoryDTO(String name, String parent,
MaterialCategoryListDTO subcategories, List<MaterialDTO> materials) {
this(generateCode(), name, parent, subcategories, materials);
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -0,0 +1,49 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.api;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* DTO for a list of <code>MaterialCategory</code> entities.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@XmlRootElement(name = "material-category-list")
public class MaterialCategoryListDTO {
@XmlElement(name = "material-category")
public List<MaterialCategoryDTO> materialCategoryDTOs = new ArrayList<MaterialCategoryDTO>();
public MaterialCategoryListDTO() {
}
public MaterialCategoryListDTO(
List<MaterialCategoryDTO> materialCategoryDTOs) {
if (materialCategoryDTOs != null) {
this.materialCategoryDTOs = materialCategoryDTOs;
}
}
}

View file

@ -0,0 +1,80 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.api;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAttribute;
import org.navalplanner.ws.common.api.IntegrationEntityDTO;
/**
* DTO for <code>Material</code> entity.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public class MaterialDTO extends IntegrationEntityDTO {
public final static String ENTITY_TYPE = "material";
@XmlAttribute
public String description;
@XmlAttribute
public BigDecimal defaultPrice;
@XmlAttribute
public String unitType;
@XmlAttribute
public Boolean disabled;
public MaterialDTO() {
}
public MaterialDTO(String code, String description,
BigDecimal defaultPrice, String unitType, Boolean disabled) {
super(code);
this.description = description;
this.defaultPrice = defaultPrice;
this.unitType = unitType;
this.disabled = disabled;
}
/**
* This constructor automatically generates a unique code. It is intended to
* facilitate the implementation of test cases that add new instances (such
* instances will have a unique code).
*/
public MaterialDTO(String description, BigDecimal defaultPrice,
String unitType, Boolean disabled) {
this(generateCode(), description, defaultPrice, unitType, disabled);
}
@Override
public String getEntityType() {
return ENTITY_TYPE;
}
}

View file

@ -0,0 +1,30 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Specification of namespace for REST-based services.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@javax.xml.bind.annotation.XmlSchema(
elementFormDefault=javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
namespace=WSCommonGlobalNames.REST_NAMESPACE
)
package org.navalplanner.ws.materials.api;
import org.navalplanner.ws.common.api.WSCommonGlobalNames;

View file

@ -0,0 +1,274 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.impl;
import static org.navalplanner.web.I18nHelper._;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.navalplanner.business.common.Registry;
import org.navalplanner.business.common.exceptions.InstanceNotFoundException;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.materials.entities.Material;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.business.materials.entities.UnitType;
import org.navalplanner.ws.materials.api.MaterialCategoryDTO;
import org.navalplanner.ws.materials.api.MaterialCategoryListDTO;
import org.navalplanner.ws.materials.api.MaterialDTO;
/**
* Converter from/to material-related entities to/from DTOs.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
public final class MaterialConverter {
private MaterialConverter() {
}
public final static MaterialCategoryDTO toDTO(
MaterialCategory materialCategory) {
// converter the materials
List<MaterialDTO> materialDTOs = new ArrayList<MaterialDTO>();
for (Material m : materialCategory.getMaterials()) {
materialDTOs.add(toDTO(m));
}
if (materialDTOs.isEmpty()) {
materialDTOs = null;
}
// converter the subcategories
MaterialCategoryListDTO subcategories = createSubcategoriesList(materialCategory
.getSubcategories());
// get the parent code
String parentCode = null;
if (materialCategory.getParent() != null) {
parentCode = materialCategory.getParent().getCode();
}
return new MaterialCategoryDTO(materialCategory.getCode(),
materialCategory.getName(), parentCode, subcategories,
materialDTOs);
}
private static MaterialCategoryListDTO createSubcategoriesList(
Set<MaterialCategory> subcategories) {
List<MaterialCategoryDTO> DTOs = new ArrayList<MaterialCategoryDTO>();
for (MaterialCategory m : subcategories) {
DTOs.add(toDTO(m));
}
if (DTOs.isEmpty()) {
return null;
}
return new MaterialCategoryListDTO(DTOs);
}
public final static MaterialDTO toDTO(Material material) {
String unitTypeCode = null;
if (material.getUnitType() != null) {
unitTypeCode = material.getUnitType().getCode();
}
return new MaterialDTO(material.getCode(), material.getDescription(),
material.getDefaultUnitPrice(), unitTypeCode, material
.getDisabled());
}
public final static MaterialCategory toEntity(
MaterialCategoryDTO materialCategoryDTO) {
MaterialCategory materialCategory = toEntityCategory(materialCategoryDTO);
// find the parent
if (materialCategoryDTO.parent != null) {
try {
MaterialCategory parentCategory = Registry
.getMaterialCategoryDAO().findByCode(
materialCategoryDTO.parent);
materialCategory.setParent(parentCategory);
} catch (InstanceNotFoundException e) {
throw new ValidationException(
_("There is no material category with this code"));
}
}
return materialCategory;
}
public final static MaterialCategory toEntityCategory(
MaterialCategoryDTO materialCategoryDTO) {
MaterialCategory materialCategory = MaterialCategory.createUnvalidated(
StringUtils.trim(materialCategoryDTO.code), StringUtils
.trim(materialCategoryDTO.name));
// Create and add the materials
if (materialCategoryDTO.materials != null) {
for (MaterialDTO materialDTO : materialCategoryDTO.materials) {
materialCategory.addMaterial(toEntity(materialDTO));
}
}
// Create and add the subcategories
if (materialCategoryDTO.subcategories != null) {
for (MaterialCategoryDTO subCategoryDTO : materialCategoryDTO.subcategories.materialCategoryDTOs) {
materialCategory.addSubcategory(toEntitySubCategories(
subCategoryDTO, materialCategory));
}
}
return materialCategory;
}
public final static MaterialCategory toEntitySubCategories(
MaterialCategoryDTO materialCategoryDTO, MaterialCategory parent) {
MaterialCategory materialCategory = toEntityCategory(materialCategoryDTO);
// find the parent
if (materialCategoryDTO.parent != null) {
if (!materialCategoryDTO.parent.equalsIgnoreCase(parent.getCode())) {
throw new ValidationException(_("inconsistent parent code."));
}
}
return materialCategory;
}
private static Material toEntity(MaterialDTO materialDTO) {
Material material = Material.createUnvalidated(StringUtils
.trim(materialDTO.code), StringUtils
.trim(materialDTO.description), materialDTO.defaultPrice,
materialDTO.disabled);
if (materialDTO.unitType != null) {
try {
UnitType unitType = Registry.getUnitTypeDAO()
.findByCodeAnotherTransaction(
materialDTO.unitType);
material.setUnitType(unitType);
} catch (InstanceNotFoundException e) {
material.setUnitType(null);
}
}
return material;
}
public final static void updateMaterialCategory(
MaterialCategory materialCategory,
MaterialCategoryDTO materialCategoryDTO) throws ValidationException {
/* check the parent code */
if (((materialCategoryDTO.parent != null)
&& (materialCategory.getParent() != null)
&& (!materialCategory.getParent().getCode().equalsIgnoreCase(
materialCategoryDTO.parent)))
|| ((!(materialCategoryDTO.parent == null) && (materialCategory
.getParent() == null)))) {
throw new ValidationException(_("inconsistent parent code."));
}
/*
* 1: Update basic properties in existing material category and add new
* materials.
*/
if (materialCategoryDTO.materials != null) {
for (MaterialDTO materialDTO : materialCategoryDTO.materials) {
/* Step 1.1 requires each material DTO to have a code. */
if (StringUtils.isBlank(materialDTO.code)) {
throw new ValidationException(
_("missing code in a material"));
}
try {
Material material = materialCategory
.getMaterialByCode(materialDTO.code);
updateMaterial(material, materialDTO);
} catch (InstanceNotFoundException e) {
materialCategory.addMaterial(toEntity(materialDTO));
}
}
}
/*
* 2: Update basic properties in existing subcategories and add new
* subcategories.
*/
if (materialCategoryDTO.subcategories != null) {
for (MaterialCategoryDTO subcategoryDTO : materialCategoryDTO.subcategories.materialCategoryDTOs) {
/* Step 2.1 requires each subcategory DTO to have a code. */
if (StringUtils.isBlank(subcategoryDTO.code)) {
throw new ValidationException(
_("missing code in a subcategory"));
}
try {
MaterialCategory subcategory = materialCategory
.getSubcategoryByCode(subcategoryDTO.code);
updateMaterialCategory(subcategory, subcategoryDTO);
} catch (InstanceNotFoundException e) {
materialCategory
.addSubcategory(toEntity(subcategoryDTO));
}
}
}
/* 3: Update material category basic properties. */
materialCategory.updateUnvalidated(StringUtils
.trim(materialCategoryDTO.name));
}
public final static void updateMaterial(Material material,
MaterialDTO materialDTO) throws ValidationException {
if (materialDTO.unitType != null) {
try {
UnitType type = Registry.getUnitTypeDAO()
.findByCodeAnotherTransaction(
materialDTO.unitType);
material.setUnitType(type);
} catch (InstanceNotFoundException e) {
throw new ValidationException(_("unit type code not found"));
}
}
material.updateUnvalidated(StringUtils.trim(materialDTO.description),
materialDTO.defaultPrice, materialDTO.disabled);
}
}

View file

@ -0,0 +1,95 @@
/*
* This file is part of NavalPlan
*
* Copyright (C) 2009 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.navalplanner.ws.materials.impl;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.navalplanner.business.common.daos.IIntegrationEntityDAO;
import org.navalplanner.business.common.exceptions.ValidationException;
import org.navalplanner.business.materials.daos.IMaterialCategoryDAO;
import org.navalplanner.business.materials.entities.MaterialCategory;
import org.navalplanner.ws.common.api.InstanceConstraintViolationsListDTO;
import org.navalplanner.ws.common.impl.GenericRESTService;
import org.navalplanner.ws.materials.api.IMaterialService;
import org.navalplanner.ws.materials.api.MaterialCategoryDTO;
import org.navalplanner.ws.materials.api.MaterialCategoryListDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* REST-based implementation of <code>IMaterialService</code>.
* @author Susana Montes Pedreira <smontes@wirelessgalicia.com>
*/
@Path("/materialcategories/")
@Produces("application/xml")
@Service("materialServiceREST")
public class MaterialServiceREST extends
GenericRESTService<MaterialCategory, MaterialCategoryDTO> implements
IMaterialService {
@Autowired
private IMaterialCategoryDAO materialCategoryDAO;
@Override
@GET
@Transactional(readOnly = true)
public MaterialCategoryListDTO getMaterials() {
return new MaterialCategoryListDTO(findAll());
}
@Override
@POST
@Consumes("application/xml")
public InstanceConstraintViolationsListDTO addMaterials(
MaterialCategoryListDTO materialCategoryListDTO) {
return save(materialCategoryListDTO.materialCategoryDTOs);
}
@Override
protected MaterialCategory toEntity(MaterialCategoryDTO entityDTO) {
return MaterialConverter.toEntity(entityDTO);
}
@Override
protected MaterialCategoryDTO toDTO(MaterialCategory entity) {
return MaterialConverter.toDTO(entity);
}
@Override
protected IIntegrationEntityDAO<MaterialCategory> getIntegrationEntityDAO() {
return materialCategoryDAO;
}
@Override
protected void updateEntity(MaterialCategory entity,
MaterialCategoryDTO entityDTO)
throws ValidationException {
MaterialConverter.updateMaterialCategory(entity, entityDTO);
}
}

Some files were not shown because too many files have changed in this diff Show more