[Suiviobsmer-commits] r1079 - in trunk: wao-business/src/main/java/fr/ifremer/wao wao-business/src/main/java/fr/ifremer/wao/bean wao-business/src/main/java/fr/ifremer/wao/entity wao-business/src/main/java/fr/ifremer/wao/io/csv2 wao-business/src/main/java/fr/ifremer/wao/io/csv2/models wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations wao-business/src/main/java/fr/ifremer/wao/service wao-business/src/main/xmi wao-business/src/test/java/fr/ifremer/wao wao-business/src/test/java/fr/ifremer/wao
Author: bleny Date: 2011-03-21 22:44:39 +0000 (Mon, 21 Mar 2011) New Revision: 1079 Log: update import-export for contacts (ObsMer and ObsVente), refactoring of ServiceContact Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/ContactImportExportModel.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UserParserFormatter.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UsersParserFormatter.java Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/PostgresMigrationCallback.java trunk/wao-business/src/main/java/fr/ifremer/wao/WaoUtils.java trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ContactStatus.java trunk/wao-business/src/main/java/fr/ifremer/wao/entity/SampleRowImpl.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Column.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Common.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Export.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Import.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/ModelBuilder.java trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/SamplingPlanImportExportModel.java trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java trunk/wao-business/src/main/xmi/wao.zargo trunk/wao-business/src/test/java/fr/ifremer/wao/AbstractServiceTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/entity/BoatImplTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/io/csv2/ExportTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceBoatImplTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactImplTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSynthesisImplTest.java trunk/wao-business/src/test/resources/import/contacts.csv trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Boats.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/ContactForm.java trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java trunk/wao-ui/src/main/webapp/ContactForm.tml trunk/wao-ui/src/main/webapp/js/contactForm.js Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/PostgresMigrationCallback.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/PostgresMigrationCallback.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/PostgresMigrationCallback.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -824,7 +824,7 @@ queries.add("ALTER TABLE SampleRow ADD observationUnit CHARACTER VARYING(255);"); queries.add("ALTER TABLE SampleRow ADD CONSTRAINT observationUnit_fkey FOREIGN KEY (observationUnit) REFERENCES TerrestrialDivision(topiaId);"); - queries.add("CREATE TABLE SampleRow_Observers (" + + queries.add("CREATE TABLE Observers_SampleRow (" + "sampleRow character varying(255) NOT NULL," + "observers character varying(255) NOT NULL," + "CONSTRAINT observers_fkey FOREIGN KEY (observers) " + Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/WaoUtils.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/WaoUtils.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/WaoUtils.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -25,6 +25,7 @@ package fr.ifremer.wao; import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.mail.EmailException; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; @@ -217,47 +218,50 @@ * @see #projectProperty(Class, java.util.List, String) */ public static <T,E> Map<T, E> projectPropertyUnique(List<E> elements, String propertyName) { - Map<T, E> projection = new LinkedHashMap<T, E>(); - for (E element : elements) { - T key; - try { - key = (T) PropertyUtils.getProperty(element, propertyName); - } catch (IllegalAccessException e) { - throw new RuntimeException(e); - } catch (InvocationTargetException e) { - throw new RuntimeException(e); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); + Map<T, E> projection = null; + if (elements != null) { + projection = new LinkedHashMap<T, E>(); + for (E element : elements) { + T key; + try { + key = (T) PropertyUtils.getProperty(element, propertyName); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } catch (InvocationTargetException e) { + throw new RuntimeException(e); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + projection.put(key, element); } - projection.put(key, element); } return projection; } public static <E extends TopiaEntity> void createOrUpdate(Class<E> clazz, Iterator<E> entitiesIterator, - TopiaDAO<E> dao, String... idProperties) - throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, TopiaException { + TopiaDAO<E> dao, String... idProperties) throws TopiaException { while (entitiesIterator.hasNext()) { E entity = entitiesIterator.next(); createOrUpdate(clazz, entity, dao, idProperties); } } - public static <E extends TopiaEntity> void createOrUpdate(Class<E> clazz, E entity, - TopiaDAO<E> dao, String... idProperties) - throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, TopiaException { + public static <E extends TopiaEntity> E createOrUpdate(Class<E> clazz, E entity, + TopiaDAO<E> dao, String... idProperties) throws TopiaException { + if (idProperties.length == 0) { + String[] topiaIdProperties = { TopiaEntity.TOPIA_ID }; + idProperties = topiaIdProperties; + } Binder<E, E> binder = BinderFactory.newBinder(clazz); - Map<String, Object> properties = new HashMap<String, Object>(); - for (String idProperty : idProperties) { - properties.put(idProperty, PropertyUtils.getProperty(entity, idProperty)); - } + Map<String, Object> properties = binder.obtainProperties(entity, idProperties); E existingEntity = dao.findByProperties(properties); if (existingEntity == null) { - dao.create(entity); + existingEntity = dao.create(entity); } else { binder.copyExcluding(entity, existingEntity, TopiaEntity.TOPIA_ID, TopiaEntity.TOPIA_CREATE_DATE, TopiaEntity.TOPIA_VERSION); - dao.update(existingEntity); + existingEntity = dao.update(existingEntity); } + return existingEntity; } } Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ContactStatus.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ContactStatus.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/bean/ContactStatus.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -24,6 +24,7 @@ package fr.ifremer.wao.bean; +import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.entity.Contact; import fr.ifremer.wao.entity.SampleMonth; @@ -210,7 +211,7 @@ * retrieving sampleMonth corresponding to a contact. * Used in {@link fr.ifremer.wao.service.ServiceContact} */ - public static final class NullSampleMonthException extends Exception { + public static final class NullSampleMonthException extends WaoBusinessException { private static final long serialVersionUID = 1L; Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/entity/SampleRowImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/entity/SampleRowImpl.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/entity/SampleRowImpl.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -93,8 +93,8 @@ sampleMonth = curr; } - if (log.isDebugEnabled()) { - log.debug("date " + date + " is in month " + monthFormat.format(curr.getPeriodDate()) + + if (log.isTraceEnabled()) { + log.trace("date " + date + " is in month " + monthFormat.format(curr.getPeriodDate()) + " [" + firstDayOfMonth + " ; " + lastDayOfMonth + "] : " + dateIsInMonth); } } @@ -106,7 +106,8 @@ } if (log.isDebugEnabled()) { - log.debug("sampleMonth for date " + date + " is " + (sampleMonth == null ? "null" : monthFormat.format(sampleMonth.getPeriodDate()))); + log.debug("sampleMonth for date " + date + " is " + + (sampleMonth == null ? "null" : monthFormat.format(sampleMonth.getPeriodDate()))); } return sampleMonth; Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Column.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Column.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Column.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -49,6 +49,7 @@ this.headerName = headerName; this.valueGetter = valueGetter; this.valueFormatter = valueFormatter; + this.ignored = true; } public Column(String headerName, ValueGetterSetter<E, T> valueGetterSetter, ValueParserFormatter<T> valueParserFormatter) { Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Common.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Common.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Common.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -1,13 +1,18 @@ package fr.ifremer.wao.io.csv2; -import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.lang.StringUtils; +import org.nuiton.util.StringUtil; -import java.lang.reflect.InvocationTargetException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; public class Common { @@ -35,7 +40,7 @@ @Override public void set(E bean, T value) throws Exception { - BeanUtils.setProperty(bean, propertyName, value); + BeanUtilsBean.getInstance().getPropertyUtils().setProperty(bean, propertyName, value); } @Override @@ -55,15 +60,123 @@ @Override public Date parse(String value) throws ParseException { - return dateFormat.parse(value); + Date date = null; + if (StringUtils.isNotBlank(value)) { + date = dateFormat.parse(value); + } + return date; } @Override - public String format(Date value) { - return dateFormat.format(value); + public String format(Date date) { + String value = ""; + if (date != null) { + value = dateFormat.format(date); + } + return value; } } + public static class ToStringParserFormatter<E> implements ValueParserFormatter<E> { + + protected Map<E, String> toStrings = new HashMap<E, String>(); + + protected Map<String, E> fromString = new HashMap<String, E>(); + + public ToStringParserFormatter(List<E> values) { + this(values, null); + } + + public ToStringParserFormatter(E[] values) { + computeToStrings(values, null); + } + + public ToStringParserFormatter(List<E> values, StringUtil.ToString<E> toString) { + computeToStrings(values, toString); + } + + /** fill toStrings and fromString */ + protected void computeToStrings(E[] values, StringUtil.ToString<E> toString) { + List<E> valuesAsList = new LinkedList<E>(); + for (E value : values) { + valuesAsList.add(value); + } + computeToStrings(valuesAsList, toString); + } + + /** fill toStrings and fromString */ + protected void computeToStrings(List<E> values, StringUtil.ToString<E> toString) { + for (E value : values) { + String valueToString; + if (toString == null) { + valueToString = value.toString(); + } else { + valueToString = toString.toString(value); + } + toStrings.put(value, valueToString); + fromString.put(valueToString, value); + } + } + + @Override + public String format(E value) { + return toStrings.get(value); + } + + @Override + public E parse(String value) throws ParseException { + return fromString.get(value); + } + } + + public static final ValueParserFormatter<Boolean> BOOLEAN = new ValueParserFormatter<Boolean>() { + + @Override + public String format(Boolean bool) { + String value; + if (bool == null) { + value = "?"; + } else if (bool) { + value = "Y"; + } else { + value = "N"; + } + return value; + } + + @Override + public Boolean parse(String value) throws ParseException { + Boolean result; + if (StringUtils.isBlank(value) || "?".equals(value)) { + result = null; + } else if ("Y".equals(value)) { + result = true; + } else if ("N".equals(value)) { + result = false; + } else { + result = Boolean.parseBoolean(value); + } + return result; + } + }; + public static final ValueParserFormatter<Date> DAY = new DateValue("dd/MM/yyyy"); + public static final ValueParserFormatter<Date> DAY_TIME = new DateValue("dd/MM/yyyy HH:mm"); + + public static class ValueSaver<E, T> implements ValueGetterSetter<E, T> { + + protected T value; + + @Override + public T get(E object) throws Exception { + return value; + } + + @Override + public void set(E object, T value) throws Exception { + this.value = value; + } + } + } Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Export.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Export.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Export.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -44,6 +44,11 @@ for (ExportableColumn column : model.getColumnsForExport()) { Object value = column.getValue(object); String formattedValue = column.formatValue(value); + boolean valueNeedQuotes = formattedValue.contains(separator) + || formattedValue.contains("\n"); + if (valueNeedQuotes) { + formattedValue = "\"" + formattedValue + "\""; + } csv.append(formattedValue).append(separator); } csv.append("\n"); Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Import.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Import.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/Import.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -193,11 +193,19 @@ } // contravariance ftw + Object parsedValue; try { - Object parsedValue = field.parseValue(value); + parsedValue = field.parseValue(value); + } catch (Exception e) { + throw new RuntimeException("exception while parsing value '" + value + "' at column '" + + field.getHeaderName() + "' at line " + lineNumber, e); + } + + try { field.setValue(element, parsedValue); } catch (Exception e) { - throw new RuntimeException("exception while reading line " + lineNumber, e); + throw new RuntimeException("exception while setting value '" + parsedValue + "' on '" + + element + "' at line " + lineNumber, e); } } Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/ModelBuilder.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/ModelBuilder.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/ModelBuilder.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -50,6 +50,7 @@ public <T> ExportableColumn<E, T> newColumnForExport(String headerName, ValueGetter<E, T> valueGetter, ValueFormatter<T> valueFormatter) { ExportableColumn<E, T> newColumn = new Column(headerName, valueGetter, valueFormatter); columnsForExport.add(newColumn); + columnsForExport.add(newColumn); return newColumn; } Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/ContactImportExportModel.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/ContactImportExportModel.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/ContactImportExportModel.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -0,0 +1,247 @@ +package fr.ifremer.wao.io.csv2.models; + +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.bean.ContactState; +import fr.ifremer.wao.bean.DataReliability; +import fr.ifremer.wao.bean.LocationType; +import fr.ifremer.wao.bean.ObsProgram; +import fr.ifremer.wao.entity.Boat; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.entity.ContactImpl; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.entity.TerrestrialLocation; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.io.csv2.Common; +import fr.ifremer.wao.io.csv2.ExportModel; +import fr.ifremer.wao.io.csv2.ExportableColumn; +import fr.ifremer.wao.io.csv2.ImportModel; +import fr.ifremer.wao.io.csv2.ImportableColumn; +import fr.ifremer.wao.io.csv2.ModelBuilder; +import fr.ifremer.wao.io.csv2.ValueGetter; +import fr.ifremer.wao.io.csv2.ValueGetterSetter; +import fr.ifremer.wao.io.csv2.ValueParserFormatter; +import fr.ifremer.wao.io.csv2.models.operations.UserParserFormatter; +import fr.ifremer.wao.io.csv2.models.operations.UsersParserFormatter; +import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang.StringUtils; + +import java.text.ParseException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ContactImportExportModel implements ImportModel<Contact>, ExportModel<Contact> { + + static class TerrestrialLocationParserFormatter implements ValueParserFormatter<TerrestrialLocation> { + + protected Map<LocationType, Map<String, TerrestrialLocation>> indexedLocations; + + protected List<TerrestrialLocation> terrestrialLocations; + + protected ValueGetter<Contact, LocationType> locationTypeGetter; + + TerrestrialLocationParserFormatter(List<TerrestrialLocation> terrestrialLocations, + ValueGetter<Contact, LocationType> locationTypeGetter) { + this.terrestrialLocations = terrestrialLocations; + this.locationTypeGetter = locationTypeGetter; + } + + @Override + public String format(TerrestrialLocation terrestrialLocation) { + return terrestrialLocation.getCode(); + } + + @Override + public TerrestrialLocation parse(String code) throws ParseException { + if (indexedLocations == null) { + indexedLocations = new HashMap<LocationType, Map<String, TerrestrialLocation>>(); + for (TerrestrialLocation terrestrialLocation : terrestrialLocations) { + LocationType locationType = terrestrialLocation.getLocationType(); + Map<String, TerrestrialLocation> locationsForType = indexedLocations.get(locationType); + if (locationsForType == null) { + locationsForType = new HashMap<String, TerrestrialLocation>(); + } + locationsForType.put(terrestrialLocation.getCode(), terrestrialLocation); + indexedLocations.put(locationType, locationsForType); + } + } + if (StringUtils.isEmpty(code)) { + throw new IllegalArgumentException("Il manque le code du lieu"); + } + LocationType locationType; + try { + locationType = locationTypeGetter.get(null); + } catch (Exception e) { + throw new RuntimeException(e); + } + if (locationType == null) { + throw new IllegalArgumentException("Le code du lieu doit être renseigné"); + } + TerrestrialLocation terrestrialLocation = indexedLocations.get(locationType).get(code); + if (terrestrialLocation == null) { + throw new IllegalArgumentException("Il n'y a pas de lieu de type '" + locationType.toString() + + "' ayant pour code '" + code + "'"); + } + return terrestrialLocation; + } + } + + static class SampleRowParserFormatter implements ValueParserFormatter<SampleRow> { + + protected Map<String, SampleRow> indexedSampleRows; + + SampleRowParserFormatter(List<SampleRow> sampleRows) { + indexedSampleRows = WaoUtils.projectPropertyUnique(sampleRows, SampleRow.PROPERTY_CODE); + } + + @Override + public String format(SampleRow sampleRow) { + return sampleRow.getCode(); + } + + @Override + public SampleRow parse(String sampleRowCode) throws ParseException { + String trimmedCode = sampleRowCode.trim(); + if (StringUtils.isEmpty(trimmedCode)) { + throw new IllegalArgumentException("Il manque le code de la ligne de plan associée"); + } + SampleRow sampleRow = indexedSampleRows.get(sampleRowCode); + if (sampleRow == null) { + throw new IllegalArgumentException("Il n'y a pas de ligne du plan avec le code '" + sampleRowCode + "'"); + } + return sampleRow; + } + } + + static class BoatParserFormatter implements ValueParserFormatter<Boat> { + + protected Map<Integer, Boat> indexedBoats; + + BoatParserFormatter(List<Boat> boats) { + indexedBoats = WaoUtils.projectPropertyUnique(boats, Boat.PROPERTY_IMMATRICULATION); + } + + @Override + public String format(Boat boat) { + return String.valueOf(boat.getImmatriculation()); + } + + @Override + public Boat parse(String value) throws ParseException { + String trimmedValue = value.trim(); + if (trimmedValue.isEmpty()) { + throw new IllegalArgumentException("Il faut préciser l'immatriculation du navire associé au contact"); + } + Integer key = Integer.valueOf(trimmedValue); + Boat boat = indexedBoats.get(key); + if (boat == null) { + throw new IllegalArgumentException("Il n'y a pas de navire avec l'immatriculation '" + + value + "'"); + } + return boat; + } + } + + protected ObsProgram obsProgram; + + protected List<WaoUser> waoUsers; + + protected List<TerrestrialLocation> terrestrialLocations; + + protected List<SampleRow> sampleRows; + + protected List<Boat> boats; + + /** for export */ + public ContactImportExportModel(ObsProgram obsProgram) { + this.obsProgram = obsProgram; + } + + /** for import */ + public ContactImportExportModel(ObsProgram obsProgram, List<WaoUser> waoUsers, + List<TerrestrialLocation> terrestrialLocations, + List<SampleRow> sampleRows, List<Boat> boats) { + this.obsProgram = obsProgram; + this.waoUsers = waoUsers; + this.terrestrialLocations = terrestrialLocations; + this.sampleRows = sampleRows; + this.boats = boats; + } + + @Override + public char getSeparator() { + return ';'; + } + + @Override + public void pushCsvHeaderNames(List<String> headerNames) { + // nothing to do + } + + @Override + public Contact newEmptyInstance() { + Contact newContact = new ContactImpl(); + newContact.setObsProgram(obsProgram); + return newContact; + } + + protected ModelBuilder<Contact> getModel() { + ModelBuilder<Contact> modelBuilder = new ModelBuilder<Contact>(); + modelBuilder.newColumnForImportExport("CONTACT_ID", Contact.TOPIA_ID); + modelBuilder.newColumnForImportExport("CONTACT_DATE_CREATION", Contact.PROPERTY_CREATION_DATE, Common.DAY_TIME); + modelBuilder.newColumnForImportExport("CONTACT_OBSERVATEUR_PRINCIPAL", Contact.PROPERTY_MAIN_OBSERVER, new UserParserFormatter(waoUsers)); + modelBuilder.newColumnForImportExport("CONTACT_OBSERVATEURS_SECONDAIRES", Contact.PROPERTY_SECONDARY_OBSERVERS, new UsersParserFormatter(waoUsers)); + modelBuilder.newColumnForImportExport("CONTACT_ETAT", "contactState", new Common.ToStringParserFormatter(ContactState.getAllowedStates(obsProgram))); + modelBuilder.newColumnForImportExport("CONTACT_DEBUT_OBSERVATION", Contact.PROPERTY_OBSERVATION_BEGIN_DATE, Common.DAY_TIME); + modelBuilder.newColumnForImportExport("CONTACT_FIN_OBSERVATION", Contact.PROPERTY_OBSERVATION_END_DATE, Common.DAY_TIME); + modelBuilder.newColumnForImportExport("CONTACT_SAISIE_DONNEES", Contact.PROPERTY_DATA_INPUT_DATE, Common.DAY); + modelBuilder.newColumnForImportExport("CONTACT_COMMENTAIRE_OBSERVATEUR", Contact.PROPERTY_COMMENT); + modelBuilder.newColumnForImportExport("CONTACT_COMMENTAIRE_COORDINATEUR", Contact.PROPERTY_COMMENT_COORDINATOR); + modelBuilder.newColumnForImportExport("CONTACT_COMMENTAIRE_PROGRAMME", Contact.PROPERTY_COMMENT_ADMIN); + + modelBuilder.newColumnForImportExport("PLAN_CODE", Contact.PROPERTY_SAMPLE_ROW, new SampleRowParserFormatter(sampleRows)); + modelBuilder.newColumnForImportExport("NAVIRE_IMMATRICULATION", Contact.PROPERTY_BOAT, new BoatParserFormatter(boats)); + modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_SOCIETE", Contact.PROPERTY_VALIDATION_COMPANY, Common.BOOLEAN); + modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_PROGRAMME", Contact.PROPERTY_VALIDATION_PROGRAM, Common.BOOLEAN); + + if (ObsProgram.OBSMER.equals(obsProgram)) { + modelBuilder.newColumnForImportExport("CONTACT_QUALITE_DONNEE", "dataReliability", + new Common.ToStringParserFormatter<DataReliability>(DataReliability.values())); + } + + if (ObsProgram.OBSVENTE.equals(obsProgram)) { + ValueGetterSetter<Contact, LocationType> locationTypeGetter = new Common.ValueSaver<Contact, LocationType>(); + modelBuilder.newMandatoryColumn("CONTACT_LIEU_TYPE", new Common.ToStringParserFormatter<LocationType>(LocationType.values()), locationTypeGetter); + modelBuilder.newColumnForExport("CONTACT_LIEU_TYPE", new ValueGetter<Contact, String>() { + @Override + public String get(Contact contact) throws Exception { + return contact.getTerrestrialLocation().getLocationType().toString(); + } + }); + + modelBuilder.newColumnForImportExport("CONTACT_LIEU_CODE", Contact.PROPERTY_TERRESTRIAL_LOCATION, + new TerrestrialLocationParserFormatter(terrestrialLocations, locationTypeGetter)); + + modelBuilder.newColumnForExport("CONTACT_LIEU_DESCRIPTION", new ValueGetter<Contact, String>() { + @Override + public String get(Contact contact) throws Exception { + return contact.getTerrestrialLocation().getDescription(); + } + }); + modelBuilder.newColumnForImportExport("CONTACT_ECHANTILLONNAGE_COMPLET", Contact.PROPERTY_COMPLETE_SAMPLING, Common.BOOLEAN); + } + + return modelBuilder; + } + + @Override + public Collection<ImportableColumn> getColumnsForImport() { + return getModel().getColumnsForImport(); + } + + @Override + public Collection<ExportableColumn> getColumnsForExport() { + return getModel().getColumnsForExport(); + } +} Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/SamplingPlanImportExportModel.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/SamplingPlanImportExportModel.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/SamplingPlanImportExportModel.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -142,36 +142,6 @@ } } - static class UsersParserFormatter implements ValueParserFormatter<List<WaoUser>> { - - protected static final String SEPARATOR = ","; - - /** all waoUsers in the database when import was started, indexed by logins */ - protected Map<String, WaoUser> allWaoUsers; - - @Override - public String format(List<WaoUser> value) { - Set<String> usersLogin = WaoUtils.<String, WaoUser> projectPropertyUnique(value, WaoUser.PROPERTY_LOGIN).keySet(); - String commaSeparatedLogins = StringUtils.join(usersLogin, ", "); - return commaSeparatedLogins; - } - - @Override - public List<WaoUser> parse(String value) throws ParseException { - String[] logins = StringUtils.split(value, SEPARATOR); - List<WaoUser> users = new LinkedList<WaoUser>(); - for (String login : logins) { - String trimmedLogin = login.trim(); - WaoUser user = allWaoUsers.get(trimmedLogin); - if (user == null) { - throw new IllegalArgumentException("il n'y a pas d'utilisateur avec l'identifiant '" + login + "'"); - } - users.add(user); - } - return users; - } - } - protected List<TerrestrialDivision> observationUnits; protected List<WaoUser> allWaoUsers; Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UserParserFormatter.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UserParserFormatter.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UserParserFormatter.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -0,0 +1,35 @@ +package fr.ifremer.wao.io.csv2.models.operations; + + +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.io.csv2.ValueParserFormatter; + +import java.text.ParseException; +import java.util.List; +import java.util.Map; + +public class UserParserFormatter implements ValueParserFormatter<WaoUser> { + + /** all waoUsers in the database when import was started, indexed by logins */ + protected Map<String, WaoUser> indexedWaoUsers; + + public UserParserFormatter(List<WaoUser> waoUsers) { + this.indexedWaoUsers = WaoUtils.projectPropertyUnique(waoUsers, WaoUser.PROPERTY_LOGIN); + } + + @Override + public String format(WaoUser waoUser) { + String userLogin = waoUser.getLogin(); + return userLogin; + } + + @Override + public WaoUser parse(String login) throws ParseException { + WaoUser user = indexedWaoUsers.get(login.trim()); + if (user == null) { + throw new IllegalArgumentException("il n'y a pas d'utilisateur avec l'identifiant '" + login + "'"); + } + return user; + } +} Added: trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UsersParserFormatter.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UsersParserFormatter.java (rev 0) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/io/csv2/models/operations/UsersParserFormatter.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -0,0 +1,46 @@ +package fr.ifremer.wao.io.csv2.models.operations; + +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.io.csv2.ValueParserFormatter; +import org.apache.commons.lang.StringUtils; + +import java.text.ParseException; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class UsersParserFormatter implements ValueParserFormatter<List<WaoUser>> { + + protected static final String SEPARATOR = ","; + + /** all waoUsers in the database when import was started, indexed by logins */ + protected Map<String, WaoUser> indexedWaoUsers; + + public UsersParserFormatter(List<WaoUser> waoUsers) { + this.indexedWaoUsers = WaoUtils.projectPropertyUnique(waoUsers, WaoUser.PROPERTY_LOGIN); + } + + @Override + public String format(List<WaoUser> value) { + Set<String> usersLogin = WaoUtils.<String, WaoUser> projectPropertyUnique(value, WaoUser.PROPERTY_LOGIN).keySet(); + String commaSeparatedLogins = StringUtils.join(usersLogin, ", "); + return commaSeparatedLogins; + } + + @Override + public List<WaoUser> parse(String value) throws ParseException { + String[] logins = StringUtils.split(value, SEPARATOR); + List<WaoUser> users = new LinkedList<WaoUser>(); + for (String login : logins) { + String trimmedLogin = login.trim(); + WaoUser user = indexedWaoUsers.get(trimmedLogin); + if (user == null) { + throw new IllegalArgumentException("il n'y a pas d'utilisateur avec l'identifiant '" + login + "'"); + } + users.add(user); + } + return users; + } +} Modified: trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java =================================================================== --- trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/main/java/fr/ifremer/wao/service/ServiceContactImpl.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -43,10 +43,10 @@ import fr.ifremer.wao.bean.DataReliability; import fr.ifremer.wao.bean.ObsProgram; import fr.ifremer.wao.bean.SamplingStrategy; -import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.bean.ValidationResult; import fr.ifremer.wao.bean.ValidationResultImpl; import fr.ifremer.wao.entity.Boat; +import fr.ifremer.wao.entity.BoatDAO; import fr.ifremer.wao.entity.Company; import fr.ifremer.wao.entity.Contact; import fr.ifremer.wao.entity.ContactDAO; @@ -58,6 +58,9 @@ import fr.ifremer.wao.entity.Profession; import fr.ifremer.wao.entity.SampleMonth; import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.entity.SampleRowDAO; +import fr.ifremer.wao.entity.TerrestrialLocation; +import fr.ifremer.wao.entity.TerrestrialLocationDAO; import fr.ifremer.wao.entity.WaoUser; import fr.ifremer.wao.entity.WaoUserDAO; import fr.ifremer.wao.io.ContactInput; @@ -72,6 +75,11 @@ import fr.ifremer.wao.io.csv.WaoCsvHeader.ContactHeader; import fr.ifremer.wao.io.csv.WaoCsvHeader.FISHING_ZONE; import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; +import fr.ifremer.wao.io.csv2.Export; +import fr.ifremer.wao.io.csv2.ExportModel; +import fr.ifremer.wao.io.csv2.Import; +import fr.ifremer.wao.io.csv2.ImportModel; +import fr.ifremer.wao.io.csv2.models.ContactImportExportModel; import org.apache.commons.lang.BooleanUtils; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.StringUtils; @@ -91,12 +99,14 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -139,20 +149,22 @@ } @Override - protected Contact executeGetContact(TopiaContext transaction, String contactId) throws Exception { + protected Contact executeGetContact(TopiaContext transaction, String contactId) throws TopiaException { ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); Contact contact = dao.findByTopiaId(contactId); // force load - contact.getMainObserver(); - contact.sizeSecondaryObservers(); - contact.getSampleRow().sizeSampleMonth(); - contact.getBoat().getName(); + if (contact != null) { + contact.getMainObserver(); + contact.sizeSecondaryObservers(); + contact.getSampleRow().sizeSampleMonth(); + contact.getBoat().getName(); - if (contact.getObsProgram() == ObsProgram.OBSVENTE) { - // load - contact.getSampleRow().getTerrestrialLocation(); - contact.getTerrestrialLocation(); + if (contact.getObsProgram() == ObsProgram.OBSVENTE) { + // load + contact.getSampleRow().getTerrestrialLocation(); + contact.getTerrestrialLocation(); + } } return contact; @@ -183,9 +195,9 @@ // contactProperty.sampleRowProperty().sampleMonth()); // TODO-fdesbois-2010-06-18 : manage aliases in addLoad addLoad(TopiaQuery.getProperty(Contact.PROPERTY_MAIN_OBSERVER, WaoUser.PROPERTY_COMPANY), - TopiaQuery.getProperty(Contact.PROPERTY_SAMPLE_ROW, SampleRow.PROPERTY_SAMPLE_MONTH) + TopiaQuery.getProperty(Contact.PROPERTY_SAMPLE_ROW, SampleRow.PROPERTY_SAMPLE_MONTH) // TopiaQuery.getProperty(Contact.SAMPLE_ROW, SampleRow.PROFESSION, Profession.DCF5CODE) - ); +); if (log.isDebugEnabled()) { log.debug("query to get contacts with load is " + query); @@ -228,16 +240,172 @@ } @Override - protected Contact executeGetNewContact(TopiaContext transaction, WaoUser user, - SampleRow row, Boat boat) throws Exception { + protected ValidationResult executeValidateContact(TopiaContext transaction, Contact contact) throws TopiaException { + + boolean success = true; + String message = null; + + if (contact.getMainObserver() == null) { + success = false; + message = "Il faut au moins un observateur référant"; + } + + if (success && contact.getSecondaryObservers() != null && + contact.getSecondaryObservers().contains(contact.getMainObserver())) { + success = false; + message = "L'utilisateur référant ne doit pas se trouver aussi parmi les observateurs secondaires"; + } + + // Validation for saving contact depends on contactState + ContactState contactState = contact.getContactState(); + Date observationBeginDate = contact.getObservationBeginDate(); + if (log.isDebugEnabled()) { + log.debug("For state : " + contactState + " and observation begin date " + observationBeginDate); + } + + boolean operationBeginDateIsValid = contact.getSampleRow().isValid(observationBeginDate); + + if (log.isDebugEnabled()) { + log.debug("operation begin data is valid : " + operationBeginDateIsValid); + } + + if (success && observationBeginDate != null && ! operationBeginDateIsValid) { + success = false; + message = "La date de début de la marée doit correspondre à un " + + "mois valide (non vide) de la ligne " + contact.getSampleRow().getCode(); + } + + Date observationEndDate = contact.getObservationEndDate(); + if (success && observationBeginDate != null && observationEndDate != null + && observationEndDate.before(observationBeginDate)) { + success = false; + message = "La date de fin d'observation ne peut pas être antérieure à celle du début"; + } + + Date currentDate = context.getCurrentDate(); + + if (success && observationEndDate != null && observationEndDate.after(currentDate)) { + success = false; + message = "La date de fin de la marée ne peut pas être postérieure à la date du jour"; + } + + Date dataInputDate = contact.getDataInputDate(); + if (success && observationEndDate != null && dataInputDate != null && observationEndDate.after(dataInputDate)) { + success = false; + message = "La date de saisie des données ne peut pas être antérieure à la date de fin de la marée"; + } + + if (success && dataInputDate != null && dataInputDate.after(currentDate)) { + success = false; + message = "La date de saisie des données ne peut pas être postérieure à la date du jour"; + } + + // Non abouti, Refus ou Refus Définitif + if (success && contactState.isUnfinishedState()) { + + Contact oldContact = null; + if (contact.getTopiaId() != null) { + oldContact = executeGetContact(transaction, contact.getTopiaId()); + } + + if (oldContact != null) { + + String newComment = contact.getComment(); + + boolean commentDefined = StringUtils.isNotEmpty(newComment); + boolean commentChanged = commentDefined && + !newComment.equals(oldContact.getComment()); + + // Ano #2540 : NPE on oldState, extract boolean for + // previous unfinishedState case + boolean previousUnfinishedState = commentDefined && + oldContact.getContactState() != null && oldContact.getContactState().isUnfinishedState(); + + // Ano #2440 : no restriction if previous state is unfinished + if (previousUnfinishedState || commentChanged) { + + // RAZ des champs + contact.setObservationBeginDate(null); + contact.setObservationEndDate(null); + contact.setNbObservants(0); + contact.setMammalsCapture(false); + contact.setMammalsObservation(false); + contact.setDataInputDate(null); + + } else { + success = false; + message = "Vous devez ajouter un commentaire pour l'état '" + contactState + "'"; + } + } + // Embarquement Réalisé + } else if (success && contactState.equals(ContactState.OBSERVATION_DONE)) { + + if (observationBeginDate == null) { + success = false; + message = "La date de début de marée est obligatoire pour l'état '" + contactState + "'"; + } + if (success && observationEndDate == null) { + success = false; + message = "La date de fin d'observation marée est obligatoire pour l'état '" + contactState + "'"; + } + if (success && contact.getNbObservants() == 0) { + success = false; + message = "Il ne peut y avoir aucun observateur pour l'état '" + contactState + "'"; + } + + if (log.isDebugEnabled()) { + log.debug("validationProgram = " + contact.isValidationProgram()); + } + } + + if (success && contact.getObsProgram() == ObsProgram.OBSMER) { // this check is only for ObsMer + if (BooleanUtils.isTrue(contact.isValidationProgram())) { + // it's an admin validation, data-reliability field must be filled + if (log.isDebugEnabled()) { + log.debug("field data reliability is " + contact.getDataReliability()); + } + + if (contact.getDataReliability() == null || + contact.getDataReliability() == DataReliability.UNKNOWN) { + success = false; + message = WaoUtils.translate(n_("wao.business.contact.validation.dataReliabilityMissingForValidation")); + } else if (contact.getDataReliability() != DataReliability.RELIABLE + && StringUtils.isEmpty(contact.getCommentAdmin())) { + success = false; + message = WaoUtils.translate(n_("wao.business.contact.validation.commentAdminNecessaryForDataReliability"), + contact.getDataReliability().toString()); + } + } + } + + ValidationResult result = new ValidationResultImpl(); + result.setSuccess(success); + result.setMessage(message); + + if (log.isDebugEnabled()) { + String logMessage = "validation of contact " + contact + " return " + result.isSuccess(); + if ( ! result.isSuccess()) { + logMessage += ". reason is '" + result.getMessage() + "'"; + } + log.debug(logMessage); + } + + return result; + } + + @Override + protected Contact executeGetNewContact(TopiaContext transaction, ConnectedUser connectedUser, + SampleRow row, Boat boat) throws WaoBusinessException, TopiaException, EmailException { + ObsProgram obsProgram = row.getObsProgram(); + WaoUser user = connectedUser.getUser(); if (boat == null) { throw new NullPointerException("boat can not be null for program " + obsProgram); } if ( ! boat.canCreateContact(obsProgram, user.getCompany())) { - throw new WaoBusinessException("Ce navire ne peut être utilisé, il est inactif ou un contact en déjà en cours"); + throw new WaoBusinessException("Ce navire ne peut être utilisé, il est inactif ou un contact est déjà en cours"); } Contact newContact = new ContactImpl(); @@ -318,41 +486,10 @@ } } - saveContact(newContact, false); + executeSaveContact(transaction, connectedUser, newContact, false); return newContact; } - @Override - public void executeSaveContact(TopiaContext transaction, - Contact contact, boolean delete) - throws TopiaException, NullSampleMonthException, EmailException { - - checkObserver(contact); - checkSampleRow(contact); - - ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); - - if (log.isDebugEnabled()) { - log.debug("Create date : " + contact.getTopiaCreateDate()); - } - - Contact contactFound = dao.findByTopiaId(contact.getTopiaId()); - - //context.prepareTopiaId(Contact.class, contact); - if (delete) { - // Need to decrement estimated value if contactFound has - // OBSERVATION_DONE state and may be real value (normally not allowed) - updateSampleMonthTidesValue(transaction, contactFound, null, true); - - // Execute delete - dao.delete(contactFound); - } else { - notifyUsersForMammalsObservation(transaction, contactFound, contact); - createOrUpdateContact(dao, contact, contactFound, true); - } - transaction.commitTransaction(); - } - protected void notifyUsersForMammalsObservation(TopiaContext transaction, Contact contactFound, Contact contact) throws TopiaException { @@ -448,193 +585,173 @@ } } - protected void checkObserver(Contact contact) throws WaoException { - // Ano #2287 Temporary fix to avoid saving a null observer - if (contact.getMainObserver() == null) { - // Throw a NullPointerException to avoid saving null observer - Throwable exception = - new NullPointerException("observer can't be null to save" + - " the contact"); + /** + * Update the SampleMonth data for tidesValue (estimated and real) from + * {@code contact} compared to its old state {@code oldContact}. The + * estimated is update when contact state {@link ContactState#OBSERVATION_DONE} + * is changed. The real is update when contact validationCompany is changed. + * The {@code calculateReal} flag determines if the real tides has to be + * calculated or not. Three cases : + * <ul> + * <li>CREATE : {@code oldContact} = null and {@code contact} is defined</li> + * <li>UPDATE : both {@code oldContact} and {@code contact} are defined</li> + * <li>DELETE : {@code oldContact} is defined and {@code contact} = null</li> + * </ul> + * <p> + * <strong>Estimated Tides value</strong> = nbContacts with OBSERVATION_DONE + * state and not refused by program (validationProgram != FALSE) + * </p> + * <p> + * <strong>Real Tides value</strong> = nbContacts accepted by company + * (validationCompany = TRUE) and not refused by program + * (validationProgram != FALSE) + * </p> + * + * @param transaction used to update the SampleMonth + * @param oldContact old state of the contact + * @param contact changed can be null for delete case + * @param calculateReal to calculate real tides value + * @throws TopiaException for any Topia technical trouble + * @throws NullSampleMonthException if SampleMonth can't be found + */ + protected void updateSampleMonthTidesValue( + TopiaContext transaction, Contact oldContact, + Contact contact, boolean calculateReal) + throws TopiaException, NullSampleMonthException { - if (log.isWarnEnabled()) { - log.warn("observer null when saving contact", exception); - } - // This message will be displayed to Client - throw new WaoException( - "L'observateur n'a pas été renseigné correctement pour " + - "la sauvegarde du contact", exception); + if (oldContact == null && contact == null) { + throw new IllegalArgumentException("Both contact and oldContact" + + " can't be null to update sampleMonth tides value"); } - } - protected void checkSampleRow(Contact contact) throws WaoException { - // Ano #2356 Temporary fix to avoid saving a null sampleRow - if (contact.getSampleRow() == null) { - // Throw a NullPointerException to avoid saving null sampleRow - Throwable exception = - new NullPointerException("sampleRow can't be null to save" + - " the contact"); + // Instantiate contact status which provide status on oldContact and + // contact changes + ContactStatus status = new ContactStatus(oldContact, contact); - if (log.isWarnEnabled()) { - log.warn("sampleRow null when saving contact", exception); - } - // This message will be displayed to Client - throw new WaoException( - "La ligne du plan d'échantillonnage n'a pas été renseigné" + - " correctement pour la sauvegarde du contact", exception); - } - } - - @Override - protected ValidationResult executeValidateContact(TopiaContext transaction, Contact contact) throws Exception { - - boolean success = true; - String message = null; - - if (contact.getMainObserver() == null) { - success = false; - message = "Il faut au moins un observateur référant"; - } - - if (success && contact.getSecondaryObservers().contains(contact.getMainObserver())) { - success = false; - message = "L'utilisateur référant ne doit pas se trouver aussi parmi les observateurs secondaires"; - } - - // Validation for saving contact depends on contactState - ContactState contactState = contact.getContactState(); - Date observationBeginDate = contact.getObservationBeginDate(); if (log.isDebugEnabled()) { - log.debug("For state : " + contactState + " and observation begin date " + observationBeginDate); + log.debug(status.toString()); } - boolean operationBeginDateIsValid = contact.getSampleRow().isValid(observationBeginDate); + // Month of TideBeginDate has changed, must decrement values on + // old sampleMonth + boolean tideBeginDateChanged = false; + if (oldContact != null && contact != null && + status.isTideBeginDateMonthChanged()) { - if (log.isDebugEnabled()) { - log.debug("operation begin data is valid : " + operationBeginDateIsValid); - } + tideBeginDateChanged = status.isTideBeginDateMonthChanged(); - if (success && observationBeginDate != null && ! operationBeginDateIsValid) { - success = false; - message = "La date de début de la marée doit correspondre à un " + - "mois valide (non vide) de la ligne " + contact.getSampleRow().getCode(); - } + // Retrieve oldMonth from status + try { + SampleMonth oldMonth = status.getOldSampleMonth(transaction); - Date observationEndDate = contact.getObservationEndDate(); - if (success && observationBeginDate != null && observationEndDate != null - && observationEndDate.before(observationBeginDate)) { - success = false; - message = "La date de fin d'observation ne peut pas être antérieure à celle du début"; - } + // Apply changes on oldMonth + if (status.isOldContactValidate()) { + // decrement real tides + oldMonth.addRealTideTime(-1); + } + // Decrement estimated only if old state is OBSERVATION_DONE + // and old validationProgram is NOT FALSE + // the estimated value has already been decremented during + // refused + if (status.isOldContactDone() && BooleanUtils.isNotFalse( + oldContact.getValidationProgram())) { + // decrement estimated tides + oldMonth.addEstimatedTideTime(-1); + } - Date currentDate = context.getCurrentDate(); - - if (success && observationEndDate != null && observationEndDate.after(currentDate)) { - success = false; - message = "La date de fin de la marée ne peut pas être postérieure à la date du jour"; + // Catch the null exception, only a warning if the oldSampleMonth is + // not found + } catch (NullSampleMonthException eee) { + if (log.isWarnEnabled()) { + log.warn("Error on retrieve old sampleMonth", eee); + } + } } - Date dataInputDate = contact.getDataInputDate(); - if (success && observationEndDate != null && dataInputDate != null && observationEndDate.after(dataInputDate)) { - success = false; - message = "La date de saisie des données ne peut pas être antérieure à la date de fin de la marée"; - } + ContactState currentState = contact != null ? + contact.getContactState() : oldContact.getContactState(); - if (success && dataInputDate != null && dataInputDate.after(currentDate)) { - success = false; - message = "La date de saisie des données ne peut pas être postérieure à la date du jour"; - } + // Validation of contact has changed in status, modify realTides + // Only calculate real for a currentState equals to OBSERVATION_DONE + if (calculateReal && ContactState.OBSERVATION_DONE.equals(currentState) && + (status.isContactValidateChanged() || tideBeginDateChanged)) { - // Non abouti, Refus ou Refus Définitif - if (success && contactState.isUnfinishedState()) { + SampleMonth sampleMonth = status.getSampleMonth(transaction); - Contact oldContact = null; - if (contact.getTopiaId() != null) { - oldContact = executeGetContact(transaction, contact.getTopiaId()); + if (status.isNewContactValidate()) { + // increment real tides + sampleMonth.addRealTideTime(1); + // validationProgram becomes not FALSE, estimatedTides must be + // incremented + if (status.isNoMoreRefused()) { + sampleMonth.addEstimatedTideTime(1); + } + // never decrement if tideBeginDate has changed + } else if (status.isOldContactValidate() && !tideBeginDateChanged) { + // decrement real tides + sampleMonth.addRealTideTime(-1); + // validationProgram becomes FALSE, estimatedTides must be + // decremented + if (status.isRefused()) { + sampleMonth.addEstimatedTideTime(-1); + } } + } - if (oldContact != null) { + // ContactState of contact has changed in status, modify estimatedTides + if (status.isContactDoneChanged() || tideBeginDateChanged) { - String newComment = contact.getComment(); + SampleMonth sampleMonth = status.getSampleMonth(transaction); - boolean commentDefined = StringUtils.isNotEmpty(newComment); - boolean commentChanged = commentDefined && - !newComment.equals(oldContact.getComment()); - - // Ano #2540 : NPE on oldState, extract boolean for - // previous unfinishedState case - boolean previousUnfinishedState = commentDefined && - oldContact.getContactState() != null && oldContact.getContactState().isUnfinishedState(); - - // Ano #2440 : no restriction if previous state is unfinished - if (previousUnfinishedState || commentChanged) { - - // RAZ des champs - contact.setObservationBeginDate(null); - contact.setObservationEndDate(null); - contact.setNbObservants(0); - contact.setMammalsCapture(false); - contact.setMammalsObservation(false); - contact.setDataInputDate(null); - - } else { - success = false; - message = "Vous devez ajouter un commentaire pour l'état '" + contactState + "'"; - } + if (status.isNewContactDone()) { + // increment estimated tides + sampleMonth.addEstimatedTideTime(1); + // never decrement if tideBeginDate has changed + } else if (status.isOldContactDone() && !tideBeginDateChanged) { + // decrement estimated tides + sampleMonth.addEstimatedTideTime(-1); } - // Embarquement Réalisé - } else if (success && contactState.equals(ContactState.OBSERVATION_DONE)) { - - if (observationBeginDate == null) { - success = false; - message = "La date de début de marée est obligatoire pour l'état '" + contactState + "'"; - } - if (success && observationEndDate == null) { - success = false; - message = "La date de fin d'observation marée est obligatoire pour l'état '" + contactState + "'"; - } - if (success && contact.getNbObservants() == 0) { - success = false; - message = "Il ne peut y avoir aucun observateur pour l'état '" + contactState + "'"; - } - - if (log.isDebugEnabled()) { - log.debug("validationProgram = " + contact.isValidationProgram()); - } } + } - if (success && contact.getObsProgram() == ObsProgram.OBSMER) { // this check is only for ObsMer - if (BooleanUtils.isTrue(contact.isValidationProgram())) { - // it's an admin validation, data-reliability field must be filled - if (log.isDebugEnabled()) { - log.debug("field data reliability is " + contact.getDataReliability()); - } + /** + * Update the elligible boat depends on contact creation. The + * {@code contact} reference can only be created for a sampleRow and a + * boat if both are linked with an elligibleBoat. So this method is + * used to create the link if needed during contacts import. This + * elligibleBoat is needed for the contact owned by a company, so + * the companyActive property of ElligibleBoat will be set to TRUE. No + * admin has decided to explicitly create this link. + * + * @param transaction used to update the ElligibleBoat + * @param contact which contains sampleRow and boat to link + * @throws TopiaException for any Topia technical trouble + */ + protected void updateElligibleBoatForContact(TopiaContext transaction, + Contact contact) throws TopiaException { - if (contact.getDataReliability() == null || - contact.getDataReliability() == DataReliability.UNKNOWN) { - success = false; - message = WaoUtils.translate(n_("wao.business.contact.validation.dataReliabilityMissingForValidation")); - } else if (contact.getDataReliability() != DataReliability.RELIABLE - && StringUtils.isEmpty(contact.getCommentAdmin())) { - success = false; - message = WaoUtils.translate(n_("wao.business.contact.validation.commentAdminNecessaryForDataReliability"), - contact.getDataReliability().toString()); - } - } - } + Boat boat = contact.getBoat(); + SampleRow row = contact.getSampleRow(); - ValidationResult result = new ValidationResultImpl(); - result.setSuccess(success); - result.setMessage(message); + ElligibleBoatDAO elligibleDAO = + WaoDAOHelper.getElligibleBoatDAO(transaction); + ElligibleBoat elligible = + elligibleDAO.findByProperties( + ElligibleBoat.PROPERTY_BOAT, contact.getBoat(), + ElligibleBoat.PROPERTY_SAMPLE_ROW, contact.getSampleRow()); - if (log.isDebugEnabled()) { - String logMessage = "validation of contact " + contact + " return " + result.isSuccess(); - if ( ! result.isSuccess()) { - logMessage += ". reason is '" + result.getMessage() + "'"; + if (elligible == null) { + // Create new elligible boat not active in a global way + elligible = elligibleDAO.create( + ElligibleBoat.PROPERTY_BOAT, boat, + ElligibleBoat.PROPERTY_SAMPLE_ROW, row); + if (log.isTraceEnabled()) { + log.trace("Create elligibleBoat for : " + + boat.getImmatriculation() + " - " + + row.getCode()); } - log.debug(logMessage); } - - return result; + elligible.setCompanyActive(Boolean.TRUE); } /** @@ -644,279 +761,292 @@ * contacts which are corrects). The {@code calculateReal} identify that * real tides has to be calculated or not during sampleMonth update. * - * @param dao to use for create or update - * @param source which contains data to save - * @param destination receiver to save (will be null for a creation) + * @param transaction current transaction + * @param contact which contains data to save + * @param contactFound receiver to save (will be null for a creation) * @param calculateReal for sampleMonth update * @throws TopiaException for any Topia technical trouble * @throws NullSampleMonthException if sampleMonth not found to update tides * value * @see #updateSampleMonthTidesValue(TopiaContext, Contact, Contact, boolean) */ - protected void createOrUpdateContact(ContactDAO dao, - Contact source, - Contact destination, + protected void createOrUpdateContact(TopiaContext transaction, + Contact contactFound, + Contact contact, boolean calculateReal) - throws TopiaException, - NullSampleMonthException { - - updateSampleMonthTidesValue( - dao.getContext(), - destination, - source, - calculateReal - ); - + throws TopiaException, WaoBusinessException { + + + // FIXME bleny 2011-03-21 validation should be active +// ValidationResult contactValidationResult = executeValidateContact(transaction, contact); +// if ( ! contactValidationResult.isSuccess()) { +// throw new WaoBusinessException(contactValidationResult.getMessage()); +// } + + ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); + + updateSampleMonthTidesValue(dao.getContext(), contactFound, contact, calculateReal); + // Create the contact if not defined - if (destination == null) { + if (contactFound == null) { if (log.isDebugEnabled()) { log.debug("Create a new contact on " + - source.getTopiaCreateDate()); + contact.getTopiaCreateDate()); } - destination = dao.create( - Contact.PROPERTY_BOAT, source.getBoat(), - Contact.PROPERTY_SAMPLE_ROW, source.getSampleRow(), + contactFound = dao.create( + Contact.PROPERTY_BOAT, contact.getBoat(), + Contact.PROPERTY_SAMPLE_ROW, contact.getSampleRow(), // FIXME-FD20100415 : don't use the topiaCreateDate as a business field - TopiaEntity.TOPIA_CREATE_DATE, source.getTopiaCreateDate() + TopiaEntity.TOPIA_CREATE_DATE, contact.getTopiaCreateDate() ); if (log.isDebugEnabled()) { log.debug("TopiaId of the new contact : " + - destination.getTopiaId()); + contactFound.getTopiaId()); } - // Set the new topiaId in source contact - source.setTopiaId(destination.getTopiaId()); + // Set the new topiaId in contact contact + contact.setTopiaId(contactFound.getTopiaId()); } // Bind the contact in argument with the contact in session - //BinderProvider.getBinder(Contact.class).copy(source, destination); + //BinderProvider.getBinder(Contact.class).copy(contact, destination); WaoBinderHelper.getSimpleTopiaBinder(Contact.class). - copyExcluding(source, destination, + copyExcluding(contact, contactFound, Contact.PROPERTY_BOAT, Contact.PROPERTY_SAMPLE_ROW ); - destination.clearSecondaryObservers(); - destination.addAllSecondaryObservers(source.getSecondaryObservers()); + contactFound.clearSecondaryObservers(); + contactFound.addAllSecondaryObservers(contact.getSecondaryObservers()); // Update the change - dao.update(destination); + dao.update(contactFound); } @Override - public Contact executeSaveComment(TopiaContext transaction, - String contactId, - UserRole userRole, - String comment) - throws TopiaException { + public void executeSaveContact(TopiaContext transaction, ConnectedUser connectedUser, + Contact contact, boolean delete) + throws EmailException, TopiaException, WaoBusinessException { ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); + Contact contactFound = dao.findByTopiaId(contact.getTopiaId()); - Contact contactToUpdate = dao.findByTopiaId(contactId); + if (delete) { + // Need to decrement estimated value if contactFound has + // OBSERVATION_DONE state and may be real value (normally not allowed) + updateSampleMonthTidesValue(transaction, contactFound, null, true); - switch (userRole) { - case ADMIN: - contactToUpdate.setCommentAdmin(comment); break; - case COORDINATOR: - contactToUpdate.setCommentCoordinator(comment); - } + // Execute delete + dao.delete(contactFound); + } else { - dao.update(contactToUpdate); + notifyUsersForMammalsObservation(transaction, contactFound, contact); + createOrUpdateContact(transaction, contactFound, contact, true); + } transaction.commitTransaction(); - - return contactToUpdate; } @Override public InputStream executeExportContactCsv(TopiaContext transaction, ContactFilter filter) throws Exception { - CsvWriter writer = null; - try { - - File file = File.createTempFile("wao-contacts-", ".csv"); - file.deleteOnExit(); + boolean useNewMethod = true; + if (useNewMethod) { - if (log.isDebugEnabled()) { - log.debug("Export contacts into : " + file.getAbsolutePath()); - } + Map<String, Contact> contacts = executeGetContacts(transaction, filter); - FileOutputStream output = new FileOutputStream(file); - writer = new CsvWriter(output, ',', context.getCsvCharset()); + ExportModel<Contact> contactExportModel = new ContactImportExportModel(filter.getObsProgram()); + Export<Contact> export = new Export<Contact>(contactExportModel, contacts.values()); + return export.startExport(); + } else { - ExportHelper<ContactHeader> export = - new ExportHelper<ContactHeader>(writer, - CONTACT.getTotalHeaders()) { + CsvWriter writer = null; + try { - @Override - public void record(ContactHeader header, String value) { - record(header.forContactCsv(), value); - } + File file = File.createTempFile("wao-contacts-", ".csv"); + file.deleteOnExit(); - @Override - protected String getHeaderValue(int index) - throws IOException { - if (log.isDebugEnabled()) { - log.debug("record header : " + index + " = " + - WaoCsvHeader.getHeaderForContactCsv(index)); - } - return WaoCsvHeader.getHeaderForContactCsv(index); + if (log.isDebugEnabled()) { + log.debug("Export contacts into : " + file.getAbsolutePath()); } - }; - export.writeHeaders(); - - DateFormat dateFormat = CONTACT.DATE_FORMAT; + OutputStream output = new FileOutputStream(file); + writer = new CsvWriter(output, ',', context.getCsvCharset()); - // Get contacts from database - ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); -// TopiaQuery query = dao.createQuery("C"); -// query.addOrderDesc("C." + TopiaEntity.TOPIA_CREATE_DATE); -// -// // No page limit in this case -// query = filter.prepareQueryForContact(query).resetLimit(); + ExportHelper<ContactHeader> export = + new ExportHelper<ContactHeader>(writer, + CONTACT.getTotalHeaders()) { - WaoQueryBuilder builder = context.newQueryBuilder(); - builder.initializeForContact(); + @Override + public void record(ContactHeader header, String value) { + record(header.forContactCsv(), value); + } - filter.setOrderBy(TopiaEntity.TOPIA_CREATE_DATE + " desc"); + @Override + protected String getHeaderValue(int index) + throws IOException { + if (log.isDebugEnabled()) { + log.debug("record header : " + index + " = " + + WaoCsvHeader.getHeaderForContactCsv(index)); + } + return WaoCsvHeader.getHeaderForContactCsv(index); + } + }; - TopiaQuery query = builder.applyContactFilter(filter); + export.writeHeaders(); - // No page limit in this case - query.resetLimit(); + DateFormat dateFormat = CONTACT.DATE_FORMAT; - if (log.isDebugEnabled()) { - log.debug("Query : " + query); - } + // Get contacts from database + ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); + // TopiaQuery query = dao.createQuery("C"); + // query.addOrderDesc("C." + TopiaEntity.TOPIA_CREATE_DATE); + // + // // No page limit in this case + // query = filter.prepareQueryForContact(query).resetLimit(); - List<Contact> contacts = dao.findAllByQuery(query); + WaoQueryBuilder builder = context.newQueryBuilder(); + builder.initializeForContact(); - DateFormat timeFormat = CONTACT.TIME_FORMAT; + filter.setOrderBy(TopiaEntity.TOPIA_CREATE_DATE + " desc"); - for (Contact contact : contacts) { - export.newRecord(); + TopiaQuery query = builder.applyContactFilter(filter); - // Contact part - export.record(CONTACT.CONT_CODE, - timeFormat.format(contact.getTopiaCreateDate())); - export.record(CONTACT.CONT_CREATION, - dateFormat.format(contact.getTopiaCreateDate())); - export.record(CONTACT.CONT_ETAT, - contact.getContactState().name()); - if (contact.getObservationBeginDate() != null) { - export.record(CONTACT.CONT_DEBUT_MAREE, - CONTACT.CONT_DEBUT_MAREE.format(contact.getObservationBeginDate())); - } - if (contact.getObservationEndDate() != null) { - export.record(CONTACT.CONT_FIN_MAREE, - CONTACT.CONT_FIN_MAREE.format(contact.getObservationEndDate())); - } - export.record(CONTACT.CONT_NB_OBSERV, - String.valueOf(contact.getNbObservants())); - export.record(CONTACT.CONT_MAM_CAPT, - CONTACT.formatMammals(contact.getMammalsCapture())); - export.record(CONTACT.CONT_MAM_OBS, - CONTACT.formatMammals(contact.getMammalsObservation())); - export.record(CONTACT.CONT_COMMENT, - contact.getComment()); - if (contact.getDataInputDate() != null) { - export.record(CONTACT.CONT_ALLEGRO, - dateFormat.format(contact.getDataInputDate())); - } - export.record(CONTACT.CONT_SOCIETE_VALID, - CONTACT.formatValidation(contact.getValidationCompany())); - export.record(CONTACT.CONT_PROGRAM_VALID, - CONTACT.formatValidation(contact.getValidationProgram())); - export.record(CONTACT.CONT_DATA_RELIABILITY, - contact.getDataReliability().name()); + // No page limit in this case + query.resetLimit(); - if (contact.getSamplingStrategy() != null) { - export.record(CONTACT.CONT_SAMPLING_STRATEGY, - contact.getSamplingStrategy().name()); + if (log.isDebugEnabled()) { + log.debug("Query : " + query); } - if (contact.getCompleteSampling() != null) { - export.record(CONTACT.CONT_COMPLETE_SAMPLING, - CONTACT.formatBoolean(contact.getCompleteSampling())); - } + List<Contact> contacts = dao.findAllByQuery(query); - // Observer part - WaoUser mainObserver = contact.getMainObserver(); + DateFormat timeFormat = CONTACT.TIME_FORMAT; - StringBuilder observersLogin = new StringBuilder(); - observersLogin.append(mainObserver.getLogin()); - StringBuilder observersNames = new StringBuilder(); - observersNames.append(mainObserver.getFullName()); - if (contact.getSecondaryObservers() != null) { - for (WaoUser secondaryObserver : contact.getSecondaryObservers()) { - observersLogin.append(", "); - observersLogin.append(secondaryObserver.getLogin()); - observersNames.append(", "); - observersNames.append(secondaryObserver.getFullName()); + for (Contact contact : contacts) { + export.newRecord(); + + // Contact part + export.record(CONTACT.CONT_CODE, + timeFormat.format(contact.getTopiaCreateDate())); + export.record(CONTACT.CONT_CREATION, + dateFormat.format(contact.getTopiaCreateDate())); + export.record(CONTACT.CONT_ETAT, + contact.getContactState().name()); + if (contact.getObservationBeginDate() != null) { + export.record(CONTACT.CONT_DEBUT_MAREE, + CONTACT.CONT_DEBUT_MAREE.format(contact.getObservationBeginDate())); } - } + if (contact.getObservationEndDate() != null) { + export.record(CONTACT.CONT_FIN_MAREE, + CONTACT.CONT_FIN_MAREE.format(contact.getObservationEndDate())); + } + export.record(CONTACT.CONT_NB_OBSERV, + String.valueOf(contact.getNbObservants())); + export.record(CONTACT.CONT_MAM_CAPT, + CONTACT.formatMammals(contact.getMammalsCapture())); + export.record(CONTACT.CONT_MAM_OBS, + CONTACT.formatMammals(contact.getMammalsObservation())); + export.record(CONTACT.CONT_COMMENT, + contact.getComment()); + if (contact.getDataInputDate() != null) { + export.record(CONTACT.CONT_ALLEGRO, + dateFormat.format(contact.getDataInputDate())); + } + export.record(CONTACT.CONT_SOCIETE_VALID, + CONTACT.formatValidation(contact.getValidationCompany())); + export.record(CONTACT.CONT_PROGRAM_VALID, + CONTACT.formatValidation(contact.getValidationProgram())); + export.record(CONTACT.CONT_DATA_RELIABILITY, + contact.getDataReliability().name()); - export.record(CONTACT.OBSERV_ID, observersLogin.toString()); - // export.record(CONTACT.OBSERV_PRENOM, mainObserver.getFirstName()); - export.record(CONTACT.OBSERV_NOM, observersNames.toString()); + if (contact.getSamplingStrategy() != null) { + export.record(CONTACT.CONT_SAMPLING_STRATEGY, + contact.getSamplingStrategy().name()); + } - Company company = mainObserver.getCompany(); - export.record(SAMPLING.SOCIETE_NOM, company.getName()); + if (contact.getCompleteSampling() != null) { + export.record(CONTACT.CONT_COMPLETE_SAMPLING, + CONTACT.formatBoolean(contact.getCompleteSampling())); + } - // SampleRow part - SampleRow row = contact.getSampleRow(); - export.record(SAMPLING.PLAN_CODE, row.getCode()); - export.record(SAMPLING.PROGRAMME_CODE, row.getProgramName()); - export.record(SAMPLING.PROGRAMME_DEBUT, - dateFormat.format(row.getPeriodBegin())); - export.record(SAMPLING.PROGRAMME_FIN, - dateFormat.format(row.getPeriodEnd())); - export.record(SAMPLING.PECHE_AUTRE, - row.getFishingZonesInfos()); + // Observer part + WaoUser mainObserver = contact.getMainObserver(); - // FishingZone part - String divisions = ""; - String separator = " - "; - for (FishingZone zone : row.getFishingZone()) { - divisions += separator + zone.getDistrictCode(); - } - export.record(FISHING_ZONE.PECHE_DIVISION, - divisions.substring(separator.length())); - export.record(FISHING_ZONE.PECHE_FACADE, row.getFacade()); - export.record(FISHING_ZONE.PECHE_ZONE, row.getSectors()); + StringBuilder observersLogin = new StringBuilder(); + observersLogin.append(mainObserver.getLogin()); + StringBuilder observersNames = new StringBuilder(); + observersNames.append(mainObserver.getFullName()); + if (contact.getSecondaryObservers() != null) { + for (WaoUser secondaryObserver : contact.getSecondaryObservers()) { + observersLogin.append(", "); + observersLogin.append(secondaryObserver.getLogin()); + observersNames.append(", "); + observersNames.append(secondaryObserver.getFullName()); + } + } - // Profession part - Profession profession = row.getProfession(); + export.record(CONTACT.OBSERV_ID, observersLogin.toString()); + // export.record(CONTACT.OBSERV_PRENOM, mainObserver.getFirstName()); + export.record(CONTACT.OBSERV_NOM, observersNames.toString()); - // export.record(SAMPLING.METIER_CODE_DCF5, profession.getCodeDCF5()); - export.record(SAMPLING.METIER_CODE_DCF5, StringUtil.join(row.getDCF5Code(), " et ", true)); - - export.record(SAMPLING.METIER_MAILLAGE, - profession.getMeshSize()); - export.record(SAMPLING.METIER_TAILLE, profession.getSize()); - export.record(SAMPLING.METIER_AUTRE, profession.getOther()); - export.record(SAMPLING.METIER_LIBELLE, profession.getLibelle()); - export.record(SAMPLING.METIER_ESPECES, profession.getSpecies()); + Company company = mainObserver.getCompany(); + export.record(SAMPLING.SOCIETE_NOM, company.getName()); - // Boat part - Boat boat = contact.getBoat(); - export.record(BOAT.NAVS_COD, - String.valueOf(boat.getImmatriculation())); - export.record(BOAT.CARN_NOM, boat.getName()); - export.record(BOAT.QUARTIER_IMMA, boat.getDistrictCode()); + // SampleRow part + SampleRow row = contact.getSampleRow(); + export.record(SAMPLING.PLAN_CODE, row.getCode()); + export.record(SAMPLING.PROGRAMME_CODE, row.getProgramName()); + export.record(SAMPLING.PROGRAMME_DEBUT, + dateFormat.format(row.getPeriodBegin())); + export.record(SAMPLING.PROGRAMME_FIN, + dateFormat.format(row.getPeriodEnd())); + export.record(SAMPLING.PECHE_AUTRE, + row.getFishingZonesInfos()); - export.writeRecord(); - } - return new FileInputStream(file); + // FishingZone part + String divisions = ""; + String separator = " - "; + for (FishingZone zone : row.getFishingZone()) { + divisions += separator + zone.getDistrictCode(); + } + export.record(FISHING_ZONE.PECHE_DIVISION, + divisions.substring(separator.length())); + export.record(FISHING_ZONE.PECHE_FACADE, row.getFacade()); + export.record(FISHING_ZONE.PECHE_ZONE, row.getSectors()); - } catch (Exception eee) { - throw eee; - } finally { - if (writer != null) { - writer.close(); + // Profession part + Profession profession = row.getProfession(); + + // export.record(SAMPLING.METIER_CODE_DCF5, profession.getCodeDCF5()); + export.record(SAMPLING.METIER_CODE_DCF5, StringUtil.join(row.getDCF5Code(), " et ", true)); + + export.record(SAMPLING.METIER_MAILLAGE, + profession.getMeshSize()); + export.record(SAMPLING.METIER_TAILLE, profession.getSize()); + export.record(SAMPLING.METIER_AUTRE, profession.getOther()); + export.record(SAMPLING.METIER_LIBELLE, profession.getLibelle()); + export.record(SAMPLING.METIER_ESPECES, profession.getSpecies()); + + // Boat part + Boat boat = contact.getBoat(); + export.record(BOAT.NAVS_COD, + String.valueOf(boat.getImmatriculation())); + export.record(BOAT.CARN_NOM, boat.getName()); + export.record(BOAT.QUARTIER_IMMA, boat.getDistrictCode()); + + export.writeRecord(); + } + return new FileInputStream(file); + + } catch (Exception eee) { + throw eee; + } finally { + if (writer != null) { + writer.close(); + } } } } @@ -931,118 +1061,167 @@ ParseException { ImportResults result = new ImportResultsImpl(); - int currRow = 1; - CsvReader reader = new CsvReader(input, context.getCsvCharset()); - try { - reader.readHeaders(); + boolean useNewMethod = true; + if (useNewMethod) { - ImportHelper.checkKeyHeader(reader, CONTACT.CONT_CREATION); + // Some DAO + WaoUserDAO waoUserDAO = WaoDAOHelper.getWaoUserDAO(transaction); + TerrestrialLocationDAO terrestrialLocationDAO = WaoDAOHelper.getTerrestrialLocationDAO(transaction); + SampleRowDAO sampleRowDAO = WaoDAOHelper.getSampleRowDAO(transaction); + BoatDAO boatDAO = WaoDAOHelper.getBoatDAO(transaction); - ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); + // prepare selection of sample-rows, those are restrained + // by ObsProgram and by company + Map<String, Object> sampleRowProperties = new HashMap<String, Object>(); + sampleRowProperties.put(SampleRow.PROPERTY_OBS_PROGRAM_ORDINAL, user.getProfile().getObsProgramOrdinal()); + if ( ! user.isAdmin()) { + sampleRowProperties.put(SampleRow.PROPERTY_COMPANY, user.getCompany()); + } - long tic; - tic = System.currentTimeMillis(); - DateFormat dateFormat = new SimpleDateFormat("MM/yyyy"); - while(reader.readRecord()) { - try { - currRow++; + // filling collection needed by model + List<SampleRow> sampleRows = sampleRowDAO.findAllByProperties(sampleRowProperties); + List<WaoUser> waoUsers = waoUserDAO.findAll(); + List<Boat> boats = boatDAO.findAll(); + List<TerrestrialLocation> terrestrialLocations = terrestrialLocationDAO.findAll(); - boolean updateValidation = user.isAdmin() && - user.getLogin().equals("admin"); + // model creation, and import starting + ImportModel<Contact> contactImportModel = new ContactImportExportModel(user.getProfile().getObsProgram(), + waoUsers, terrestrialLocations, sampleRows, boats); + Import<Contact> contactImport = new Import<Contact>(contactImportModel, input); - // Load ContactInput using CsvReader - ContactInput contactCsv = new ContactInput(); - contactCsv.initialize(transaction, user, currRow); - loadContactCsv(reader, contactCsv, updateValidation); + try { + Iterator<Contact> contactIterator = contactImport.startImport(); - if (log.isDebugEnabled()) { - log.debug("Ligne " + currRow + " : " + - "Create date : " + - contactCsv.getTopiaCreateDate()); - } + while (contactIterator.hasNext()) { + Contact contact = contactIterator.next(); - // Retrieve the existing contact - String companyProperty = - TopiaQuery.getProperty(Contact.PROPERTY_MAIN_OBSERVER, - WaoUser.PROPERTY_COMPANY); + executeSaveContact(transaction, user, contact, false); - Contact contact = dao.findByProperties( - TopiaEntity.TOPIA_CREATE_DATE, - contactCsv.getTopiaCreateDate(), - companyProperty, contactCsv.getCompany(), - Contact.PROPERTY_BOAT, contactCsv.getBoat(), - Contact.PROPERTY_SAMPLE_ROW, contactCsv.getSampleRow()); + result.incNbImported(); + } + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + contactImport.stopImport(); + } - // Seems to have a problem with companyProperty ?!? using - // DAOLegacy (criteria) -// TopiaQuery query = dao.createQuery(). -// addEquals(TopiaEntity.TOPIA_CREATE_DATE, -// contactCsv.getTopiaCreateDate()). -// addEquals(companyProperty, contactCsv.getCompany()). -// addEquals(Contact.PROPERTY_BOAT, contactCsv.getBoat()). -// addEquals(Contact.SAMPLE_ROW, -// contactCsv.getSampleRow()); -// Contact contact = dao.findByQuery(query); + transaction.commitTransaction(); - // Check validation for existing Contact - if (!updateValidation && contact != null && - contact.getValidationCompany() != null) { - throw new ImportRefusedException("Le contact est" + - " déjà validé dans l'application" + - " et ne peut pas être importé", currRow, - Contact.PROPERTY_VALIDATION_COMPANY); - } + } else { + int currRow = 1; - // Create elligibleBoat if needed before saving the contact - updateElligibleBoatForContact(transaction, contactCsv); + CsvReader reader = new CsvReader(input, context.getCsvCharset()); + try { + reader.readHeaders(); + ImportHelper.checkKeyHeader(reader, CONTACT.CONT_CREATION); + + ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); + + long tic; + tic = System.currentTimeMillis(); + DateFormat dateFormat = new SimpleDateFormat("MM/yyyy"); + while(reader.readRecord()) { try { - // Execute createOrUpdateContact - // Will calculate data for SampleMonth and maybe - // throw a NullSampleMonthException if there is - // an error during the calcul of sampleMonthTidesValue - createOrUpdateContact(dao, contactCsv, contact, - updateValidation); + currRow++; - } catch (NullSampleMonthException eee) { - log.debug("exception", eee); - log.debug("contact : " + contact); - if (contact != null) { - log.debug("tideBeginDate : " + contact.getObservationBeginDate()); + boolean updateValidation = user.isAdmin() && + user.getLogin().equals("admin"); + + // Load ContactInput using CsvReader + ContactInput contactCsv = new ContactInput(); + contactCsv.initialize(transaction, user, currRow); + loadContactCsv(reader, contactCsv, updateValidation); + + if (log.isDebugEnabled()) { + log.debug("Ligne " + currRow + " : " + + "Create date : " + + contactCsv.getTopiaCreateDate()); } - // The row will be refused in this case - throw new ImportRefusedException("Impossible de " + - "mettre à jour le nombre de marée réels, " + - "vérifiez le mois de " + - dateFormat.format(contact.getObservationBeginDate()) + - " pour la ligne du plan " + - contactCsv.getSampleRow().getCode(), currRow, - Contact.PROPERTY_OBSERVATION_BEGIN_DATE, eee); - } - result.incNbImported(); + // Retrieve the existing contact + String companyProperty = + TopiaQuery.getProperty(Contact.PROPERTY_MAIN_OBSERVER, + WaoUser.PROPERTY_COMPANY); - if (result.getNbRowsImported() % 1000 == 0) { - transaction.commitTransaction(); - tic = ImportHelper.logTimeAndMemory(log, tic, - "contacts ligne " + currRow); - } + Contact contact = dao.findByProperties( + TopiaEntity.TOPIA_CREATE_DATE, + contactCsv.getTopiaCreateDate(), + companyProperty, contactCsv.getCompany(), + Contact.PROPERTY_BOAT, contactCsv.getBoat(), + Contact.PROPERTY_SAMPLE_ROW, contactCsv.getSampleRow()); - } catch(ImportRefusedException eee) { - if (log.isWarnEnabled()) { - log.warn("Error during contact import row : " + - eee.getRowNumber(), eee); + // Seems to have a problem with companyProperty ?!? using + // DAOLegacy (criteria) + // TopiaQuery query = dao.createQuery(). + // addEquals(TopiaEntity.TOPIA_CREATE_DATE, + // contactCsv.getTopiaCreateDate()). + // addEquals(companyProperty, contactCsv.getCompany()). + // addEquals(Contact.PROPERTY_BOAT, contactCsv.getBoat()). + // addEquals(Contact.SAMPLE_ROW, + // contactCsv.getSampleRow()); + // Contact contact = dao.findByQuery(query); + + // Check validation for existing Contact + if (!updateValidation && contact != null && + contact.getValidationCompany() != null) { + throw new ImportRefusedException("Le contact est" + + " déjà validé dans l'application" + + " et ne peut pas être importé", currRow, + Contact.PROPERTY_VALIDATION_COMPANY); + } + + // Create elligibleBoat if needed before saving the contact + updateElligibleBoatForContact(transaction, contactCsv); + + try { + // Execute createOrUpdateContact + // Will calculate data for SampleMonth and maybe + // throw a NullSampleMonthException if there is + // an error during the calcul of sampleMonthTidesValue + createOrUpdateContact(transaction, contact, contactCsv, + updateValidation); + + } catch (NullSampleMonthException eee) { + log.debug("exception", eee); + log.debug("contact : " + contact); + if (contact != null) { + log.debug("tideBeginDate : " + contact.getObservationBeginDate()); + } + // The row will be refused in this case + throw new ImportRefusedException("Impossible de " + + "mettre à jour le nombre de marée réels, " + + "vérifiez le mois de " + + dateFormat.format(contact.getObservationBeginDate()) + + " pour la ligne du plan " + + contactCsv.getSampleRow().getCode(), currRow, + Contact.PROPERTY_OBSERVATION_BEGIN_DATE, eee); + } + + result.incNbImported(); + + if (result.getNbRowsImported() % 1000 == 0) { + transaction.commitTransaction(); + tic = ImportHelper.logTimeAndMemory(log, tic, + "contacts ligne " + currRow); + } + + } catch(ImportRefusedException eee) { + if (log.isWarnEnabled()) { + log.warn("Error during contact import row : " + + eee.getRowNumber(), eee); + } + result.addError(eee.getRowNumber(), eee.getMessage()); + result.incNbRefused(); } - result.addError(eee.getRowNumber(), eee.getMessage()); - result.incNbRefused(); } + + // Commit for last rows imported + transaction.commitTransaction(); + } finally { + reader.close(); } - - // Commit for last rows imported - transaction.commitTransaction(); - } finally { - reader.close(); } return result; } @@ -1135,175 +1314,6 @@ } - /** - * Update the SampleMonth data for tidesValue (estimated and real) from - * {@code contact} compared to its old state {@code oldContact}. The - * estimated is update when contact state {@link ContactState#OBSERVATION_DONE} - * is changed. The real is update when contact validationCompany is changed. - * The {@code calculateReal} flag determines if the real tides has to be - * calculated or not. Three cases : - * <ul> - * <li>CREATE : {@code oldContact} = null and {@code contact} is defined</li> - * <li>UPDATE : both {@code oldContact} and {@code contact} are defined</li> - * <li>DELETE : {@code oldContact} is defined and {@code contact} = null</li> - * </ul> - * <p> - * <strong>Estimated Tides value</strong> = nbContacts with OBSERVATION_DONE - * state and not refused by program (validationProgram != FALSE) - * </p> - * <p> - * <strong>Real Tides value</strong> = nbContacts accepted by company - * (validationCompany = TRUE) and not refused by program - * (validationProgram != FALSE) - * </p> - * - * @param transaction used to update the SampleMonth - * @param oldContact old state of the contact - * @param contact changed can be null for delete case - * @param calculateReal to calculate real tides value - * @throws TopiaException for any Topia technical trouble - * @throws NullSampleMonthException if SampleMonth can't be found - */ - protected void updateSampleMonthTidesValue( - TopiaContext transaction, Contact oldContact, - Contact contact, boolean calculateReal) - throws TopiaException, NullSampleMonthException { - - if (oldContact == null && contact == null) { - throw new IllegalArgumentException("Both contact and oldContact" + - " can't be null to update sampleMonth tides value"); - } - - // Instantiate contact status which provide status on oldContact and - // contact changes - ContactStatus status = new ContactStatus(oldContact, contact); - - if (log.isDebugEnabled()) { - log.debug(status.toString()); - } - - // Month of TideBeginDate has changed, must decrement values on - // old sampleMonth - boolean tideBeginDateChanged = false; - if (oldContact != null && contact != null && - status.isTideBeginDateMonthChanged()) { - - tideBeginDateChanged = status.isTideBeginDateMonthChanged(); - - // Retrieve oldMonth from status - try { - SampleMonth oldMonth = status.getOldSampleMonth(transaction); - - // Apply changes on oldMonth - if (status.isOldContactValidate()) { - // decrement real tides - oldMonth.addRealTideTime(-1); - } - // Decrement estimated only if old state is OBSERVATION_DONE - // and old validationProgram is NOT FALSE - // the estimated value has already been decremented during - // refused - if (status.isOldContactDone() && BooleanUtils.isNotFalse( - oldContact.getValidationProgram())) { - // decrement estimated tides - oldMonth.addEstimatedTideTime(-1); - } - - // Catch the null exception, only a warning if the oldSampleMonth is - // not found - } catch (NullSampleMonthException eee) { - if (log.isWarnEnabled()) { - log.warn("Error on retrieve old sampleMonth", eee); - } - } - } - - ContactState currentState = contact != null ? - contact.getContactState() : oldContact.getContactState(); - - // Validation of contact has changed in status, modify realTides - // Only calculate real for a currentState equals to OBSERVATION_DONE - if (calculateReal && ContactState.OBSERVATION_DONE.equals(currentState) && - (status.isContactValidateChanged() || tideBeginDateChanged)) { - - SampleMonth sampleMonth = status.getSampleMonth(transaction); - - if (status.isNewContactValidate()) { - // increment real tides - sampleMonth.addRealTideTime(1); - // validationProgram becomes not FALSE, estimatedTides must be - // incremented - if (status.isNoMoreRefused()) { - sampleMonth.addEstimatedTideTime(1); - } - // never decrement if tideBeginDate has changed - } else if (status.isOldContactValidate() && !tideBeginDateChanged) { - // decrement real tides - sampleMonth.addRealTideTime(-1); - // validationProgram becomes FALSE, estimatedTides must be - // decremented - if (status.isRefused()) { - sampleMonth.addEstimatedTideTime(-1); - } - } - } - - // ContactState of contact has changed in status, modify estimatedTides - if (status.isContactDoneChanged() || tideBeginDateChanged) { - - SampleMonth sampleMonth = status.getSampleMonth(transaction); - - if (status.isNewContactDone()) { - // increment estimated tides - sampleMonth.addEstimatedTideTime(1); - // never decrement if tideBeginDate has changed - } else if (status.isOldContactDone() && !tideBeginDateChanged) { - // decrement estimated tides - sampleMonth.addEstimatedTideTime(-1); - } - } - } - - /** - * Update the elligible boat depends on contact creation. The - * {@code contact} reference can only be created for a sampleRow and a - * boat if both are linked with an elligibleBoat. So this method is - * used to create the link if needed during contacts import. This - * elligibleBoat is needed for the contact owned by a company, so - * the companyActive property of ElligibleBoat will be set to TRUE. No - * admin has decided to explicitly create this link. - * - * @param transaction used to update the ElligibleBoat - * @param contact which contains sampleRow and boat to link - * @throws TopiaException for any Topia technical trouble - */ - protected void updateElligibleBoatForContact(TopiaContext transaction, - Contact contact) throws TopiaException { - - Boat boat = contact.getBoat(); - SampleRow row = contact.getSampleRow(); - - ElligibleBoatDAO elligibleDAO = - WaoDAOHelper.getElligibleBoatDAO(transaction); - ElligibleBoat elligible = - elligibleDAO.findByProperties( - ElligibleBoat.PROPERTY_BOAT, contact.getBoat(), - ElligibleBoat.PROPERTY_SAMPLE_ROW, contact.getSampleRow()); - - if (elligible == null) { - // Create new elligible boat not active in a global way - elligible = elligibleDAO.create( - ElligibleBoat.PROPERTY_BOAT, boat, - ElligibleBoat.PROPERTY_SAMPLE_ROW, row); - if (log.isTraceEnabled()) { - log.trace("Create elligibleBoat for : " + - boat.getImmatriculation() + " - " + - row.getCode()); - } - } - elligible.setCompanyActive(Boolean.TRUE); - } - @Override public boolean executeSendContactDoneEmail(TopiaContext transaction, Contact contact) throws WaoBusinessException, TopiaException { Modified: trunk/wao-business/src/main/xmi/wao.zargo =================================================================== (Binary files differ) Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/AbstractServiceTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/AbstractServiceTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/AbstractServiceTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -567,6 +567,8 @@ ServiceContact serviceContact = manager.getServiceContact(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); + // Contacts for company TARTANPION Contact contact1 = new ContactImpl(); contact1.setBoat(boat); @@ -575,7 +577,7 @@ contact1.setContactState(ContactState.OBSERVATION_DONE); Date begin = DateUtil.createDate(3, 3, 2010); contact1.setObservationBeginDate(begin); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); Contact contact2 = new ContactImpl(); contact2.setBoat(boat); @@ -584,7 +586,7 @@ contact2.setContactState(ContactState.OBSERVATION_DONE); begin = DateUtil.createDate(3, 10, 2010); contact2.setObservationBeginDate(begin); - serviceContact.saveContact(contact2, false); + serviceContact.saveContact(connectedUser, contact2, false); Contact contact3 = new ContactImpl(); contact3.setBoat(boat); @@ -593,7 +595,7 @@ contact3.setContactState(ContactState.CONTACT_REFUSED); begin = DateUtil.createDate(3, 5, 2010); contact3.setTopiaCreateDate(begin); - serviceContact.saveContact(contact3, false); + serviceContact.saveContact(connectedUser, contact3, false); // Contacts for company BIS Contact contact4 = new ContactImpl(); @@ -603,7 +605,7 @@ contact4.setContactState(ContactState.OBSERVATION_EXPECTED); begin = DateUtil.createDate(3, 3, 2010); contact4.setTopiaCreateDate(begin); - serviceContact.saveContact(contact4, false); + serviceContact.saveContact(connectedUser, contact4, false); Contact contact5 = new ContactImpl(); contact5.setBoat(boat2); @@ -612,7 +614,7 @@ contact5.setContactState(ContactState.OBSERVATION_CANCELLED); begin = DateUtil.createDate(3, 5, 2010); contact5.setTopiaCreateDate(begin); - serviceContact.saveContact(contact5, false); + serviceContact.saveContact(connectedUser, contact5, false); // Contact refused by program, will not be in result Contact contact6 = new ContactImpl(); @@ -623,7 +625,7 @@ begin = DateUtil.createDate(3, 3, 2010); contact6.setTopiaCreateDate(begin); contact6.setValidationProgram(Boolean.FALSE); - serviceContact.saveContact(contact6, false); + serviceContact.saveContact(connectedUser, contact6, false); } public ConnectedUser getConnectedUser(WaoUser user, UserRole userRole, ObsProgram obsProgram) { Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/entity/BoatImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/entity/BoatImplTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/entity/BoatImplTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -27,7 +27,9 @@ import fr.ifremer.wao.AbstractServiceTest; import fr.ifremer.wao.TestManager; import fr.ifremer.wao.WaoDAOHelper; +import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.ContactState; +import fr.ifremer.wao.bean.DataReliability; import fr.ifremer.wao.bean.ObsProgram; import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.service.ServiceBoat; @@ -103,6 +105,7 @@ user.setCompany(company); serviceUser.createUpdateUser(user, true); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); InputStream input = getClass().getResourceAsStream("/import/navires.csv"); ServiceBoat serviceBoat = manager.getServiceBoat(); serviceBoat.importBoatCsv(input); @@ -135,9 +138,9 @@ serviceSampling.createUpdateSampleRow(row, boats, new SampleRowLogImpl()); ServiceContact serviceContact = manager.getServiceContact(); - Contact contact1 = serviceContact.getNewContact(user, row, boat); + Contact contact1 = serviceContact.getNewContact(connectedUser, row, boat); contact1.setContactState(ContactState.CONTACT_START); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); /** EXEC METHOD **/ boolean result = boat.canCreateContact(ObsProgram.OBSMER, company); @@ -145,8 +148,10 @@ Assert.assertFalse(result); contact1.setContactState(ContactState.CONTACT_DEFINITELY_REFUSED); + contact1.setComment("why contact was definitely refused"); + contact1.setDataReliability(DataReliability.RELIABLE); contact1.setValidationProgram(Boolean.TRUE); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); result = boat.canCreateContact(ObsProgram.OBSMER, company); // contact have a definitive refused for this boat @@ -154,21 +159,21 @@ contact1.setContactState(ContactState.OBSERVATION_DONE); contact1.setObservationBeginDate(DateUtil.createDate(3, 3, 2010)); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); result = boat.canCreateContact(ObsProgram.OBSMER, company); // contact is finished Assert.assertTrue(result); contact1.setContactState(ContactState.OBSERVATION_CANCELLED); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); result = boat.canCreateContact(ObsProgram.OBSMER, company); // contact is finished Assert.assertTrue(result); contact1.setContactState(ContactState.CONTACT_REFUSED); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); result = boat.canCreateContact(ObsProgram.OBSMER, company); // contact is finished @@ -233,14 +238,17 @@ transaction.closeContext(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); ServiceContact serviceContact = manager.getServiceContact(); // First contact : OK - Contact contact1 = serviceContact.getNewContact(user, row, boat); + Contact contact1 = serviceContact.getNewContact(connectedUser, row, boat); contact1.setContactState(ContactState.OBSERVATION_DONE); Date begin = DateUtil.createDate(3, 5, 2010); contact1.setObservationBeginDate(begin); + Date end = DateUtil.createDate(4, 5, 2010); + contact1.setObservationEndDate(end); contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); /** EXEC METHOD **/ @@ -248,36 +256,37 @@ int result = boat.getNbBoarding(fromDate); Assert.assertEquals(1, result); - Contact contact2 = serviceContact.getNewContact(user, row, boat); + Contact contact2 = serviceContact.getNewContact(connectedUser, row, boat); // Second contact with ValidationProgram = FALSE contact2.setContactState(ContactState.OBSERVATION_DONE); begin = DateUtil.createDate(3, 8, 2010); contact2.setObservationBeginDate(begin); contact2.setValidationCompany(Boolean.TRUE); contact2.setValidationProgram(Boolean.FALSE); - serviceContact.saveContact(contact2, false); + serviceContact.saveContact(connectedUser, contact2, false); result = boat.getNbBoarding(fromDate); Assert.assertEquals(1, result); - Contact contact3 = serviceContact.getNewContact(user, row, boat); + Contact contact3 = serviceContact.getNewContact(connectedUser, row, boat); // Third contact with tideBeginDate < fromDate contact3.setContactState(ContactState.OBSERVATION_DONE); begin = DateUtil.createDate(3, 3, 2010); contact3.setObservationBeginDate(begin); contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); + serviceContact.saveContact(connectedUser, contact3, false); result = boat.getNbBoarding(fromDate); Assert.assertEquals(1, result); - Contact contact4 = serviceContact.getNewContact(user2, row2, boat); + connectedUser = getConnectedUser(user2, UserRole.ADMIN, ObsProgram.OBSMER); + Contact contact4 = serviceContact.getNewContact(connectedUser, row2, boat); // Fourth contact : OK with an other company contact4.setContactState(ContactState.OBSERVATION_DONE); begin = DateUtil.createDate(3, 5, 2010); contact4.setObservationBeginDate(begin); contact4.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact4, false); + serviceContact.saveContact(connectedUser, contact4, false); result = boat.getNbBoarding(fromDate); Assert.assertEquals(2, result); Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/io/csv2/ExportTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/io/csv2/ExportTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/io/csv2/ExportTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -1,6 +1,7 @@ package fr.ifremer.wao.io.csv2; import fr.ifremer.wao.bean.ObsProgram; +import fr.ifremer.wao.entity.Contact; import fr.ifremer.wao.entity.SampleRow; import fr.ifremer.wao.entity.SampleRowImpl; import fr.ifremer.wao.entity.TerrestrialDivision; Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceBoatImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceBoatImplTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceBoatImplTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -299,10 +299,11 @@ row.getProfession(); transaction.closeContext(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); ServiceContact serviceContact = manager.getServiceContact(); - Contact contact1 = serviceContact.getNewContact(user, row, boat); + Contact contact1 = serviceContact.getNewContact(connectedUser, row, boat); contact1.setContactState(ContactState.CONTACT_START); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); CompanyBoatInfos companyBoatInfos = service.getCompanyBoatInfos(ObsProgram.OBSMER, 174592, company); Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactImplTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactImplTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -88,21 +88,6 @@ Assert.assertEquals(0, results.size()); } - @Test(expected = NullPointerException.class) - public void failOnSavingContactWithNullSampleRow() throws Throwable { - - Contact contact = new ContactImpl(); - WaoUser observer = createDefaultObserver(); - contact.setMainObserver(observer); - - try { - service.saveContact(contact, false); - Assert.fail(); - } catch (WaoException eee) { - throw eee.getCause(); - } - } - @Test public void testSaveContactWithMultipleObservers() throws TopiaException { Contact contact = createDefaultContact(); @@ -111,13 +96,13 @@ contact.addSecondaryObservers(createUser("toto", UserRole.OBSERVER, company)); contact.addSecondaryObservers(createUser("titi", UserRole.OBSERVER, company)); - service.saveContact(contact, false); + service.saveContact(null, contact, false); Contact savedContact = service.getContact(contact.getTopiaId()); Assert.assertEquals(2, savedContact.getSecondaryObservers().size()); contact.clearSecondaryObservers(); - service.saveContact(contact, false); + service.saveContact(null, contact, false); savedContact = service.getContact(contact.getTopiaId()); Assert.assertEquals(0, savedContact.getSecondaryObservers().size()); } Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceContactInternalTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -22,13 +22,16 @@ package fr.ifremer.wao.service; import com.csvreader.CsvReader; +import fr.ifremer.wao.AbstractServiceTest; import fr.ifremer.wao.TestManager; import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.ContactState; import fr.ifremer.wao.bean.ContactStatus.NullSampleMonthException; +import fr.ifremer.wao.bean.ObsProgram; import fr.ifremer.wao.bean.SamplingStrategy; +import fr.ifremer.wao.bean.UserRole; import fr.ifremer.wao.entity.Boat; import fr.ifremer.wao.entity.BoatDAO; import fr.ifremer.wao.entity.Company; @@ -39,6 +42,7 @@ import fr.ifremer.wao.entity.SampleMonthDAO; import fr.ifremer.wao.entity.SampleRow; import fr.ifremer.wao.entity.SampleRowDAO; +import fr.ifremer.wao.entity.UserProfileImpl; import fr.ifremer.wao.entity.WaoUser; import fr.ifremer.wao.entity.WaoUserDAO; import fr.ifremer.wao.io.ContactInput; @@ -47,6 +51,7 @@ import fr.ifremer.wao.io.csv.WaoCsvHeader.BOAT; import fr.ifremer.wao.io.csv.WaoCsvHeader.CONTACT; import fr.ifremer.wao.io.csv.WaoCsvHeader.SAMPLING; +import org.apache.commons.collections.CollectionUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; @@ -84,7 +89,7 @@ * Mise a jour: $Date$ * par : $Author$ */ -public class ServiceContactInternalTest { +public class ServiceContactInternalTest extends AbstractServiceTest { private static TestManager manager; @@ -185,53 +190,6 @@ } @Test - public void testGetExistingSampleMonthForContact() - throws TopiaException, NullSampleMonthException { - log.info("testGetExistingSampleMonthForContact"); - -// /** PREPARE DATA **/ -// prepareData(false, false); -// -// /** EXEC METHOD **/ -// log.info("test 1 : SampleMonth exists for contact"); -// TopiaContext transaction = manager.getContext().beginTransaction(); -// try { -// SampleMonthDAO monthDAO = -// WaoDAOHelper.getSampleMonthDAO(transaction); -// -// // Contact is valid for the sampleMonth -// -// SampleMonth result = -// service.getExistingSampleMonthForContact(monthDAO, -// contact.getSampleRow(), contact.getObservationBeginDate()); -// -// assertEquals(sampleMonth, result); -// -// } finally { -// transaction.closeContext(); -// } -// -// log.info("test 2 : contact tideBeginDate doesn't match with any" + -// " SampleMonth"); -// transaction = manager.getContext().beginTransaction(); -// try { -// SampleMonthDAO monthDAO = -// WaoDAOHelper.getSampleMonthDAO(transaction); -// -// Date contactDate = DateUtil.createDate(18, 10, 2010); -// when(contact.getObservationBeginDate()).thenReturn(contactDate); -// -// service.getExistingSampleMonthForContact(monthDAO, -// contact.getSampleRow(), contact.getObservationBeginDate()); -// } catch (Exception eee) { -// log.error("Error : " + eee.getMessage()); -// assertEquals(NullSampleMonthException.class, eee.getClass()); -// } finally { -// transaction.closeContext(); -// } - } - - @Test public void testUpdateSampleMonthTidesValue() throws TopiaException, NullSampleMonthException { log.info("testUpdateSampleMonthTidesValue"); @@ -668,7 +626,7 @@ @Test public void testCreateOrUpdateContact() - throws TopiaException, NullSampleMonthException { + throws TopiaException, WaoBusinessException { log.info("testCreateOrUpdateContact"); /** PREPARE DATA **/ @@ -681,8 +639,10 @@ // dao.delete(contact); // } + ConnectedUser connectedUser = getConnectedUser(observer, UserRole.OBSERVER, ObsProgram.OBSMER); + // Don't use a mock in this case - Contact newContact = service.getNewContact(observer, sampleRow, boat); + Contact newContact = service.getNewContact(connectedUser, sampleRow, boat); newContact.setTopiaCreateDate(DateUtil.createDate(2, 3, 2010)); /** EXEC METHOD **/ @@ -693,9 +653,7 @@ try { transaction = manager.getContext().beginTransaction(); - ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); - - service.createOrUpdateContact(dao, newContact, null, false); + service.createOrUpdateContact(transaction, null, newContact, false); transaction.commitTransaction(); newTopiaId = newContact.getTopiaId(); @@ -740,7 +698,7 @@ ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); Contact oldContact = dao.findByTopiaId(newTopiaId); - service.createOrUpdateContact(dao, newContact, oldContact, false); + service.createOrUpdateContact(transaction, oldContact, newContact, false); transaction.commitTransaction(); } finally { if (transaction != null) { @@ -785,8 +743,8 @@ prepareData(true, true); when(creator.getCompany()).thenReturn(company); - when(creator.isAdmin()).thenReturn(false); when(creator.getLogin()).thenReturn(observer.getLogin()); + when(creator.getProfile()).thenReturn(new UserProfileImpl(ObsProgram.OBSMER, UserRole.ADMIN, true)); /** EXEC METHOD **/ log.info("test 1 : Import new contact with observer creator"); @@ -821,8 +779,8 @@ log.info("test 2 : Import new contact with super admin creator"); when(creator.getCompany()).thenReturn(company); - when(creator.isAdmin()).thenReturn(true); when(creator.getLogin()).thenReturn("admin"); + when(creator.getProfile()).thenReturn(new UserProfileImpl(ObsProgram.OBSMER, UserRole.ADMIN, true)); input = getClass().getResourceAsStream("/import/contacts.csv"); try { @@ -833,22 +791,5 @@ } finally { input.close(); } - - log.info("test 2 : Check update validations of the contact"); - try { - transaction = manager.getContext().beginTransaction(); - - ContactDAO dao = WaoDAOHelper.getContactDAO(transaction); - - List<Contact> contactsFound = dao.findAll(); - assertEquals(1, contactsFound.size()); - Contact contactFound = contactsFound.get(0); - assertTrue(contactFound.getValidationCompany()); - assertTrue(contactFound.getValidationProgram()); - } finally { - if (transaction != null) { - transaction.closeContext(); - } - } } } Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSamplingImplTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -28,6 +28,7 @@ import fr.ifremer.wao.WaoBusinessException; import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.WaoException; +import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.FacadeRow; import fr.ifremer.wao.bean.ObsProgram; import fr.ifremer.wao.bean.SamplingFilter; @@ -195,7 +196,8 @@ contact.setMainObserver(observer); contact.setSampleRow(result); - manager.getServiceContact().saveContact(contact, false); + ConnectedUser connectedUser = getConnectedUser(observer, UserRole.OBSERVER, ObsProgram.OBSMER); + manager.getServiceContact().saveContact(connectedUser, contact, false); serviceSampling.createUpdateSampleRow(result, boats, new SampleRowLogImpl()); @@ -523,7 +525,8 @@ contact.setMainObserver(observer); contact.setSampleRow(row); - manager.getServiceContact().saveContact(contact, false); + ConnectedUser connectedUser = getConnectedUser(observer, UserRole.OBSERVER, ObsProgram.OBSMER); + manager.getServiceContact().saveContact(connectedUser, contact, false); boolean errorCatched = false; try { Modified: trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSynthesisImplTest.java =================================================================== --- trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSynthesisImplTest.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/java/fr/ifremer/wao/service/ServiceSynthesisImplTest.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -27,6 +27,7 @@ import fr.ifremer.wao.AbstractServiceTest; import fr.ifremer.wao.WaoDAOHelper; import fr.ifremer.wao.bean.BoardingResult; +import fr.ifremer.wao.bean.ConnectedUser; import fr.ifremer.wao.bean.ContactAverageReactivity; import fr.ifremer.wao.bean.ContactState; import fr.ifremer.wao.bean.ContactStateStatistics; @@ -151,6 +152,7 @@ transaction.closeContext(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); ServiceContact serviceContact = manager.getServiceContact(); // First contact : OK @@ -162,7 +164,7 @@ Date begin = DateUtil.createDate(3, 3, 2010); contact1.setObservationBeginDate(begin); contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); Contact contact2 = new ContactImpl(); contact2.setBoat(boat); @@ -172,7 +174,7 @@ begin = DateUtil.createDate(3, 3, 2010); contact2.setObservationBeginDate(begin); contact2.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact2, false); + serviceContact.saveContact(connectedUser, contact2, false); Contact contact3 = new ContactImpl(); contact3.setBoat(boat2); @@ -182,7 +184,7 @@ begin = DateUtil.createDate(3, 3, 2010); contact3.setObservationBeginDate(begin); contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); + serviceContact.saveContact(connectedUser, contact3, false); /** EXEC METHOD **/ SamplingFilter filter = new SamplingFilterImpl(); @@ -242,6 +244,7 @@ transaction.closeContext(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); ServiceContact serviceContact = manager.getServiceContact(); // First contact : OK @@ -255,7 +258,7 @@ Date begin = DateUtil.createDate(3, 3, 2010); contact1.setObservationBeginDate(begin); contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); Contact contact2 = new ContactImpl(); contact2.setBoat(boat); @@ -267,7 +270,7 @@ begin = DateUtil.createDate(3, 3, 2010); contact2.setObservationBeginDate(begin); contact2.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact2, false); + serviceContact.saveContact(connectedUser, contact2, false); Contact contact3 = new ContactImpl(); contact3.setBoat(boat2); @@ -279,7 +282,7 @@ begin = DateUtil.createDate(3, 3, 2010); contact3.setObservationBeginDate(begin); contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); + serviceContact.saveContact(connectedUser, contact3, false); /** EXEC METHOD **/ @@ -524,6 +527,7 @@ transaction.closeContext(); + ConnectedUser connectedUser = getConnectedUser(user, UserRole.ADMIN, ObsProgram.OBSMER); ServiceContact serviceContact = manager.getServiceContact(); // First contact : OK @@ -537,7 +541,7 @@ contact1.setDataInputDate(inputDate); contact1.setContactState(ContactState.OBSERVATION_DONE); contact1.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact1, false); + serviceContact.saveContact(connectedUser, contact1, false); Contact contact2 = new ContactImpl(); contact2.setBoat(boat); @@ -549,7 +553,7 @@ contact2.setDataInputDate(inputDate); contact2.setContactState(ContactState.OBSERVATION_DONE); contact2.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact2, false); + serviceContact.saveContact(connectedUser, contact2, false); Contact contact3 = new ContactImpl(); contact3.setBoat(boat2); @@ -560,7 +564,7 @@ contact3.setDataInputDate(begin); contact3.setContactState(ContactState.OBSERVATION_DONE); contact3.setValidationCompany(Boolean.TRUE); - serviceContact.saveContact(contact3, false); + serviceContact.saveContact(connectedUser, contact3, false); /** EXEC METHOD **/ Modified: trunk/wao-business/src/test/resources/import/contacts.csv =================================================================== --- trunk/wao-business/src/test/resources/import/contacts.csv 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-business/src/test/resources/import/contacts.csv 2011-03-21 22:44:39 UTC (rev 1079) @@ -1,2 +1,2 @@ -"CONT_CREATION","OBSERV_ID","PLAN_CODE","NAVS_COD","CONT_ETAT","CONT_DEBUT_MAREE","CONT_FIN_MAREE","CONT_NB_OBSERV","CONT_MAM_CAPT","CONT_MAM_OBS","CONT_COMMENT","CONT_ALLEGRO","CONT_SOCIETE_VALID","CONT_PROGRAM_VALID","CONT_DATA_RELIABILITY" -17/03/2010,"jmichmuche","2010_01",175846,"OBSERVATION_EXPECTED","18/03/2010 12:34","19/03/2010 22:33",1,,,,22/07/2010,"A","A",RELIABLE +CONTACT_ID;CONTACT_DATE_CREATION;CONTACT_OBSERVATEUR_PRINCIPAL;CONTACT_OBSERVATEURS_SECONDAIRES;CONTACT_ETAT;CONTACT_DEBUT_OBSERVATION;CONTACT_FIN_OBSERVATION;CONTACT_SAISIE_DONNEES;CONTACT_COMMENTAIRE_OBSERVATEUR;CONTACT_COMMENTAIRE_COORDINATEUR;CONTACT_COMMENTAIRE_PROGRAMME;PLAN_CODE;NAVIRE_IMMATRICULATION;CONTACT_VALIDATION_SOCIETE;CONTACT_VALIDATION_PROGRAMME;CONTACT_QUALITE_DONNEE +;01/03/2011 10:24;jmichmuche;;Refus définitif;;;;ne veut plus collaborer;;;2010_0001;175846;?;?;Inconnue \ No newline at end of file Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Boats.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Boats.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Boats.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -860,7 +860,7 @@ // Get boat from list boat = getBoats().get(boatImmatriculation); //contacts.createNewContact(boat, sampleRow); - Contact newContact = serviceContact.getNewContact(user.getUser(), sampleRow, boat); + Contact newContact = serviceContact.getNewContact(user, sampleRow, boat); contacts.setContactSelectedId(newContact.getTopiaId()); return contacts; } @@ -869,7 +869,7 @@ // Get sampleRow from elligibleBoat list ElligibleBoat elligible = getCompanyBoatInfos().getElligibleBoat(sampleRowCode); sampleRow = elligible.getSampleRow(); - Contact newContact = serviceContact.getNewContact(user.getUser(), sampleRow, getBoatSelected()); + Contact newContact = serviceContact.getNewContact(user, sampleRow, getBoatSelected()); // contacts.createNewContact(getBoatSelected(), sampleRow); contacts.setContactSelectedId(newContact.getTopiaId()); return contacts; Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/ContactForm.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/ContactForm.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/ContactForm.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -416,7 +416,7 @@ logger.debug("secondary observers : " + contact.getSecondaryObservers()); logger.debug("Contact sendEmail : " + sendEmail); } - serviceContact.saveContact(contact, false); + serviceContact.saveContact(connectedUser, contact, false); try { if (sendEmail && serviceContact.sendContactDoneEmail(contact)) { Modified: trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java =================================================================== --- trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-ui/src/main/java/fr/ifremer/wao/ui/pages/Contacts.java 2011-03-21 22:44:39 UTC (rev 1079) @@ -626,7 +626,7 @@ protected void saveContact(Contact contact) { ValidationResult validationResult = serviceContact.validateContact(contact); if (validationResult.isSuccess()) { - serviceContact.saveContact(contact, false); + serviceContact.saveContact(user, contact, false); } else { layout.addError(validationResult.getMessage()); } @@ -639,7 +639,7 @@ } contactSelectedId = contactId; modifiedContact = getContacts().get(contactId); - serviceContact.saveContact(modifiedContact, true); + serviceContact.saveContact(user, modifiedContact, true); } } Modified: trunk/wao-ui/src/main/webapp/ContactForm.tml =================================================================== --- trunk/wao-ui/src/main/webapp/ContactForm.tml 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-ui/src/main/webapp/ContactForm.tml 2011-03-21 22:44:39 UTC (rev 1079) @@ -233,7 +233,7 @@ ${message:wao.ui.field.Contact.mammalsCapture} <img src="${asset:context:img/fishing-net-22px.png}" alt="${message:wao.ui.field.Contact.mammalsCapture}" /> </label> - <input t:type="checkbox" t:id="mammalsCapture" value="contact.mammalsCapture" onclick="updateMammalsInfoBox();" /> + <input t:type="checkbox" t:id="mammalsCapture" value="contact.mammalsCapture" onclick="updateMammalsInfoBox(this);" /> </div> <div id="mammalsInfoBox"> <label for="mammalsInfo"> Modified: trunk/wao-ui/src/main/webapp/js/contactForm.js =================================================================== --- trunk/wao-ui/src/main/webapp/js/contactForm.js 2011-03-21 18:40:38 UTC (rev 1078) +++ trunk/wao-ui/src/main/webapp/js/contactForm.js 2011-03-21 22:44:39 UTC (rev 1079) @@ -16,8 +16,8 @@ }); /** mammals Info box must be showed only if mammalsCapture is checked */ -function updateMammalsInfoBox() { - if ($('mammalsCapture').checked) { +function updateMammalsInfoBox(mammalsCapture) { + if (mammalsCapture.checked) { $('mammalsInfoBox').show(); } else { $('mammalsInfoBox').hide(); @@ -25,6 +25,6 @@ } Event.observe(window, 'load', function(event) { - updateMammalsInfoBox(); + updateMammalsInfoBox($('mammalsCapture')); });
participants (1)
-
bleny@users.labs.libre-entreprise.org