Author: bleny Date: 2014-06-20 19:38:35 +0200 (Fri, 20 Jun 2014) New Revision: 2078 Url: http://forge.codelutin.com/projects/wao/repository/revisions/2078 Log: refs #4488 start contacts Added: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/MissingContactTerrestrialLocationException.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ContactsServiceTest.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsFilterValuesJsonAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/CreateContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/DeleteContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/EditContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ExportContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ImportContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ValidateContactJsonAction.java branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/ContactsAction-conversion.properties branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/contacts.jsp branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/edit-contact-input.jsp Removed: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ObsMerContactsService.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ObsMerContactImportExportModel.java branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ObsMerContactsServiceTest.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsFilterValuesJsonAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/CreateContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/DeleteContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/EditContactAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ExportContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ImportContactsAction.java branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ValidateContactJsonAction.java branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/obsmer/ContactsAction-conversion.properties branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/contacts.jsp branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/edit-contact-input.jsp Modified: branches/wao-4.0-obsvente/wao-persistence/src/main/java/fr/ifremer/wao/entity/TerrestrialLocationTopiaDao.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/ObsMerFixtures.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/SynthesisService.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/UpdateContactCommand.java branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/administration/ReferentialService.java branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_en_GB.properties branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_fr_FR.properties branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_en_GB.properties branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_fr_FR.properties branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/synthesis.jsp branches/wao-4.0-obsvente/wao-web/src/main/webapp/endpoints-js.jsp Modified: branches/wao-4.0-obsvente/wao-persistence/src/main/java/fr/ifremer/wao/entity/TerrestrialLocationTopiaDao.java =================================================================== --- branches/wao-4.0-obsvente/wao-persistence/src/main/java/fr/ifremer/wao/entity/TerrestrialLocationTopiaDao.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-persistence/src/main/java/fr/ifremer/wao/entity/TerrestrialLocationTopiaDao.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -21,8 +21,10 @@ * #L% */ +import fr.ifremer.wao.WaoUtils; import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep; +import java.util.Collection; import java.util.Collections; import java.util.List; @@ -39,4 +41,8 @@ return forLocationTypeOrdinalEquals(locationType.ordinal()); } + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<TerrestrialLocation> forLocationTypeIn(Collection<LocationType> locationTypes) { + return forLocationTypeOrdinalIn(WaoUtils.toOrdinals(locationTypes)); + } + } Modified: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/ObsMerFixtures.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/ObsMerFixtures.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/ObsMerFixtures.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -36,8 +36,8 @@ import fr.ifremer.wao.entity.WaoUser; import fr.ifremer.wao.entity.WaoUserImpl; import fr.ifremer.wao.entity.WaoUserTopiaDao; +import fr.ifremer.wao.services.service.ContactsService; import fr.ifremer.wao.services.service.ImportErrorException; -import fr.ifremer.wao.services.service.ObsMerContactsService; import fr.ifremer.wao.services.service.ObsMerSamplingPlanService; import fr.ifremer.wao.services.service.administration.ReferentialService; import org.apache.commons.io.IOUtils; @@ -199,7 +199,7 @@ InputStream input = null; try { input = getClass().getResourceAsStream("/import/contacts.csv"); - serviceContext.newService(ObsMerContactsService.class).importContacts(admin(), input); + serviceContext.newService(ContactsService.class).importContacts(admin(), input); } catch (ImportErrorException e) { throw new WaoTechnicalException(e); } finally { Deleted: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,65 +0,0 @@ -package fr.ifremer.wao.services.service; - -import com.google.common.collect.ImmutableSet; -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.services.AuthenticatedWaoUser; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; - -public class ContactsService extends WaoServiceSupport { - - private static final Log log = LogFactory.getLog(ContactsService.class); - - public ContactsFilter newContactFilter(AuthenticatedWaoUser authenticatedWaoUser) { - - ContactsFilter newContactsFilter = new ContactsFilter(); - - newContactsFilter.getSampleRowFilter().setObsProgram(authenticatedWaoUser.getObsProgram()); - - // DO NOT REMOVE THIS - if (authenticatedWaoUser.isCoordinatorOrObserver()) { - String authenticatedWaoUserCompanyTopiaId = authenticatedWaoUser.getWaoUser().getCompany().getTopiaId(); - newContactsFilter.getSampleRowFilter().setCompanyIds(ImmutableSet.of(authenticatedWaoUserCompanyTopiaId)); - } - - Calendar periodFromCalendar = Calendar.getInstance(); - periodFromCalendar.setTime(serviceContext.getNow()); - - // in the firsts months of a new year go from now to 6 months before - // in the rest of the year, just start at the beginning of the current year - if (periodFromCalendar.get(Calendar.MONTH) < 3) { - periodFromCalendar.add(Calendar.MONTH, -6); - } else { - periodFromCalendar.set(Calendar.DAY_OF_YEAR, 1); - } - - Date periodFrom = periodFromCalendar.getTime(); - Date periodTo = DateUtils.addYears(periodFromCalendar.getTime(), 1); - - newContactsFilter.setPeriodFrom(periodFrom); - newContactsFilter.setPeriodTo(periodTo); - - if (authenticatedWaoUser.isProfessional()) { - // Pour le profesionnel, on restreint d'office à la liste des contacts portant sur les bateaux qu'il peut voir - Collection<String> canReadBoatsTopiaIds = authenticatedWaoUser.getWaoUser().getCanReadBoatsTopiaIds(); - if (CollectionUtils.isEmpty(canReadBoatsTopiaIds)) { - if (log.isWarnEnabled()) { - log.warn("user " + authenticatedWaoUser.getWaoUser() + " is professional but can't read any boat"); - } - } else { - newContactsFilter.getBoatFilter().setBoatIds(new HashSet<>(canReadBoatsTopiaIds)); - } - } - - return newContactsFilter; - - } - -} Copied: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java (from rev 2077, branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ObsMerContactsService.java) =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java (rev 0) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ContactsService.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,1026 @@ +package fr.ifremer.wao.services.service; + +/* + * #%L + * Wao :: Services + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.google.common.base.Charsets; +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import fr.ifremer.wao.ContactsFilter; +import fr.ifremer.wao.WaoTechnicalException; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.Boat; +import fr.ifremer.wao.entity.Company; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.entity.ContactImpl; +import fr.ifremer.wao.entity.ContactState; +import fr.ifremer.wao.entity.ContactStateMotif; +import fr.ifremer.wao.entity.ContactTopiaDao; +import fr.ifremer.wao.entity.DataReliability; +import fr.ifremer.wao.entity.ElligibleBoat; +import fr.ifremer.wao.entity.ElligibleBoatTopiaDao; +import fr.ifremer.wao.entity.LocationType; +import fr.ifremer.wao.entity.ObsProgram; +import fr.ifremer.wao.entity.ObservedDataControl; +import fr.ifremer.wao.entity.SampleMonth; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.entity.TerrestrialLocation; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.entity.WaoUserTopiaDao; +import fr.ifremer.wao.services.AuthenticatedWaoUser; +import fr.ifremer.wao.services.service.csv.ContactImportExportModel; +import fr.ifremer.wao.services.service.mail.AddBoatToUserAllegroWalletEmail; +import fr.ifremer.wao.services.service.mail.EmailService; +import fr.ifremer.wao.services.service.mail.MammalsObservationEmail; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.csv.AbstractImportErrorInfo; +import org.nuiton.csv.Export; +import org.nuiton.csv.ExportModel; +import org.nuiton.csv.Import2; +import org.nuiton.csv.ImportConf; +import org.nuiton.csv.ImportModel; +import org.nuiton.csv.ImportRow; +import org.nuiton.i18n.I18n; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.util.DateUtil; +import org.nuiton.util.StringUtil; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderFactory; +import org.nuiton.util.pagination.PaginationParameter; +import org.nuiton.util.pagination.PaginationResult; + +import java.io.InputStream; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import static org.nuiton.i18n.I18n.l; + +public class ContactsService extends WaoServiceSupport { + + private static final Log log = LogFactory.getLog(ContactsService.class); + + public ContactsFilter newContactFilter(AuthenticatedWaoUser authenticatedWaoUser) { + + ContactsFilter newContactsFilter = new ContactsFilter(); + + newContactsFilter.getSampleRowFilter().setObsProgram(authenticatedWaoUser.getObsProgram()); + + // DO NOT REMOVE THIS + if (authenticatedWaoUser.isCoordinatorOrObserver()) { + String authenticatedWaoUserCompanyTopiaId = authenticatedWaoUser.getWaoUser().getCompany().getTopiaId(); + newContactsFilter.getSampleRowFilter().setCompanyIds(ImmutableSet.of(authenticatedWaoUserCompanyTopiaId)); + } + + Calendar periodFromCalendar = Calendar.getInstance(); + periodFromCalendar.setTime(serviceContext.getNow()); + + // in the firsts months of a new year go from now to 6 months before + // in the rest of the year, just start at the beginning of the current year + if (periodFromCalendar.get(Calendar.MONTH) < 3) { + periodFromCalendar.add(Calendar.MONTH, -6); + } else { + periodFromCalendar.set(Calendar.DAY_OF_YEAR, 1); + } + + Date periodFrom = periodFromCalendar.getTime(); + Date periodTo = DateUtils.addYears(periodFromCalendar.getTime(), 1); + + newContactsFilter.setPeriodFrom(periodFrom); + newContactsFilter.setPeriodTo(periodTo); + + if (authenticatedWaoUser.isProfessional()) { + // Pour le profesionnel, on restreint d'office à la liste des contacts portant sur les bateaux qu'il peut voir + Collection<String> canReadBoatsTopiaIds = authenticatedWaoUser.getWaoUser().getCanReadBoatsTopiaIds(); + if (CollectionUtils.isEmpty(canReadBoatsTopiaIds)) { + if (log.isWarnEnabled()) { + log.warn("user " + authenticatedWaoUser.getWaoUser() + " is professional but can't read any boat"); + } + } else { + newContactsFilter.getBoatFilter().setBoatIds(new HashSet<>(canReadBoatsTopiaIds)); + } + } + + return newContactsFilter; + + } + + public ContactsFilterValues getContactsFilterValues(AuthenticatedWaoUser authenticatedWaoUser, ContactsFilter filter) { + + ContactTopiaDao dao = getContactDao(); + List<Contact> contacts = dao.forFilter(filter, false).findAll(); + + Optional<String> optionalCompanyId = Optional.absent(); + if (authenticatedWaoUser.isCoordinatorOrObserver()) { + optionalCompanyId = Optional.of(authenticatedWaoUser.getCompany().getTopiaId()); + } + ContactsFilterValues contactsFilterValues = new ContactsFilterValues(serviceContext.getLocale(), authenticatedWaoUser.getObsProgram(), optionalCompanyId); + + for (Contact contact : contacts) { + contactsFilterValues.addContact(contact); + } + + return contactsFilterValues; + } + + public ObsMerContactsList getContactsList(AuthenticatedWaoUser authenticatedWaoUser, + ContactsFilter filter, + PaginationParameter queryPager) { + + ContactTopiaDao dao = getContactDao(); + + // Need to copy to add sort attributes + PaginationParameter.PaginationParameterBuilder builder = PaginationParameter.builder(queryPager.getPageNumber(), queryPager.getPageSize()); + if (filter.isSortedByBoardingDate()) { + builder.addOrder(Contact.PROPERTY_OBSERVATION_BEGIN_DATE, true); + } else { + builder.addOrder(Contact.PROPERTY_CREATION_DATE, true); + } + PaginationParameter pager = builder.build(); + + PaginationResult<Contact> contacts = dao.forFilter(filter, false).findPage(pager); + + ContactsFilterValues filterValues = getContactsFilterValues(authenticatedWaoUser, filter); + + ObsMerContactsList contactsList = new ObsMerContactsList(); + contactsList.setContacts(contacts); + contactsList.setFilterValues(filterValues); + return contactsList; + } + + public PaginationParameter newContactsPaginationParameter(int pageNumber, int pageSize) { + PaginationParameter result = PaginationParameter.of(pageNumber, pageSize); + return result; + } + + public UpdateContactCommand newUpdateContactCommand(AuthenticatedWaoUser authenticatedWaoUser, Optional<String> optionalContactId) { + + //FIXME Should we apply some security rules (can create, update, import) ? + //Preconditions.checkState(authenticatedWaoUser.isAuthorizedToCreateSampleRow()); + + UpdateContactCommand updateContactCommand = new UpdateContactCommand(); + + updateContactCommand.setAdmin(authenticatedWaoUser.isAdmin()); + + Contact contact; + + if (optionalContactId.isPresent()) { + + String contactId = optionalContactId.get(); + + contact = getContact(contactId); + + updateContactCommand.setContact(contact); + + updateContactCommand.setCreation(false); + + String mainObserverId = contact.getMainObserver().getTopiaId(); + updateContactCommand.setMainObserverId(mainObserverId); + Set<String> secondaryObserversTopiaIds = contact.getSecondaryObserversTopiaIds(); + updateContactCommand.setSecondaryObserverIds(secondaryObserversTopiaIds); + + String terrestrialLocationId = contact.getTerrestrialLocation().getTopiaId(); + updateContactCommand.setTerrestrialLocationId(terrestrialLocationId); + + } else { + + contact = new ContactImpl(); + + contact.setObsProgram(authenticatedWaoUser.getObsProgram()); + + contact.setCreationDate(getNow()); + + updateContactCommand.setContact(contact); + + updateContactCommand.setCreation(true); + } + + return updateContactCommand; + } + + public Contact getContact(String contactId) { + return getContactDao().forTopiaIdEquals(contactId).findUnique(); + } + + public InputStream exportContacts(ContactsFilter filter) { + ContactTopiaDao dao = getContactDao(); + + List<Contact> contacts = dao.forFilter(filter, true).findAll(); + + ExportModel<Contact> exportModel = ContactImportExportModel.forExport(getLocale(), + filter.getSampleRowFilter().getObsProgram()); + + Export<Contact> export = Export.newExport(exportModel, contacts); + + try { + + String csvContent = export.toString(Charsets.UTF_8); + + InputStream csvInputStream = IOUtils.toInputStream(csvContent, Charsets.UTF_8); + + return csvInputStream; + + } catch (Exception e) { + throw new WaoTechnicalException(e); + } + } + + public void importContacts(AuthenticatedWaoUser authenticatedWaoUser, + InputStream csv) throws ImportErrorException { + + ObsProgram obsProgram = authenticatedWaoUser.getObsProgram(); + + List<SampleRow> sampleRows = + getSampleRowDao().forObsProgramOrdinalEquals(obsProgram.ordinal()).findAll(); + List<WaoUser> waoUsers = getWaoUserDao().findAll(); + List<Boat> boats = getBoatDao().findAll(); + List<ContactStateMotif> motives = getContactStateMotifDao().findAll(); + List<TerrestrialLocation> terrestrialLocations = + getTerrestrialLocationDao().forLocationTypeIn(ImmutableSet.of(LocationType.AUCTION, LocationType.PORT)).findAll(); + + Locale l = getLocale(); + ImportModel<Contact> contactImportModel = + ContactImportExportModel.forImport(l, + obsProgram, + waoUsers, + sampleRows, + boats, + motives, + terrestrialLocations); + + ImportConf importConf = new ImportConf(); + importConf.setStrictMode(true); + + Import2<Contact> contactImport = Import2.newImport(importConf, contactImportModel, csv); + + for (ImportRow<Contact> contactRow : contactImport) { + + if (!contactRow.isValid()) { + // throw first error + Set<AbstractImportErrorInfo<Contact>> errors = contactRow.getErrors(); + AbstractImportErrorInfo<Contact> errorInfo = errors.iterator().next(); + throw new ImportErrorException(errorInfo.getCause()); + } + long lineNumber = contactRow.getLineNumber(); + + Contact contact = contactRow.getBean(); + + String contactId = contact.getTopiaId(); + + if (StringUtils.isEmpty(contactId)) { + contactId = null; + } + + Optional<String> optionalContactId = Optional.fromNullable(contactId); + UpdateContactCommand updateContactCommand = newUpdateContactCommand(authenticatedWaoUser, + optionalContactId); + + if (updateContactCommand.isCreation()) { + + updateContactCommand.setContact(contact); + + // Prevent that someone who is not admin change data that only admin + // must be able to modify + if ( ! authenticatedWaoUser.isAdmin()) { + contact.setCommentAdmin(null); + contact.setValidationProgram(null); + contact.setDataReliability(DataReliability.UNKNOWN); + } + + } else { + + Contact contactToUpdate = updateContactCommand.getContact(); + + // TODO brendan 20/06/14 create to binders + Binder<Contact, Contact> binder = BinderFactory.newBinder(Contact.class); + binder.copyExcluding(contact, contactToUpdate, TopiaEntity.PROPERTY_TOPIA_ID, TopiaEntity.PROPERTY_TOPIA_VERSION, + TopiaEntity.PROPERTY_TOPIA_CREATE_DATE, Contact.PROPERTY_SAMPLE_ROW); + + // Prevent that someone who is not admin change data that only admin + // must be able to modify + if ( ! authenticatedWaoUser.isAdmin()) { + contactToUpdate.setCommentAdmin(contact.getCommentAdmin()); + contactToUpdate.setValidationProgram(contact.getValidationProgram()); + contactToUpdate.setDataReliability(contact.getDataReliability()); + } + + } + + try { + validate(authenticatedWaoUser, updateContactCommand, false); + } catch (ContactNotUpdatableException e) { + String message = l(l, "wao.import.contact.failure.not.updatable", lineNumber); + throw new ImportErrorException(message); + } catch (UnwantedContactContactStateMotifException e) { + String message = l(l, "wao.import.contact.failure.unwantedContactStateMotif", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactNbObservantsException e) { + String state = WaoUtils.l(l, e.getContact().getContactState()); + String message = l(l, "wao.import.contact.failure.missingObserver", lineNumber, state); + throw new ImportErrorException(message); + } catch (MissingContactObservationEndDateException e) { + String state = WaoUtils.l(l, e.getContact().getContactState()); + String message = l(l, "wao.import.contact.failure.missingObservationEndDate", lineNumber, state); + throw new ImportErrorException(message); + } catch (ContactDataInputDateBeforeObservationEndDateException e) { + String message = l(l, "wao.import.contact.failure.dataInputDateBeforeObservationEndDate", lineNumber); + throw new ImportErrorException(message); + } catch (InvalidContactObservationBeginDateException e) { + String message = l(l, "wao.import.contact.failure.invalidObservationBeginDate", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactRestitutionException e) { + String message = l(l, "wao.import.contact.failure.missingRestitution", lineNumber); + throw new ImportErrorException(message); + } catch (ContactDataInputDateAfterTodayException e) { + String message = l(l, "wao.import.contact.failure.dataInputDateAfterToday", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactCommentException e) { + String state = WaoUtils.l(l, e.getContact().getContactState()); + String message = l(l, "wao.import.contact.failure.missingComment", state, lineNumber); + throw new ImportErrorException(message); + } catch (MismatchContactMainObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + String message = l(l, "wao.import.contact.failure.mismatchCompanyForObserver", lineNumber, observerLogin, companyName); + throw new ImportErrorException(message); + } catch (ContactRestitutionDateBeforeDataInputDateException e) { + String message = l(l, "wao.import.contact.failure.transmissionDateBeforeDataInputDate", lineNumber); + throw new ImportErrorException(message); + } catch (ContactObservationEndDateBeforeBeginDateException e) { + String message = l(l, "wao.import.contact.failure.observationEndDateBeforeBeginDate", lineNumber); + throw new ImportErrorException(message); + } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { + String message = l(l, "wao.import.contact.failure.duplicatedMainObserverInSecondaryObservers", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactDataReliabilityException e) { + String message = l(l, "wao.import.contact.failure.missingDataReliability", lineNumber); + throw new ImportErrorException(message); + } catch (MismatchContactSecondaryObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + String message = l(l, "wao.import.contact.failure.mismatchCompanyForObserver", lineNumber, observerLogin, companyName); + throw new ImportErrorException(message); + } catch (MissingContactObservedDataControlException e) { + String message = l(l, "wao.import.contact.failure.missingObservedDataControl", lineNumber); + throw new ImportErrorException(message); + } catch (ContactWithObservedDataControlToCorrectionAskedException e) { + String message = l(l, "wao.import.contact.failure.observedDataControlToCorrectionAsked", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactStateMotifException e) { + String message = l(l, "wao.import.contact.failure.missingContactStateMotif", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactDataInputDateException e) { + String message = l(l, "wao.import.contact.failure.missingDataInputDate", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactMainObserverException e) { + String message = l(l, "wao.import.contact.failure.missingMainObserver", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactCommentAdminException e) { + String dataReliability = WaoUtils.l(l, e.getContact().getDataReliability()); + String message = l(l, "wao.import.contact.failure.missingCommentAdmin", lineNumber, dataReliability); + throw new ImportErrorException(message); + } catch (ContactObservationEndDateAfterTodayException e) { + String message = l(l, "wao.import.contact.failure.observationEndDateAfterToday", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactObservationBeginDateException e) { + String state = WaoUtils.l(l, e.getContact().getContactState()); + String message = l(l, "wao.import.contact.failure.missingObservationBeginDate", lineNumber, state); + throw new ImportErrorException(message); + } catch (MissingContactMammalsInfoException e) { + String message = l(l, "wao.import.contact.failure.missingContactMammalsInfo", lineNumber); + throw new ImportErrorException(message); + } catch (MissingContactTerrestrialLocationException e) { + String message = l(l, "wao.import.contact.failure.missingTerrestrialLocation", lineNumber); + throw new ImportErrorException(message); + } + + save0(updateContactCommand); + } + + commit(); + } + + public void preValidate(UpdateContactCommand updateContactCommand) { + + String mainObserverId = updateContactCommand.getMainObserverId(); + + WaoUser mainObserver = getWaoUserDao().forTopiaIdEquals(mainObserverId).findUnique(); + updateContactCommand.getContact().setMainObserver(mainObserver); + + List<WaoUser> secondaryObservers = getWaoUserDao().forTopiaIdIn(updateContactCommand.getSecondaryObserverIds()).findAll(); + updateContactCommand.getContact().setSecondaryObservers(new HashSet<>(secondaryObservers)); + + TerrestrialLocation terrestrialLocation = getTerrestrialLocationDao().forTopiaIdEquals(updateContactCommand.getTerrestrialLocationId()).findUnique(); + updateContactCommand.getContact().setTerrestrialLocation(terrestrialLocation); + + } + + public void validate(AuthenticatedWaoUser authenticatedWaoUser, + UpdateContactCommand updateContactCommand, + boolean needUpdate) throws + ContactNotUpdatableException, + MissingContactMainObserverException, + MismatchContactMainObserverCompanyException, + DuplicatedContactMainObserverInSecondaryObserversException, + MismatchContactSecondaryObserverCompanyException, + InvalidContactObservationBeginDateException, + ContactObservationEndDateBeforeBeginDateException, + ContactObservationEndDateAfterTodayException, + ContactDataInputDateBeforeObservationEndDateException, + ContactDataInputDateAfterTodayException, + MissingContactCommentException, + MissingContactObservationBeginDateException, + MissingContactObservationEndDateException, + MissingContactNbObservantsException, + MissingContactStateMotifException, + UnwantedContactContactStateMotifException, + MissingContactObservedDataControlException, + MissingContactMammalsInfoException, + ContactWithObservedDataControlToCorrectionAskedException, + MissingContactRestitutionException, + MissingContactDataInputDateException, + ContactRestitutionDateBeforeDataInputDateException, + MissingContactDataReliabilityException, + MissingContactCommentAdminException, MissingContactTerrestrialLocationException { + + if (needUpdate) { + Preconditions.checkState(!updateContactCommand.isCreation()); + } + + //FIXME Do some security checks about authenticatedWaoUser + + // Check if contact can be updated + boolean canUpdateContact = updateContactCommand.canUpdateContact(authenticatedWaoUser); + if (!canUpdateContact) { + throw new ContactNotUpdatableException(); + } + + // Check if a validation controls are required + boolean mustValidateContact = updateContactCommand.mustValidateContact(); + + if (mustValidateContact) { + + // Pass validation controls + Contact contact = updateContactCommand.getContact(); + + Company company = contact.getSampleRow().getCompany(); + + WaoUser mainObserver = contact.getMainObserver(); + + { + //--- + // mainObserver + //--- + + if (mainObserver == null) { + throw new MissingContactMainObserverException(contact); + } + + boolean observerWorksForCompanyInSampleRow = mainObserver.getCompany().equals(company); + if (!observerWorksForCompanyInSampleRow) { + throw new MismatchContactMainObserverCompanyException(contact, mainObserver, company); + } + } + + if (contact.isSecondaryObserversNotEmpty()) { + + //--- + // secondaryObservers + //--- + + if (contact.getSecondaryObservers().contains(mainObserver)) { + throw new DuplicatedContactMainObserverInSecondaryObserversException(contact); + } + + for (WaoUser observer : contact.getSecondaryObservers()) { + boolean observerWorksForCompanyInSampleRow = observer.getCompany().equals(company); + if (!observerWorksForCompanyInSampleRow) { + throw new MismatchContactSecondaryObserverCompanyException(contact, observer, company); + } + } + } + + Date observationBeginDate = contact.getObservationBeginDate(); + Date observationEndDate = contact.getObservationEndDate(); + Date dataInputDate = contact.getDataInputDate(); + + SampleRow sampleRow = contact.getSampleRow(); + + if (observationBeginDate != null) { + + //--- + // observationBeginDate + //--- + + SampleMonth month = sampleRow.getSampleMonth(observationBeginDate); + boolean operationBeginDateIsValid = month != null; + + if (!operationBeginDateIsValid) { + throw new InvalidContactObservationBeginDateException(contact); + } + } + + Date currentDate = serviceContext.getNow(); + + if (observationEndDate != null) { + + //--- + // observationEndDate + //--- + + if (observationBeginDate != null + && observationEndDate.before(observationBeginDate)) { + throw new ContactObservationEndDateBeforeBeginDateException(contact); + } + + if (observationEndDate.after(currentDate)) { + throw new ContactObservationEndDateAfterTodayException(contact, currentDate); + } + + } + + if (dataInputDate != null) { + + //--- + // dataInputDate + //--- + + if (observationEndDate != null) { + + // Here, we check that the date input date is after the end of the + // observation. Since the first is a day (at 00:00) and the second + // is date-time, there may be a bug if the data input day is the same + // as the end of observation + boolean dataInputDateAfterObservationEndDate = + observationEndDate.after(DateUtil.setMaxTimeOfDay(dataInputDate)); + + if (dataInputDateAfterObservationEndDate) { + throw new ContactDataInputDateBeforeObservationEndDateException(contact); + } + } + + if (dataInputDate.after(currentDate)) { + throw new ContactDataInputDateAfterTodayException(contact, currentDate); + } + } + + //--- + // contactState + //--- + + ContactState contactState = contact.getContactState(); + + boolean contactMustHaveAMotif = false; + switch (contactState) { + case OBSERVATION_CANCELLED: + + // Non abouti + + if (StringUtils.isBlank(contact.getComment())) { + throw new MissingContactCommentException(contact); + } + break; + case OBSERVATION_DONE: + + // Observation réalisée + + if (observationBeginDate == null) { + throw new MissingContactObservationBeginDateException(contact); + } + if (observationEndDate == null) { + throw new MissingContactObservationEndDateException(contact); + } + if (contact.getNbObservants() == 0) { + throw new MissingContactNbObservantsException(contact); + } + if (contact.getObsProgram().isObsVente() && contact.getTerrestrialLocation() == null) { + throw new MissingContactTerrestrialLocationException(contact); + } + break; + + case CONTACT_REFUSED: + contactMustHaveAMotif = true; + break; + case CONTACT_DEFINITELY_REFUSED: + contactMustHaveAMotif = true; + break; + + } + + //--- + // contactStateMotif + //--- + + if (contactMustHaveAMotif && contact.getContactStateMotif() == null) { + throw new MissingContactStateMotifException(contact); + } + + if (!contactMustHaveAMotif && contact.getContactStateMotif() != null) { + throw new UnwantedContactContactStateMotifException(contact); + } + + if (contact.isMammalsCapture() && StringUtils.isBlank(contact.getMammalsInfo())) { + throw new MissingContactMammalsInfoException(contact); + } + + if (BooleanUtils.isTrue(contact.getValidationCompany())) { + + //--- + // validationCompany + //--- + + if (ContactState.OBSERVATION_DONE == contactState) { + if (contact.getObservedDataControl() == null) { + throw new MissingContactObservedDataControlException(contact); + } else if (contact.getObservedDataControl().equals(ObservedDataControl.CORRECTION_ASKED)) { + throw new ContactWithObservedDataControlToCorrectionAskedException(contact); + } + } + + // Pour valider un contact société, il faut que le contact aie une date de transmission + Date restitution = contact.getRestitution(); + if (ObservedDataControl.ACCEPTED == contact.getObservedDataControl() && restitution == null) { + throw new MissingContactRestitutionException(contact); + } + if (dataInputDate == null && restitution != null) { + throw new MissingContactDataInputDateException(contact); + } + if (dataInputDate != null && restitution != null && restitution.before(dataInputDate)) { + throw new ContactRestitutionDateBeforeDataInputDateException(contact); + } + } + + DataReliability dataReliability = contact.getDataReliability(); + + if (dataReliability != null && dataReliability.isCommentRequired() && StringUtils.isBlank(contact.getCommentAdmin())) { + throw new MissingContactCommentAdminException(contact); + } + + if (BooleanUtils.isTrue(contact.getValidationProgram())) { + + //--- + // validationProgram + //--- + + // it's an admin validation, data-reliability field must be filled + + if (dataReliability == null || DataReliability.UNKNOWN == dataReliability) { + throw new MissingContactDataReliabilityException(contact); + } + } + } + } + + public void save(UpdateContactCommand updateContactCommand, + boolean needUpdate) throws ContactNotUpdatableException { + + if (needUpdate) { + Preconditions.checkState(!updateContactCommand.isCreation()); + } + + save0(updateContactCommand); + + commit(); + + updateAllegroWalletIfNecessary(updateContactCommand); + + notifyMammalsObservationIfNecessary(updateContactCommand); + + } + + protected void notifyMammalsObservationIfNecessary(UpdateContactCommand updateContactCommand) { + + if (updateContactCommand.isMammalsInfosChanged()) { + + Contact contact = updateContactCommand.getContact(); + + MammalsObservationEmail email = getEmailService().newMammalsObservationEmail(); + email.setContact(contact); + + // now trying to find to what user we need to send the mail + WaoUserTopiaDao userDao = getWaoUserDao(); + // users contains all the user we need to notify for the capture + List<WaoUser> waoUsers = userDao.forMammalsNotificationsEquals(true).addEquals(WaoUser.PROPERTY_ACTIVE, true).findAll(); + + for (WaoUser waoUser : waoUsers) { + if (StringUtil.isEmail(waoUser.getLogin())) { + email.addBcc(waoUser); + } else { + if (log.isWarnEnabled()) { + log.warn("will not send mammals capture notification to user " + waoUser + ". login is not an email"); + } + } + } + + getEmailService().send(email); + + } + + } + + public void delete(String contactId) throws IllegalDeletionException { + + Contact contact = getContact(contactId); + + // Execute delete + ContactTopiaDao dao = getContactDao(); + + Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> allUsages = dao.findAllUsages(contact); + + if (!allUsages.isEmpty()) { + throw new IllegalDeletionException(allUsages); + } + + ObsMerSamplingPlanService samplingPlanService = newService(ObsMerSamplingPlanService.class); + + samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); + + dao.delete(contact); + + commit(); + } + + protected void save0(UpdateContactCommand updateContactCommand) { + + // Get contact to validate (must exist) + Contact contact = updateContactCommand.getContact(); + + ContactTopiaDao dao = getContactDao(); + + ObsMerSamplingPlanService samplingPlanService = newService(ObsMerSamplingPlanService.class); + + if (updateContactCommand.isCreation()) { + + //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. + + ElligibleBoatTopiaDao elligibleDAO = getElligibleBoatDao(); + ElligibleBoat elligible = elligibleDAO.findUniqueOrNull(contact); + + if (elligible == null) { + // Create new elligible boat not active in a global way + elligible = elligibleDAO.create(contact); + } + elligible.setCompanyActive(Boolean.TRUE); + + if (contact.getCreationDate() == null) { + contact.setCreationDate(serviceContext.getNow()); + } + + samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); + + dao.create(contact); + + } else { + + samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); + + dao.update(contact); + } + + } + + protected void updateAllegroWalletIfNecessary(UpdateContactCommand updateContactCommand) { + + Contact contact = updateContactCommand.getContact(); + ContactState contactState = contact.getContactState(); + ObsProgram obsProgram = contact.getObsProgram(); + + boolean addBoatToObserversAllegroWallet = false; + + if (obsProgram == ObsProgram.OBSMER) { + addBoatToObserversAllegroWallet = contactState == ContactState.OBSERVATION_DONE + || contactState == ContactState.OBSERVATION_EXPECTED; + } else if (obsProgram == ObsProgram.OBSVENTE) { + addBoatToObserversAllegroWallet = ContactState.OBSERVATION_DONE == contactState; + } + + if (addBoatToObserversAllegroWallet) { + + Boat boat = contact.getBoat(); + + String info; + + if (contactState == ContactState.OBSERVATION_EXPECTED) { + info = I18n.l( + serviceContext.getLocale(), + "wao.email.addBoatToUserAllegroWallet.contactExpected", + WaoUtils.formatDate(serviceContext.getLocale(), contact.getObservationBeginDate())); + } else if (contactState == ContactState.OBSERVATION_DONE) { + info = I18n.l( + serviceContext.getLocale(), + "wao.email.addBoatToUserAllegroWallet.contactDone", + WaoUtils.formatDateTime(serviceContext.getLocale(), contact.getObservationBeginDate()), + WaoUtils.formatDateTime(serviceContext.getLocale(), contact.getObservationEndDate())); + } else { + throw new IllegalStateException(contactState + " should not lead to a mail sent"); + } + + // in obsvente, only the main observer + Collection<WaoUser> observers; + if (ObsProgram.OBSVENTE.equals(obsProgram)) { + observers = ImmutableSet.of(contact.getMainObserver()); + } else if (ObsProgram.OBSMER.equals(obsProgram)) { + observers = contact.getAllObservers(); + } else { + throw new IllegalStateException(); + } + + EmailService emailService = getEmailService(); + + WaoUserTopiaDao waoUserDao = getWaoUserDao(); + + for (WaoUser observer : observers) { + + boolean boatAlreadyInWallet = observer.containsAllegroWallet(boat); + + if (boatAlreadyInWallet) { + + if (log.isInfoEnabled()) { + log.info("user " + observer + " already has " + boat + " in his allegroWallet"); + } + + } else { + + if (log.isInfoEnabled()) { + log.info("user " + observer + " miss " + boat + " in his allegro wallet, adding"); + } + + String observerLogin = observer.getLogin(); + String emailToUpdateAllegroWallets = getApplicationConfig().getEmailToUpdateAllegroWallets(); + + AddBoatToUserAllegroWalletEmail email = + emailService.newAddBoatToUserAllegroWalletEmail(); + + email.setBoat(boat); + email.setObserver(observer); + email.setInfo(info); + email.setObsProgram(contact.getObsProgram()); + + if ( ! StringUtil.isEmail(observerLogin)) { + if (log.isInfoEnabled()) { + log.info("user login is not a email, won't send anything: " + observerLogin + " email=" + email); + } + } else if ( ! observer.isActive()) { + if (log.isInfoEnabled()) { + log.info("observer is no longer active, won't send " + email); + } + } else if (StringUtils.isBlank(emailToUpdateAllegroWallets)) { + if (log.isInfoEnabled()) { + log.info("no email to update allegro wallets provided in configuration, won't send " + email); + } + } else if ( ! StringUtil.isEmail(emailToUpdateAllegroWallets)) { + if (log.isWarnEnabled()) { + log.warn("email to update allegro wallets provided in configuration is not valid, won't send " + emailToUpdateAllegroWallets); + } + } else { + + email.addBcc(observer); + + email.addTo(emailToUpdateAllegroWallets); + + emailService.send(email); + + observer.addAllegroWallet(boat); + waoUserDao.update(observer); + commit(); + + } + } + } + } + } + + public Contact createContact(AuthenticatedWaoUser authenticatedWaoUser, String sampleRowId, String boatId) { + + if (log.isInfoEnabled()) { + log.info(authenticatedWaoUser.getWaoUser() + " is creating a contact for " + sampleRowId + " and " + boatId); + } + + UpdateContactCommand updateContactCommand = newUpdateContactCommand(authenticatedWaoUser, Optional.<String>absent()); + + Boat boat = getBoatDao().findByTopiaId(boatId); + Preconditions.checkState(boat.isActive(), "boat must be active"); + + SampleRow sampleRow = getSampleRowDao().findByTopiaId(sampleRowId); + ObsProgram obsProgram = sampleRow.getObsProgram(); + + WaoUser observer = authenticatedWaoUser.getWaoUser(); + Contact mostRecentContactOrNull = getContactDao().findMostRecentContactOrNull(obsProgram, boatId, observer.getCompany().getTopiaId()); + Preconditions.checkState( + mostRecentContactOrNull == null || mostRecentContactOrNull.getContactState().isFinalState(), + "contact already exists"); + + Date now = serviceContext.getNow(); + + Contact newContact = updateContactCommand.getContact(); + newContact.setDataReliability(DataReliability.UNKNOWN); + newContact.setBoat(boat); + newContact.setMainObserver(observer); + newContact.setSampleRow(sampleRow); + newContact.setCreationDate(now); + + // initial contact state depends on the program + if (obsProgram == ObsProgram.OBSMER) { + newContact.setContactState(ContactState.CONTACT_START); + } else if (obsProgram == ObsProgram.OBSVENTE) { + newContact.setContactState(ContactState.OBSERVATION_EXPECTED); + } + + // we can suppose a new contact default values are the one + // expected in the sampling plan + + if (newContact.getObsProgram() == ObsProgram.OBSVENTE) { + // we hope in this contact, user used expected sampling strategy + newContact.setSamplingStrategy(sampleRow.getSamplingStrategy()); + } + + // In the case of ObsVente, we may have a user who wants to create + // multiple contact for a same day. Here we try, to ease the input + // of data by trying to pre-fill some field using data given + // in a previous entered contact + + if (newContact.getObsProgram() == ObsProgram.OBSVENTE) { + // try to pre-fill some field for user-experience + + // let's try to find a recent similar contact + Map<String, Object> properties = new HashMap<>(); + properties.put(Contact.PROPERTY_OBS_PROGRAM_ORDINAL, newContact.getObsProgram().ordinal()); + properties.put(Contact.PROPERTY_SAMPLE_ROW, sampleRow); + properties.put(Contact.PROPERTY_MAIN_OBSERVER, observer); + + List<Contact> candidates = getContactDao().forProperties(properties).findAll(); + + Contact similarContact = null; // to be found among candidates + for (Contact candidate : candidates) { + if (DateUtil.getDifferenceInDays(candidate.getCreationDate(), now) <= 1) { + similarContact = candidate; + } + } + + if (log.isDebugEnabled()) { + String logMessage; + if (similarContact == null) { + logMessage = "no similar contact found"; + } else { + logMessage = "similar contact found to pre-fill values of contact : " + + similarContact.getTopiaId() + " boat = " + similarContact.getBoat().getName(); + } + log.debug(logMessage); + } + + if (similarContact != null) { + newContact.setObservationBeginDate(similarContact.getObservationBeginDate()); + newContact.setObservationEndDate(similarContact.getObservationEndDate()); + newContact.setTerrestrialLocation(similarContact.getTerrestrialLocation()); + newContact.clearSecondaryObservers(); + newContact.addAllSecondaryObservers(similarContact.getSecondaryObservers()); + newContact.setDataInputDate(similarContact.getDataInputDate()); + } + } + + save0(updateContactCommand); + + commit(); + + return newContact; + + } + +} Added: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/MissingContactTerrestrialLocationException.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/MissingContactTerrestrialLocationException.java (rev 0) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/MissingContactTerrestrialLocationException.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,10 @@ +package fr.ifremer.wao.services.service; + +import fr.ifremer.wao.entity.Contact; + +public class MissingContactTerrestrialLocationException extends WaoContactValidationException { + + public MissingContactTerrestrialLocationException(Contact contact) { + super(contact); + } +} Deleted: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ObsMerContactsService.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ObsMerContactsService.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/ObsMerContactsService.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,976 +0,0 @@ -package fr.ifremer.wao.services.service; - -/* - * #%L - * Wao :: Services - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.base.Charsets; -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.WaoTechnicalException; -import fr.ifremer.wao.WaoUtils; -import fr.ifremer.wao.entity.Boat; -import fr.ifremer.wao.entity.Company; -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.entity.ContactImpl; -import fr.ifremer.wao.entity.ContactState; -import fr.ifremer.wao.entity.ContactStateMotif; -import fr.ifremer.wao.entity.ContactTopiaDao; -import fr.ifremer.wao.entity.DataReliability; -import fr.ifremer.wao.entity.ElligibleBoat; -import fr.ifremer.wao.entity.ElligibleBoatTopiaDao; -import fr.ifremer.wao.entity.ObsProgram; -import fr.ifremer.wao.entity.ObservedDataControl; -import fr.ifremer.wao.entity.SampleMonth; -import fr.ifremer.wao.entity.SampleRow; -import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.entity.WaoUserTopiaDao; -import fr.ifremer.wao.services.AuthenticatedWaoUser; -import fr.ifremer.wao.services.service.csv.ObsMerContactImportExportModel; -import fr.ifremer.wao.services.service.mail.AddBoatToUserAllegroWalletEmail; -import fr.ifremer.wao.services.service.mail.EmailService; -import fr.ifremer.wao.services.service.mail.MammalsObservationEmail; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.csv.AbstractImportErrorInfo; -import org.nuiton.csv.Export; -import org.nuiton.csv.ExportModel; -import org.nuiton.csv.Import2; -import org.nuiton.csv.ImportConf; -import org.nuiton.csv.ImportModel; -import org.nuiton.csv.ImportRow; -import org.nuiton.i18n.I18n; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.util.DateUtil; -import org.nuiton.util.StringUtil; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderFactory; -import org.nuiton.util.pagination.PaginationParameter; -import org.nuiton.util.pagination.PaginationResult; - -import java.io.InputStream; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import static org.nuiton.i18n.I18n.l; - -public class ObsMerContactsService extends ContactsService { - - private static final Log log = LogFactory.getLog(ObsMerContactsService.class); - - public ContactsFilterValues getContactsFilterValues(AuthenticatedWaoUser authenticatedWaoUser, ContactsFilter filter) { - - ContactTopiaDao dao = getContactDao(); - List<Contact> contacts = dao.forFilter(filter, false).findAll(); - - Optional<String> optionalCompanyId = Optional.absent(); - if (authenticatedWaoUser.isCoordinatorOrObserver()) { - optionalCompanyId = Optional.of(authenticatedWaoUser.getCompany().getTopiaId()); - } - ContactsFilterValues contactsFilterValues = new ContactsFilterValues(serviceContext.getLocale(), authenticatedWaoUser.getObsProgram(), optionalCompanyId); - - for (Contact contact : contacts) { - contactsFilterValues.addContact(contact); - } - - return contactsFilterValues; - } - - public ObsMerContactsList getContactsList(AuthenticatedWaoUser authenticatedWaoUser, - ContactsFilter filter, - PaginationParameter queryPager) { - - ContactTopiaDao dao = getContactDao(); - - // Need to copy to add sort attributes - PaginationParameter.PaginationParameterBuilder builder = PaginationParameter.builder(queryPager.getPageNumber(), queryPager.getPageSize()); - if (filter.isSortedByBoardingDate()) { - builder.addOrder(Contact.PROPERTY_OBSERVATION_BEGIN_DATE, true); - } else { - builder.addOrder(Contact.PROPERTY_CREATION_DATE, true); - } - PaginationParameter pager = builder.build(); - - PaginationResult<Contact> contacts = dao.forFilter(filter, false).findPage(pager); - - ContactsFilterValues filterValues = getContactsFilterValues(authenticatedWaoUser, filter); - - ObsMerContactsList contactsList = new ObsMerContactsList(); - contactsList.setContacts(contacts); - contactsList.setFilterValues(filterValues); - return contactsList; - } - - public PaginationParameter newContactsPaginationParameter(int pageNumber, int pageSize) { - PaginationParameter result = PaginationParameter.of(pageNumber, pageSize); - return result; - } - - public UpdateContactCommand newUpdateContactCommand(AuthenticatedWaoUser authenticatedWaoUser, Optional<String> optionalContactId) { - - //FIXME Should we apply some security rules (can create, update, import) ? - //Preconditions.checkState(authenticatedWaoUser.isAuthorizedToCreateSampleRow()); - - UpdateContactCommand updateContactCommand = new UpdateContactCommand(); - - updateContactCommand.setAdmin(authenticatedWaoUser.isAdmin()); - - Contact contact; - - if (optionalContactId.isPresent()) { - - String contactId = optionalContactId.get(); - - contact = getContact(contactId); - - updateContactCommand.setContact(contact); - - updateContactCommand.setCreation(false); - - String mainObserverId = contact.getMainObserver().getTopiaId(); - updateContactCommand.setMainObserverId(mainObserverId); - Set<String> secondaryObserversTopiaIds = contact.getSecondaryObserversTopiaIds(); - updateContactCommand.setSecondaryObserverIds(secondaryObserversTopiaIds); - - } else { - - contact = new ContactImpl(); - - contact.setObsProgram(authenticatedWaoUser.getObsProgram()); - - updateContactCommand.setContact(contact); - - updateContactCommand.setCreation(true); - } - - return updateContactCommand; - } - - public Contact getContact(String contactId) { - return getContactDao().forTopiaIdEquals(contactId).findUnique(); - } - - public InputStream exportContacts(ContactsFilter filter) { - ContactTopiaDao dao = getContactDao(); - - List<Contact> contacts = dao.forFilter(filter, true).findAll(); - - ExportModel<Contact> exportModel = ObsMerContactImportExportModel.forExport(getLocale(), - filter.getSampleRowFilter().getObsProgram()); - - Export<Contact> export = Export.newExport(exportModel, contacts); - - try { - - String csvContent = export.toString(Charsets.UTF_8); - - InputStream csvInputStream = IOUtils.toInputStream(csvContent, Charsets.UTF_8); - - return csvInputStream; - - } catch (Exception e) { - throw new WaoTechnicalException(e); - } - } - - public void importContacts(AuthenticatedWaoUser authenticatedWaoUser, - InputStream csv) throws ImportErrorException { - - ObsProgram obsProgram = authenticatedWaoUser.getObsProgram(); - - List<SampleRow> sampleRows = - getSampleRowDao().forObsProgramOrdinalEquals(obsProgram.ordinal()).findAll(); - List<WaoUser> waoUsers = getWaoUserDao().findAll(); - List<Boat> boats = getBoatDao().findAll(); - List<ContactStateMotif> motives = getContactStateMotifDao().findAll(); - - Locale l = getLocale(); - ImportModel<Contact> contactImportModel = - ObsMerContactImportExportModel.forImport(l, - obsProgram, - waoUsers, - sampleRows, - boats, - motives); - - ImportConf importConf = new ImportConf(); - importConf.setStrictMode(true); - - Import2<Contact> contactImport = Import2.newImport(importConf, contactImportModel, csv); - - for (ImportRow<Contact> contactRow : contactImport) { - - if (!contactRow.isValid()) { - // throw first error - Set<AbstractImportErrorInfo<Contact>> errors = contactRow.getErrors(); - AbstractImportErrorInfo<Contact> errorInfo = errors.iterator().next(); - throw new ImportErrorException(errorInfo.getCause()); - } - long lineNumber = contactRow.getLineNumber(); - - Contact contact = contactRow.getBean(); - - String contactId = contact.getTopiaId(); - - if (StringUtils.isEmpty(contactId)) { - contactId = null; - } - - Optional<String> optionalContactId = Optional.fromNullable(contactId); - UpdateContactCommand updateContactCommand = newUpdateContactCommand(authenticatedWaoUser, - optionalContactId); - - if (updateContactCommand.isCreation()) { - - updateContactCommand.setContact(contact); - - // Prevent that someone who is not admin change data that only admin - // must be able to modify - if ( ! authenticatedWaoUser.isAdmin()) { - contact.setCommentAdmin(null); - contact.setValidationProgram(null); - contact.setDataReliability(DataReliability.UNKNOWN); - } - - } else { - - Contact contactToUpdate = updateContactCommand.getContact(); - Binder<Contact, Contact> binder = BinderFactory.newBinder(Contact.class); - binder.copy(contact, contactToUpdate, - Contact.PROPERTY_CREATION_DATE, - Contact.PROPERTY_MAIN_OBSERVER, - Contact.PROPERTY_SECONDARY_OBSERVERS, - "contactState", - Contact.PROPERTY_OBSERVATION_BEGIN_DATE, - Contact.PROPERTY_OBSERVATION_END_DATE, - Contact.PROPERTY_DATA_INPUT_DATE, - Contact.PROPERTY_COMMENT, - Contact.PROPERTY_COMMENT_COORDINATOR, - Contact.PROPERTY_COMMENT_ADMIN, - Contact.PROPERTY_BOAT, - Contact.PROPERTY_VALIDATION_COMPANY, - Contact.PROPERTY_VALIDATION_PROGRAM, - Contact.PROPERTY_SAMPLE_ROW, - Contact.PROPERTY_MAMMALS_OBSERVATION, - Contact.PROPERTY_MAMMALS_CAPTURE, - Contact.PROPERTY_MAMMALS_INFO, - Contact.PROPERTY_CONTACT_STATE_MOTIF, - Contact.PROPERTY_RESTITUTION, - Contact.PROPERTY_OBSERVED_DATA_CONTROL); - - // Prevent that someone who is not admin change data that only admin - // must be able to modify - if ( ! authenticatedWaoUser.isAdmin()) { - contactToUpdate.setCommentAdmin(contact.getCommentAdmin()); - contactToUpdate.setValidationProgram(contact.getValidationProgram()); - contactToUpdate.setDataReliability(contact.getDataReliability()); - } - - } - - try { - validate(authenticatedWaoUser, updateContactCommand, false); - } catch (ContactNotUpdatableException e) { - String message = l(l, "wao.import.contact.failure.not.updatable", lineNumber); - throw new ImportErrorException(message); - } catch (UnwantedContactContactStateMotifException e) { - String message = l(l, "wao.import.contact.failure.unwantedContactStateMotif", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactNbObservantsException e) { - String state = WaoUtils.l(l, e.getContact().getContactState()); - String message = l(l, "wao.import.contact.failure.missingObserver", lineNumber, state); - throw new ImportErrorException(message); - } catch (MissingContactObservationEndDateException e) { - String state = WaoUtils.l(l, e.getContact().getContactState()); - String message = l(l, "wao.import.contact.failure.missingObservationEndDate", lineNumber, state); - throw new ImportErrorException(message); - } catch (ContactDataInputDateBeforeObservationEndDateException e) { - String message = l(l, "wao.import.contact.failure.dataInputDateBeforeObservationEndDate", lineNumber); - throw new ImportErrorException(message); - } catch (InvalidContactObservationBeginDateException e) { - String message = l(l, "wao.import.contact.failure.invalidObservationBeginDate", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactRestitutionException e) { - String message = l(l, "wao.import.contact.failure.missingRestitution", lineNumber); - throw new ImportErrorException(message); - } catch (ContactDataInputDateAfterTodayException e) { - String message = l(l, "wao.import.contact.failure.dataInputDateAfterToday", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactCommentException e) { - String state = WaoUtils.l(l, e.getContact().getContactState()); - String message = l(l, "wao.import.contact.failure.missingComment", state, lineNumber); - throw new ImportErrorException(message); - } catch (MismatchContactMainObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - String message = l(l, "wao.import.contact.failure.mismatchCompanyForObserver", lineNumber, observerLogin, companyName); - throw new ImportErrorException(message); - } catch (ContactRestitutionDateBeforeDataInputDateException e) { - String message = l(l, "wao.import.contact.failure.transmissionDateBeforeDataInputDate", lineNumber); - throw new ImportErrorException(message); - } catch (ContactObservationEndDateBeforeBeginDateException e) { - String message = l(l, "wao.import.contact.failure.observationEndDateBeforeBeginDate", lineNumber); - throw new ImportErrorException(message); - } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { - String message = l(l, "wao.import.contact.failure.duplicatedMainObserverInSecondaryObservers", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactDataReliabilityException e) { - String message = l(l, "wao.import.contact.failure.missingDataReliability", lineNumber); - throw new ImportErrorException(message); - } catch (MismatchContactSecondaryObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - String message = l(l, "wao.import.contact.failure.mismatchCompanyForObserver", lineNumber, observerLogin, companyName); - throw new ImportErrorException(message); - } catch (MissingContactObservedDataControlException e) { - String message = l(l, "wao.import.contact.failure.missingObservedDataControl", lineNumber); - throw new ImportErrorException(message); - } catch (ContactWithObservedDataControlToCorrectionAskedException e) { - String message = l(l, "wao.import.contact.failure.observedDataControlToCorrectionAsked", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactStateMotifException e) { - String message = l(l, "wao.import.contact.failure.missingContactStateMotif", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactDataInputDateException e) { - String message = l(l, "wao.import.contact.failure.missingDataInputDate", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactMainObserverException e) { - String message = l(l, "wao.import.contact.failure.missingMainObserver", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactCommentAdminException e) { - String dataReliability = WaoUtils.l(l, e.getContact().getDataReliability()); - String message = l(l, "wao.import.contact.failure.missingCommentAdmin", lineNumber, dataReliability); - throw new ImportErrorException(message); - } catch (ContactObservationEndDateAfterTodayException e) { - String message = l(l, "wao.import.contact.failure.observationEndDateAfterToday", lineNumber); - throw new ImportErrorException(message); - } catch (MissingContactObservationBeginDateException e) { - String state = WaoUtils.l(l, e.getContact().getContactState()); - String message = l(l, "wao.import.contact.failure.missingObservationBeginDate", lineNumber, state); - throw new ImportErrorException(message); - } catch (MissingContactMammalsInfoException e) { - String message = l(l, "wao.import.contact.failure.missingContactMammalsInfo", lineNumber); - throw new ImportErrorException(message); - } - - save0(updateContactCommand); - } - - commit(); - } - - public void preValidate(UpdateContactCommand updateContactCommand) { - - String mainObserverId = updateContactCommand.getMainObserverId(); - - WaoUser mainObserver = getWaoUserDao().forTopiaIdEquals(mainObserverId).findUnique(); - updateContactCommand.getContact().setMainObserver(mainObserver); - - List<WaoUser> secondaryObservers = getWaoUserDao().forTopiaIdIn(updateContactCommand.getSecondaryObserverIds()).findAll(); - updateContactCommand.getContact().setSecondaryObservers(new HashSet<>(secondaryObservers)); - - } - - public void validate(AuthenticatedWaoUser authenticatedWaoUser, - UpdateContactCommand updateContactCommand, - boolean needUpdate) throws - ContactNotUpdatableException, - MissingContactMainObserverException, - MismatchContactMainObserverCompanyException, - DuplicatedContactMainObserverInSecondaryObserversException, - MismatchContactSecondaryObserverCompanyException, - InvalidContactObservationBeginDateException, - ContactObservationEndDateBeforeBeginDateException, - ContactObservationEndDateAfterTodayException, - ContactDataInputDateBeforeObservationEndDateException, - ContactDataInputDateAfterTodayException, - MissingContactCommentException, - MissingContactObservationBeginDateException, - MissingContactObservationEndDateException, - MissingContactNbObservantsException, - MissingContactStateMotifException, - UnwantedContactContactStateMotifException, - MissingContactObservedDataControlException, - MissingContactMammalsInfoException, - ContactWithObservedDataControlToCorrectionAskedException, - MissingContactRestitutionException, - MissingContactDataInputDateException, - ContactRestitutionDateBeforeDataInputDateException, - MissingContactDataReliabilityException, - MissingContactCommentAdminException { - - if (needUpdate) { - Preconditions.checkState(!updateContactCommand.isCreation()); - } - - //FIXME Do some security checks about authenticatedWaoUser - - // Check if contact can be updated - boolean canUpdateContact = updateContactCommand.canUpdateContact(authenticatedWaoUser); - if (!canUpdateContact) { - throw new ContactNotUpdatableException(); - } - - // Check if a validation controls are required - boolean mustValidateContact = updateContactCommand.mustValidateContact(); - - if (mustValidateContact) { - - // Pass validation controls - Contact contact = updateContactCommand.getContact(); - - Company company = contact.getSampleRow().getCompany(); - - WaoUser mainObserver = contact.getMainObserver(); - - { - //--- - // mainObserver - //--- - - if (mainObserver == null) { - throw new MissingContactMainObserverException(contact); - } - - boolean observerWorksForCompanyInSampleRow = mainObserver.getCompany().equals(company); - if (!observerWorksForCompanyInSampleRow) { - throw new MismatchContactMainObserverCompanyException(contact, mainObserver, company); - } - } - - if (contact.isSecondaryObserversNotEmpty()) { - - //--- - // secondaryObservers - //--- - - if (contact.getSecondaryObservers().contains(mainObserver)) { - throw new DuplicatedContactMainObserverInSecondaryObserversException(contact); - } - - for (WaoUser observer : contact.getSecondaryObservers()) { - boolean observerWorksForCompanyInSampleRow = observer.getCompany().equals(company); - if (!observerWorksForCompanyInSampleRow) { - throw new MismatchContactSecondaryObserverCompanyException(contact, observer, company); - } - } - } - - Date observationBeginDate = contact.getObservationBeginDate(); - Date observationEndDate = contact.getObservationEndDate(); - Date dataInputDate = contact.getDataInputDate(); - - SampleRow sampleRow = contact.getSampleRow(); - - if (observationBeginDate != null) { - - //--- - // observationBeginDate - //--- - - SampleMonth month = sampleRow.getSampleMonth(observationBeginDate); - boolean operationBeginDateIsValid = month != null; - - if (!operationBeginDateIsValid) { - throw new InvalidContactObservationBeginDateException(contact); - } - } - - Date currentDate = serviceContext.getNow(); - - if (observationEndDate != null) { - - //--- - // observationEndDate - //--- - - if (observationBeginDate != null - && observationEndDate.before(observationBeginDate)) { - throw new ContactObservationEndDateBeforeBeginDateException(contact); - } - - if (observationEndDate.after(currentDate)) { - throw new ContactObservationEndDateAfterTodayException(contact, currentDate); - } - - } - - if (dataInputDate != null) { - - //--- - // dataInputDate - //--- - - if (observationEndDate != null) { - - // Here, we check that the date input date is after the end of the - // observation. Since the first is a day (at 00:00) and the second - // is date-time, there may be a bug if the data input day is the same - // as the end of observation - boolean dataInputDateAfterObservationEndDate = - observationEndDate.after(DateUtil.setMaxTimeOfDay(dataInputDate)); - - if (dataInputDateAfterObservationEndDate) { - throw new ContactDataInputDateBeforeObservationEndDateException(contact); - } - } - - if (dataInputDate.after(currentDate)) { - throw new ContactDataInputDateAfterTodayException(contact, currentDate); - } - } - - //--- - // contactState - //--- - - ContactState contactState = contact.getContactState(); - - boolean contactMustHaveAMotif = false; - switch (contactState) { - case OBSERVATION_CANCELLED: - - // Non abouti - - if (StringUtils.isBlank(contact.getComment())) { - throw new MissingContactCommentException(contact); - } - break; - case OBSERVATION_DONE: - - // Observation réalisée - - if (observationBeginDate == null) { - throw new MissingContactObservationBeginDateException(contact); - } - if (observationEndDate == null) { - throw new MissingContactObservationEndDateException(contact); - } - if (contact.getNbObservants() == 0) { - throw new MissingContactNbObservantsException(contact); - } - break; - - case CONTACT_REFUSED: - contactMustHaveAMotif = true; - break; - case CONTACT_DEFINITELY_REFUSED: - contactMustHaveAMotif = true; - break; - - } - - //--- - // contactStateMotif - //--- - - if (contactMustHaveAMotif && contact.getContactStateMotif() == null) { - throw new MissingContactStateMotifException(contact); - } - - if (!contactMustHaveAMotif && contact.getContactStateMotif() != null) { - throw new UnwantedContactContactStateMotifException(contact); - } - - if (contact.isMammalsCapture() && StringUtils.isBlank(contact.getMammalsInfo())) { - throw new MissingContactMammalsInfoException(contact); - } - - if (BooleanUtils.isTrue(contact.getValidationCompany())) { - - //--- - // validationCompany - //--- - - if (ContactState.OBSERVATION_DONE == contactState) { - if (contact.getObservedDataControl() == null) { - throw new MissingContactObservedDataControlException(contact); - } else if (contact.getObservedDataControl().equals(ObservedDataControl.CORRECTION_ASKED)) { - throw new ContactWithObservedDataControlToCorrectionAskedException(contact); - } - } - - // Pour valider un contact société, il faut que le contact aie une date de transmission - Date restitution = contact.getRestitution(); - if (ObservedDataControl.ACCEPTED == contact.getObservedDataControl() && restitution == null) { - throw new MissingContactRestitutionException(contact); - } - if (dataInputDate == null && restitution != null) { - throw new MissingContactDataInputDateException(contact); - } - if (dataInputDate != null && restitution != null && restitution.before(dataInputDate)) { - throw new ContactRestitutionDateBeforeDataInputDateException(contact); - } - } - - DataReliability dataReliability = contact.getDataReliability(); - - if (dataReliability != null && dataReliability.isCommentRequired() && StringUtils.isBlank(contact.getCommentAdmin())) { - throw new MissingContactCommentAdminException(contact); - } - - if (BooleanUtils.isTrue(contact.getValidationProgram())) { - - //--- - // validationProgram - //--- - - // it's an admin validation, data-reliability field must be filled - - if (dataReliability == null || DataReliability.UNKNOWN == dataReliability) { - throw new MissingContactDataReliabilityException(contact); - } - } - } - } - - public void save(UpdateContactCommand updateContactCommand, - boolean needUpdate) throws ContactNotUpdatableException { - - if (needUpdate) { - Preconditions.checkState(!updateContactCommand.isCreation()); - } - - save0(updateContactCommand); - - commit(); - - updateAllegroWalletIfNecessary(updateContactCommand); - - notifyMammalsObservationIfNecessary(updateContactCommand); - - } - - protected void notifyMammalsObservationIfNecessary(UpdateContactCommand updateContactCommand) { - - if (updateContactCommand.isMammalsInfosChanged()) { - - Contact contact = updateContactCommand.getContact(); - - MammalsObservationEmail email = getEmailService().newMammalsObservationEmail(); - email.setContact(contact); - - // now trying to find to what user we need to send the mail - WaoUserTopiaDao userDao = getWaoUserDao(); - // users contains all the user we need to notify for the capture - List<WaoUser> waoUsers = userDao.forMammalsNotificationsEquals(true).addEquals(WaoUser.PROPERTY_ACTIVE, true).findAll(); - - for (WaoUser waoUser : waoUsers) { - if (StringUtil.isEmail(waoUser.getLogin())) { - email.addBcc(waoUser); - } else { - if (log.isWarnEnabled()) { - log.warn("will not send mammals capture notification to user " + waoUser + ". login is not an email"); - } - } - } - - getEmailService().send(email); - - } - - } - - public void delete(String contactId) throws IllegalDeletionException { - - Contact contact = getContact(contactId); - - // Execute delete - ContactTopiaDao dao = getContactDao(); - - Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> allUsages = dao.findAllUsages(contact); - - if (!allUsages.isEmpty()) { - throw new IllegalDeletionException(allUsages); - } - - ObsMerSamplingPlanService samplingPlanService = newService(ObsMerSamplingPlanService.class); - - samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); - - dao.delete(contact); - - commit(); - } - - protected void save0(UpdateContactCommand updateContactCommand) { - - // Get contact to validate (must exist) - Contact contact = updateContactCommand.getContact(); - - ContactTopiaDao dao = getContactDao(); - - ObsMerSamplingPlanService samplingPlanService = newService(ObsMerSamplingPlanService.class); - - if (updateContactCommand.isCreation()) { - - //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. - - ElligibleBoatTopiaDao elligibleDAO = getElligibleBoatDao(); - ElligibleBoat elligible = elligibleDAO.findUniqueOrNull(contact); - - if (elligible == null) { - // Create new elligible boat not active in a global way - elligible = elligibleDAO.create(contact); - } - elligible.setCompanyActive(Boolean.TRUE); - - if (contact.getCreationDate() == null) { - contact.setCreationDate(serviceContext.getNow()); - } - - samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); - - dao.create(contact); - - } else { - - samplingPlanService.recomputeSampleRowEstimatedAndRealTides(contact.getSampleRow()); - - dao.update(contact); - } - - } - - protected void updateAllegroWalletIfNecessary(UpdateContactCommand updateContactCommand) { - - Contact contact = updateContactCommand.getContact(); - ContactState contactState = contact.getContactState(); - ObsProgram obsProgram = contact.getObsProgram(); - - boolean addBoatToObserversAllegroWallet = false; - - if (obsProgram == ObsProgram.OBSMER) { - addBoatToObserversAllegroWallet = contactState == ContactState.OBSERVATION_DONE - || contactState == ContactState.OBSERVATION_EXPECTED; - } else if (obsProgram == ObsProgram.OBSVENTE) { - addBoatToObserversAllegroWallet = ContactState.OBSERVATION_DONE == contactState; - } - - if (addBoatToObserversAllegroWallet) { - - Boat boat = contact.getBoat(); - - String info; - - if (contactState == ContactState.OBSERVATION_EXPECTED) { - info = I18n.l( - serviceContext.getLocale(), - "wao.email.addBoatToUserAllegroWallet.contactExpected", - WaoUtils.formatDate(serviceContext.getLocale(), contact.getObservationBeginDate())); - } else if (contactState == ContactState.OBSERVATION_DONE) { - info = I18n.l( - serviceContext.getLocale(), - "wao.email.addBoatToUserAllegroWallet.contactDone", - WaoUtils.formatDateTime(serviceContext.getLocale(), contact.getObservationBeginDate()), - WaoUtils.formatDateTime(serviceContext.getLocale(), contact.getObservationEndDate())); - } else { - throw new IllegalStateException(contactState + " should not lead to a mail sent"); - } - - // in obsvente, only the main observer - Collection<WaoUser> observers; - if (ObsProgram.OBSVENTE.equals(obsProgram)) { - observers = ImmutableSet.of(contact.getMainObserver()); - } else if (ObsProgram.OBSMER.equals(obsProgram)) { - observers = contact.getAllObservers(); - } else { - throw new IllegalStateException(); - } - - EmailService emailService = getEmailService(); - - WaoUserTopiaDao waoUserDao = getWaoUserDao(); - - for (WaoUser observer : observers) { - - boolean boatAlreadyInWallet = observer.containsAllegroWallet(boat); - - if (boatAlreadyInWallet) { - - if (log.isInfoEnabled()) { - log.info("user " + observer + " already has " + boat + " in his allegroWallet"); - } - - } else { - - if (log.isInfoEnabled()) { - log.info("user " + observer + " miss " + boat + " in his allegro wallet, adding"); - } - - String observerLogin = observer.getLogin(); - String emailToUpdateAllegroWallets = getApplicationConfig().getEmailToUpdateAllegroWallets(); - - AddBoatToUserAllegroWalletEmail email = - emailService.newAddBoatToUserAllegroWalletEmail(); - - email.setBoat(boat); - email.setObserver(observer); - email.setInfo(info); - email.setObsProgram(contact.getObsProgram()); - - if ( ! StringUtil.isEmail(observerLogin)) { - if (log.isInfoEnabled()) { - log.info("user login is not a email, won't send anything: " + observerLogin + " email=" + email); - } - } else if ( ! observer.isActive()) { - if (log.isInfoEnabled()) { - log.info("observer is no longer active, won't send " + email); - } - } else if (StringUtils.isBlank(emailToUpdateAllegroWallets)) { - if (log.isInfoEnabled()) { - log.info("no email to update allegro wallets provided in configuration, won't send " + email); - } - } else if ( ! StringUtil.isEmail(emailToUpdateAllegroWallets)) { - if (log.isWarnEnabled()) { - log.warn("email to update allegro wallets provided in configuration is not valid, won't send " + emailToUpdateAllegroWallets); - } - } else { - - email.addBcc(observer); - - email.addTo(emailToUpdateAllegroWallets); - - emailService.send(email); - - observer.addAllegroWallet(boat); - waoUserDao.update(observer); - commit(); - - } - } - } - } - } - - public Contact createContact(AuthenticatedWaoUser authenticatedWaoUser, String sampleRowId, String boatId) { - - if (log.isInfoEnabled()) { - log.info(authenticatedWaoUser.getWaoUser() + " is creating a contact for " + sampleRowId + " and " + boatId); - } - - UpdateContactCommand updateContactCommand = newUpdateContactCommand(authenticatedWaoUser, Optional.<String>absent()); - - Boat boat = getBoatDao().findByTopiaId(boatId); - Preconditions.checkState(boat.isActive(), "boat must be active"); - - SampleRow sampleRow = getSampleRowDao().findByTopiaId(sampleRowId); - ObsProgram obsProgram = sampleRow.getObsProgram(); - - WaoUser observer = authenticatedWaoUser.getWaoUser(); - Contact mostRecentContactOrNull = getContactDao().findMostRecentContactOrNull(obsProgram, boatId, observer.getCompany().getTopiaId()); - Preconditions.checkState( - mostRecentContactOrNull == null || mostRecentContactOrNull.getContactState().isFinalState(), - "contact already exists"); - - Date now = serviceContext.getNow(); - - Contact newContact = updateContactCommand.getContact(); - newContact.setDataReliability(DataReliability.UNKNOWN); - newContact.setBoat(boat); - newContact.setMainObserver(observer); - newContact.setSampleRow(sampleRow); - newContact.setCreationDate(now); - - // initial contact state depends on the program - if (obsProgram == ObsProgram.OBSMER) { - newContact.setContactState(ContactState.CONTACT_START); - } else if (obsProgram == ObsProgram.OBSVENTE) { - newContact.setContactState(ContactState.OBSERVATION_EXPECTED); - } - - // we can suppose a new contact default values are the one - // expected in the sampling plan - - if (newContact.getObsProgram() == ObsProgram.OBSVENTE) { - // we hope in this contact, user used expected sampling strategy - newContact.setSamplingStrategy(sampleRow.getSamplingStrategy()); - } - - // In the case of ObsVente, we may have a user who wants to create - // multiple contact for a same day. Here we try, to ease the input - // of data by trying to pre-fill some field using data given - // in a previous entered contact - - if (newContact.getObsProgram() == ObsProgram.OBSVENTE) { - // try to pre-fill some field for user-experience - - // let's try to find a recent similar contact - Map<String, Object> properties = new HashMap<>(); - properties.put(Contact.PROPERTY_OBS_PROGRAM_ORDINAL, newContact.getObsProgram().ordinal()); - properties.put(Contact.PROPERTY_SAMPLE_ROW, sampleRow); - properties.put(Contact.PROPERTY_MAIN_OBSERVER, observer); - - List<Contact> candidates = getContactDao().forProperties(properties).findAll(); - - Contact similarContact = null; // to be found among candidates - for (Contact candidate : candidates) { - if (DateUtil.getDifferenceInDays(candidate.getCreationDate(), now) <= 1) { - similarContact = candidate; - } - } - - if (log.isDebugEnabled()) { - String logMessage; - if (similarContact == null) { - logMessage = "no similar contact found"; - } else { - logMessage = "similar contact found to pre-fill values of contact : " - + similarContact.getTopiaId() + " boat = " + similarContact.getBoat().getName(); - } - log.debug(logMessage); - } - - if (similarContact != null) { - newContact.setObservationBeginDate(similarContact.getObservationBeginDate()); - newContact.setObservationEndDate(similarContact.getObservationEndDate()); - newContact.setTerrestrialLocation(similarContact.getTerrestrialLocation()); - newContact.clearSecondaryObservers(); - newContact.addAllSecondaryObservers(similarContact.getSecondaryObservers()); - newContact.setDataInputDate(similarContact.getDataInputDate()); - } - } - - save0(updateContactCommand); - - commit(); - - return newContact; - - } - -} Modified: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/SynthesisService.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/SynthesisService.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/SynthesisService.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -46,7 +46,7 @@ public ContactsFilter newFilter(AuthenticatedWaoUser authenticatedWaoUser) { - ContactsService contactsService = newService(ObsMerContactsService.class); + ContactsService contactsService = newService(ContactsService.class); ContactsFilter newFilter = contactsService.newContactFilter(authenticatedWaoUser); Modified: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/UpdateContactCommand.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/UpdateContactCommand.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/UpdateContactCommand.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -57,6 +57,8 @@ protected Set<String> secondaryObserverIds = new HashSet<>(); + private String terrestrialLocationId; + public boolean isCreation() { return creation; } @@ -180,4 +182,12 @@ public void setSecondaryObserverIds(Set<String> secondaryObserverIds) { this.secondaryObserverIds = secondaryObserverIds; } + + public String getTerrestrialLocationId() { + return terrestrialLocationId; + } + + public void setTerrestrialLocationId(String terrestrialLocationId) { + this.terrestrialLocationId = terrestrialLocationId; + } } Modified: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/administration/ReferentialService.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/administration/ReferentialService.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/administration/ReferentialService.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -96,6 +96,7 @@ import java.io.InputStream; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -1130,4 +1131,21 @@ return dcf5Codes; } + + public List<TerrestrialLocation> getTerrestrialLocationInDistricts(Collection<TerrestrialLocation> terrestrialDistricts) { + + Set districtCodes = new HashSet(); + for (TerrestrialLocation terrestrialDistrict : terrestrialDistricts) { + Preconditions.checkArgument(terrestrialDistrict.isDistrict()); + districtCodes.add(terrestrialDistrict.getDistrictCode()); + } + + TerrestrialLocationTopiaDao dao = getTerrestrialLocationDao(); + + List<TerrestrialLocation> locationsInDistricts = dao.forLocationTypeIn(ImmutableSet.of(LocationType.PORT, LocationType.AUCTION)).addIn(TerrestrialLocation.PROPERTY_DISTRICT_CODE, districtCodes).findAll(); + + return locationsInDistricts; + + } + } Deleted: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,332 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2011 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ -package fr.ifremer.wao.services.service.csv; - -import fr.ifremer.wao.entity.Boat; -import fr.ifremer.wao.entity.Company; -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.entity.ContactImpl; -import fr.ifremer.wao.entity.ContactState; -import fr.ifremer.wao.entity.ContactStateMotif; -import fr.ifremer.wao.entity.DataReliability; -import fr.ifremer.wao.entity.LocationType; -import fr.ifremer.wao.entity.ObsDebCode; -import fr.ifremer.wao.entity.ObsProgram; -import fr.ifremer.wao.entity.ObservationType; -import fr.ifremer.wao.entity.ObservedDataControl; -import fr.ifremer.wao.entity.SampleRow; -import fr.ifremer.wao.entity.TerrestrialLocation; -import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.services.service.csv.operations.BoatParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.CompanyParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.ContactStateMotivesParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.I18nAbleParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.LocationTypeParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.ObsDebCodeParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.SampleRowParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.UserParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.UsersParserFormatter; -import org.apache.commons.lang3.StringUtils; -import org.nuiton.csv.Common; -import org.nuiton.csv.ExportableColumn; -import org.nuiton.csv.ImportExportModel; -import org.nuiton.csv.ImportableColumn; -import org.nuiton.csv.ModelBuilder; -import org.nuiton.csv.ValueFormatter; -import org.nuiton.csv.ValueGetter; -import org.nuiton.csv.ValueGetterSetter; -import org.nuiton.csv.ValueParserFormatter; -import org.nuiton.i18n.I18n; - -import java.text.ParseException; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -public class ContactImportExportModel implements ImportExportModel<Contact> { - - /** will get terrestrial location depending on location code and pushed location type */ - 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) { - String code = ""; - if (terrestrialLocation != null) { - code = terrestrialLocation.getCode(); - } - return code; - } - - @Override - public TerrestrialLocation parse(String code) throws ParseException { - if (indexedLocations == null) { - indexedLocations = new HashMap<>(); - for (TerrestrialLocation terrestrialLocation : terrestrialLocations) { - LocationType locationType = terrestrialLocation.getLocationType(); - Map<String, TerrestrialLocation> locationsForType = indexedLocations.get(locationType); - if (locationsForType == null) { - locationsForType = new HashMap<>(); - } - locationsForType.put(terrestrialLocation.getCode(), terrestrialLocation); - indexedLocations.put(locationType, locationsForType); - } - } - TerrestrialLocation terrestrialLocation = null; - if (StringUtils.isNotBlank(code)) { - LocationType locationType; - try { - locationType = locationTypeGetter.get(null); - } catch (Exception e) { - throw new RuntimeException(e); - } - if (locationType == null) { - throw new IllegalArgumentException(I18n.t("wao.import.contact.failure.locationTypeMissing")); - } - terrestrialLocation = indexedLocations.get(locationType).get(code); - if (terrestrialLocation == null) { - throw new IllegalArgumentException(I18n.t("wao.import.contact.failure.wrongTerrestrialLocation", - locationType.toString(), code)); - } - } - return terrestrialLocation; - } - } - - protected final Locale locale; - - protected ObsProgram obsProgram; - - protected List<WaoUser> waoUsers; - - protected List<TerrestrialLocation> terrestrialLocations; - - protected List<SampleRow> sampleRows; - - protected List<Boat> boats; - - protected List<ObsDebCode> obsDebCodes; - - protected List<ContactStateMotif> motives; - - /** for export */ - public ContactImportExportModel(Locale locale, ObsProgram obsProgram) { - this.locale = locale; - this.obsProgram = obsProgram; - } - - /** for import */ - public ContactImportExportModel(Locale locale, ObsProgram obsProgram, List<WaoUser> waoUsers, - List<TerrestrialLocation> terrestrialLocations, - List<SampleRow> sampleRows, List<Boat> boats, - List<ObsDebCode> obsDebCodes, List<ContactStateMotif> motives) { - this.locale = locale; - this.obsProgram = obsProgram; - this.waoUsers = waoUsers; - this.terrestrialLocations = terrestrialLocations; - this.sampleRows = sampleRows; - this.boats = boats; - this.obsDebCodes = obsDebCodes; - this.motives = motives; - } - - @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<>(); - modelBuilder.newColumnForImportExport("CONTACT_ID", Contact.PROPERTY_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(locale, waoUsers)); - modelBuilder.newColumnForImportExport("CONTACT_OBSERVATEURS_SECONDAIRES", Contact.PROPERTY_SECONDARY_OBSERVERS, new UsersParserFormatter(locale, waoUsers)); - modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_NOMS"); - modelBuilder.newColumnForExport( - "CONTACT_OBSERVATEURS_NOMS", - "allObservers", - new ValueFormatter<List<WaoUser>>() { - @Override - public String format(List<WaoUser> value) { - List<String> fullNames = new LinkedList<>(); - for (WaoUser waoUser : value) { - fullNames.add(waoUser.getFullName()); - } - return StringUtils.join(fullNames, ", "); - } - } - ); - modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_SOCIETE"); - modelBuilder.newColumnForExport( - "CONTACT_OBSERVATEURS_SOCIETE", - new ValueGetter<Contact, Company>() { - @Override - public Company get(Contact contact) { - return contact.getMainObserver().getCompany(); - } - }, - new CompanyParserFormatter(locale, null) - ); - modelBuilder.newColumnForImportExport("CONTACT_ETAT", "contactState", new I18nAbleParserFormatter<>(locale, 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("NAVIRE_IMMATRICULATION", Contact.PROPERTY_BOAT, new BoatParserFormatter(boats, locale)); - modelBuilder.newIgnoredColumn("NAVIRE_NOM"); - modelBuilder.newColumnForExport("NAVIRE_NOM", new ValueGetter<Contact, String>() { - @Override - public String get(Contact contact) throws Exception { - return contact.getBoat().getName(); - } - }); - modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_SOCIETE", Contact.PROPERTY_VALIDATION_COMPANY, Common.BOOLEAN); - modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_PROGRAMME", Contact.PROPERTY_VALIDATION_PROGRAM, Common.BOOLEAN); - - modelBuilder.newColumnForImportExport("PLAN_CODE", Contact.PROPERTY_SAMPLE_ROW, new SampleRowParserFormatter(locale, sampleRows)); - - if (obsProgram == ObsProgram.OBSMER) { - modelBuilder.newColumnForImportExport("CONTACT_QUALITE_DONNEE", "dataReliability", - new I18nAbleParserFormatter<>(locale, DataReliability.values())); - modelBuilder.newColumnForImportExport("CONTACT_OBSERVATION_MAMMIFERE", Contact.PROPERTY_MAMMALS_OBSERVATION, Common.BOOLEAN); - modelBuilder.newColumnForImportExport("CONTACT_CAPTURE_ACCIDENTELLE", Contact.PROPERTY_MAMMALS_CAPTURE, Common.BOOLEAN); - modelBuilder.newIgnoredColumn("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS"); - modelBuilder.newColumnForExport("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS", Contact.PROPERTY_MAMMALS_INFO); - modelBuilder.newColumnForImportExport("CONTACT_ETAT_MOTIF_CODE", Contact.PROPERTY_CONTACT_STATE_MOTIF, new ContactStateMotivesParserFormatter(locale, motives)); - modelBuilder.newIgnoredColumn("CONTACT_ETAT_MOTIF_NOM"); - modelBuilder.newColumnForExport("CONTACT_ETAT_MOTIF_NOM", new ValueGetter<Contact, String>() { - @Override - public String get(Contact contact) throws Exception { - String name = ""; - if (contact.getContactStateMotif() != null) { - name = contact.getContactStateMotif().getName(); - } - return name; - } - }); - modelBuilder.newColumnForImportExport("CONTACT_TRANSMISSION_RESTITUTION", Contact.PROPERTY_RESTITUTION, Common.DAY); - - List<ObservedDataControl> observedDataControlsValues = new LinkedList<>(); - Collections.addAll(observedDataControlsValues, ObservedDataControl.values()); - observedDataControlsValues.add(null); - I18nAbleParserFormatter<ObservedDataControl> valueParserFormatter = new I18nAbleParserFormatter<>(locale, observedDataControlsValues); - valueParserFormatter.setAcceptNullValues(true); - modelBuilder.newColumnForImportExport("CONTACT_DONNEES_ALLEGRO_VALIDEES", Contact.PROPERTY_OBSERVED_DATA_CONTROL, valueParserFormatter); - } else { - // FIXME 20110606 bleny contact.getTerrestrialLocation() may be null, export will fail - - // terrestrial location for both ObsVente and ObsDeb - ValueGetterSetter<Contact, LocationType> locationTypeGetter = new Common.ValueSaver<>(); - LocationTypeParserFormatter locationTypeParserFormatter = new LocationTypeParserFormatter(locale); - modelBuilder.newMandatoryColumn( - "CONTACT_LIEU_TYPE", - locationTypeParserFormatter, - locationTypeGetter); - modelBuilder.newColumnForExport( - "CONTACT_LIEU_TYPE", - new ValueGetter<Contact, LocationType>() { - @Override - public LocationType get(Contact contact) throws Exception { - LocationType locationType = null; - if (contact.getTerrestrialLocation() != null) { - locationType = contact.getTerrestrialLocation() - .getLocationType(); - } - return locationType; - } - }, - locationTypeParserFormatter - ); - modelBuilder.newColumnForImportExport( - "CONTACT_LIEU_CODE", - Contact.PROPERTY_TERRESTRIAL_LOCATION, - new TerrestrialLocationParserFormatter(terrestrialLocations, locationTypeGetter)); - - modelBuilder.newIgnoredColumn("CONTACT_LIEU_DESCRIPTION"); - modelBuilder.newColumnForExport("CONTACT_LIEU_DESCRIPTION", new ValueGetter<Contact, String>() { - @Override - public String get(Contact contact) throws Exception { - String description = ""; - if (contact.getTerrestrialLocation() != null) { - description = contact.getTerrestrialLocation() - .getDescription(); - } - return description; - } - }); - } - - if (obsProgram == ObsProgram.OBSVENTE) { - modelBuilder.newColumnForImportExport("CONTACT_ECHANTILLONNAGE_COMPLET", Contact.PROPERTY_COMPLETE_SAMPLING, Common.BOOLEAN); - } - - if (obsProgram == ObsProgram.OBSDEB) { - modelBuilder.newColumnForImportExport("CONTACT_DATE_DEBARQUEMENT", Contact.PROPERTY_LANDING_DATE, Common.DAY_TIME); - modelBuilder.newColumnForImportExport("CONTACT_TYPE_OBSERVATION", "observationType", new I18nAbleParserFormatter<>(locale, ObservationType.values())); - modelBuilder.newColumnForImportExport("CONTACT_METIER", Contact.PROPERTY_OBS_DEB_CODE, new ObsDebCodeParserFormatter(locale, obsDebCodes)); - } - - return modelBuilder; - } - - @Override - public Iterable<ExportableColumn<Contact, Object>> getColumnsForExport() { - return (Iterable) getModel().getColumnsForExport(); - } - - @Override - public Iterable<ImportableColumn<Contact, Object>> getColumnsForImport() { - return (Iterable) getModel().getColumnsForImport(); - } - -} Copied: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java (from rev 2075, branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ObsMerContactImportExportModel.java) =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java (rev 0) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ContactImportExportModel.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,344 @@ +/* + * #%L + * Wao :: Business + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2009 - 2011 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ +package fr.ifremer.wao.services.service.csv; + +import com.google.common.base.Preconditions; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.Boat; +import fr.ifremer.wao.entity.Company; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.entity.ContactImpl; +import fr.ifremer.wao.entity.ContactState; +import fr.ifremer.wao.entity.ContactStateMotif; +import fr.ifremer.wao.entity.DataReliability; +import fr.ifremer.wao.entity.LocationType; +import fr.ifremer.wao.entity.ObsProgram; +import fr.ifremer.wao.entity.ObservedDataControl; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.entity.TerrestrialLocation; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.services.service.csv.operations.BoatParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.CompanyParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.ContactStateMotivesParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.I18nAbleParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.LocationTypeParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.SampleRowParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.UserParserFormatter; +import fr.ifremer.wao.services.service.csv.operations.UsersParserFormatter; +import org.apache.commons.lang3.StringUtils; +import org.nuiton.csv.Common; +import org.nuiton.csv.ExportableColumn; +import org.nuiton.csv.ImportExportModel; +import org.nuiton.csv.ImportableColumn; +import org.nuiton.csv.ModelBuilder; +import org.nuiton.csv.ValueFormatter; +import org.nuiton.csv.ValueGetter; +import org.nuiton.csv.ValueGetterSetter; +import org.nuiton.csv.ValueParserFormatter; +import org.nuiton.i18n.I18n; + +import java.text.ParseException; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +public class ContactImportExportModel implements ImportExportModel<Contact> { + + protected final Locale locale; + + protected ObsProgram obsProgram; + + protected List<WaoUser> waoUsers; + + protected List<SampleRow> sampleRows; + + protected List<Boat> boats; + + protected List<ContactStateMotif> motives; + + private List<TerrestrialLocation> terrestrialLocations; + + public static ContactImportExportModel forExport(Locale locale, + ObsProgram obsProgram) { + return new ContactImportExportModel(locale, obsProgram, null, null, null, null, null); + } + + public static ContactImportExportModel forImport(Locale locale, + ObsProgram obsProgram, + List<WaoUser> waoUsers, + List<SampleRow> sampleRows, + List<Boat> boats, + List<ContactStateMotif> motives, + List<TerrestrialLocation> terrestrialLocations) { + + Preconditions.checkState(waoUsers != null, "To import must have waoUsers"); + Preconditions.checkState(boats != null, "To import must have boats"); + Preconditions.checkState(sampleRows != null, "To import must have sampleRows"); + Preconditions.checkState(motives != null, "To import must have motives"); + Preconditions.checkState(terrestrialLocations != null, "To import must have motives"); + return new ContactImportExportModel(locale, obsProgram, waoUsers, sampleRows, boats, motives, terrestrialLocations); + } + + protected ContactImportExportModel(Locale locale, + ObsProgram obsProgram, + List<WaoUser> waoUsers, + List<SampleRow> sampleRows, + List<Boat> boats, + List<ContactStateMotif> motives, + List<TerrestrialLocation> terrestrialLocations) { + this.locale = locale; + this.obsProgram = obsProgram; + this.waoUsers = waoUsers; + this.sampleRows = sampleRows; + this.boats = boats; + this.motives = motives; + this.terrestrialLocations = terrestrialLocations; + } + + @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<>(); + modelBuilder.newColumnForImportExport("CONTACT_ID", Contact.PROPERTY_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(locale, waoUsers)); + modelBuilder.newColumnForImportExport("CONTACT_OBSERVATEURS_SECONDAIRES", Contact.PROPERTY_SECONDARY_OBSERVERS, new UsersParserFormatter(locale, waoUsers)); + + modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_NOMS"); + modelBuilder.newColumnForExport( + "CONTACT_OBSERVATEURS_NOMS", + "allObservers", + new ValueFormatter<List<WaoUser>>() { + @Override + public String format(List<WaoUser> value) { + List<String> fullNames = new LinkedList<>(); + for (WaoUser waoUser : value) { + fullNames.add(waoUser.getFullName()); + } + return StringUtils.join(fullNames, ", "); + } + } + ); + modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_SOCIETE"); + modelBuilder.newColumnForExport( + "CONTACT_OBSERVATEURS_SOCIETE", + new ValueGetter<Contact, Company>() { + @Override + public Company get(Contact contact) { + return contact.getMainObserver().getCompany(); + } + }, + new CompanyParserFormatter(locale, null) + ); + modelBuilder.newColumnForImportExport("CONTACT_ETAT", "contactState", new I18nAbleParserFormatter<>(locale, 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("NAVIRE_IMMATRICULATION", Contact.PROPERTY_BOAT, new BoatParserFormatter(boats, locale)); + modelBuilder.newIgnoredColumn("NAVIRE_NOM"); + modelBuilder.newColumnForExport("NAVIRE_NOM", new ValueGetter<Contact, String>() { + @Override + public String get(Contact contact) throws Exception { + return contact.getBoat().getName(); + } + }); + modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_SOCIETE", Contact.PROPERTY_VALIDATION_COMPANY, Common.BOOLEAN); + modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_PROGRAMME", Contact.PROPERTY_VALIDATION_PROGRAM, Common.BOOLEAN); + + modelBuilder.newColumnForImportExport("PLAN_CODE", Contact.PROPERTY_SAMPLE_ROW, new SampleRowParserFormatter(locale, sampleRows)); + + if (obsProgram.isObsMer()) { + modelBuilder.newColumnForImportExport("CONTACT_QUALITE_DONNEE", "dataReliability", + new I18nAbleParserFormatter<>(locale, DataReliability.values())); + modelBuilder.newColumnForImportExport("CONTACT_OBSERVATION_MAMMIFERE", Contact.PROPERTY_MAMMALS_OBSERVATION, Common.BOOLEAN); + modelBuilder.newColumnForImportExport("CONTACT_CAPTURE_ACCIDENTELLE", Contact.PROPERTY_MAMMALS_CAPTURE, Common.BOOLEAN); + modelBuilder.newIgnoredColumn("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS"); + modelBuilder.newColumnForExport("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS", Contact.PROPERTY_MAMMALS_INFO); + modelBuilder.newColumnForImportExport("CONTACT_ETAT_MOTIF_CODE", Contact.PROPERTY_CONTACT_STATE_MOTIF, new ContactStateMotivesParserFormatter(locale, motives)); + modelBuilder.newIgnoredColumn("CONTACT_ETAT_MOTIF_NOM"); + modelBuilder.newColumnForExport("CONTACT_ETAT_MOTIF_NOM", new ValueGetter<Contact, String>() { + + @Override + public String get(Contact contact) throws Exception { + String name = ""; + if (contact.getContactStateMotif() != null) { + name = contact.getContactStateMotif().getName(); + } + return name; + } + }); + modelBuilder.newColumnForImportExport("CONTACT_TRANSMISSION_RESTITUTION", Contact.PROPERTY_RESTITUTION, Common.DAY); + + List<ObservedDataControl> observedDataControlsValues = new LinkedList<>(); + Collections.addAll(observedDataControlsValues, ObservedDataControl.values()); + observedDataControlsValues.add(null); + I18nAbleParserFormatter<ObservedDataControl> valueParserFormatter = new I18nAbleParserFormatter<>(locale, observedDataControlsValues); + valueParserFormatter.setAcceptNullValues(true); + modelBuilder.newColumnForImportExport("CONTACT_DONNEES_ALLEGRO_VALIDEES", Contact.PROPERTY_OBSERVED_DATA_CONTROL, valueParserFormatter); + } + + if (obsProgram.isObsVente()) { + modelBuilder.newColumnForImportExport("CONTACT_ECHANTILLONNAGE_COMPLET", Contact.PROPERTY_COMPLETE_SAMPLING, Common.BOOLEAN); + + // FIXME 20110606 bleny contact.getTerrestrialLocation() may be null, export will fail + + // terrestrial location for both ObsVente and ObsDeb + ValueGetterSetter<Contact, LocationType> locationTypeGetter = new Common.ValueSaver<>(); + LocationTypeParserFormatter locationTypeParserFormatter = new LocationTypeParserFormatter(locale); + modelBuilder.newMandatoryColumn( + "CONTACT_LIEU_TYPE", + locationTypeParserFormatter, + locationTypeGetter); + modelBuilder.newColumnForExport( + "CONTACT_LIEU_TYPE", + new ValueGetter<Contact, LocationType>() { + @Override + public LocationType get(Contact contact) throws Exception { + LocationType locationType = null; + if (contact.getTerrestrialLocation() != null) { + locationType = contact.getTerrestrialLocation() + .getLocationType(); + } + return locationType; + } + }, + locationTypeParserFormatter); + modelBuilder.newColumnForImportExport( + "CONTACT_LIEU_CODE", + Contact.PROPERTY_TERRESTRIAL_LOCATION, + new TerrestrialLocationParserFormatter(locale, terrestrialLocations, locationTypeGetter)); + + modelBuilder.newIgnoredColumn("CONTACT_LIEU_DESCRIPTION"); + modelBuilder.newColumnForExport("CONTACT_LIEU_DESCRIPTION", new ValueGetter<Contact, String>() { + @Override + public String get(Contact contact) throws Exception { + String description = ""; + if (contact.getTerrestrialLocation() != null) { + description = contact.getTerrestrialLocation() + .getDescription(); + } + return description; + } + }); + + } + + return modelBuilder; + } + + @Override + public Iterable<ExportableColumn<Contact, Object>> getColumnsForExport() { + return (Iterable) getModel().getColumnsForExport(); + } + + @Override + public Iterable<ImportableColumn<Contact, Object>> getColumnsForImport() { + return (Iterable) getModel().getColumnsForImport(); + } /** will get terrestrial location depending on location code and pushed location type */ + + protected static class TerrestrialLocationParserFormatter implements ValueParserFormatter<TerrestrialLocation> { + + protected Locale locale; + + protected Map<LocationType, Map<String, TerrestrialLocation>> indexedLocations; + + protected List<TerrestrialLocation> terrestrialLocations; + + protected ValueGetter<Contact, LocationType> locationTypeGetter; + + TerrestrialLocationParserFormatter(Locale locale, + List<TerrestrialLocation> terrestrialLocations, + ValueGetter<Contact, LocationType> locationTypeGetter) { + this.locale = locale; + this.terrestrialLocations = terrestrialLocations; + this.locationTypeGetter = locationTypeGetter; + } + + @Override + public String format(TerrestrialLocation terrestrialLocation) { + String code = ""; + if (terrestrialLocation != null) { + code = terrestrialLocation.getCode(); + } + return code; + } + + @Override + public TerrestrialLocation parse(String code) throws ParseException { + if (indexedLocations == null) { + indexedLocations = new HashMap<>(); + for (TerrestrialLocation terrestrialLocation : terrestrialLocations) { + LocationType locationType = terrestrialLocation.getLocationType(); + Map<String, TerrestrialLocation> locationsForType = indexedLocations.get(locationType); + if (locationsForType == null) { + locationsForType = new HashMap<>(); + } + locationsForType.put(terrestrialLocation.getCode(), terrestrialLocation); + indexedLocations.put(locationType, locationsForType); + } + } + TerrestrialLocation terrestrialLocation = null; + if (StringUtils.isNotBlank(code)) { + LocationType locationType; + try { + locationType = locationTypeGetter.get(null); + } catch (Exception e) { + throw new RuntimeException(e); + } + if (locationType == null) { + throw new IllegalArgumentException(I18n.l(locale, "wao.import.contact.failure.locationTypeMissing")); + } + terrestrialLocation = indexedLocations.get(locationType).get(code); + if (terrestrialLocation == null) { + throw new IllegalArgumentException(I18n.l(locale, "wao.import.contact.failure.wrongTerrestrialLocation", + WaoUtils.l(locale, locationType), code)); + } + } + return terrestrialLocation; + } + } + +} Deleted: branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ObsMerContactImportExportModel.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ObsMerContactImportExportModel.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/java/fr/ifremer/wao/services/service/csv/ObsMerContactImportExportModel.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,217 +0,0 @@ -/* - * #%L - * Wao :: Business - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2009 - 2011 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ -package fr.ifremer.wao.services.service.csv; - -import com.google.common.base.Preconditions; -import fr.ifremer.wao.entity.Boat; -import fr.ifremer.wao.entity.Company; -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.entity.ContactImpl; -import fr.ifremer.wao.entity.ContactState; -import fr.ifremer.wao.entity.ContactStateMotif; -import fr.ifremer.wao.entity.DataReliability; -import fr.ifremer.wao.entity.ObsProgram; -import fr.ifremer.wao.entity.ObservedDataControl; -import fr.ifremer.wao.entity.SampleRow; -import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.services.service.csv.operations.BoatParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.CompanyParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.ContactStateMotivesParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.I18nAbleParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.SampleRowParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.UserParserFormatter; -import fr.ifremer.wao.services.service.csv.operations.UsersParserFormatter; -import org.apache.commons.lang3.StringUtils; -import org.nuiton.csv.Common; -import org.nuiton.csv.ExportableColumn; -import org.nuiton.csv.ImportExportModel; -import org.nuiton.csv.ImportableColumn; -import org.nuiton.csv.ModelBuilder; -import org.nuiton.csv.ValueFormatter; -import org.nuiton.csv.ValueGetter; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; - -public class ObsMerContactImportExportModel implements ImportExportModel<Contact> { - - protected final Locale locale; - - protected ObsProgram obsProgram; - - protected List<WaoUser> waoUsers; - - protected List<SampleRow> sampleRows; - - protected List<Boat> boats; - - protected List<ContactStateMotif> motives; - - public static ObsMerContactImportExportModel forExport(Locale locale, - ObsProgram obsProgram) { - return new ObsMerContactImportExportModel(locale, obsProgram, null, null, null, null); - } - - public static ObsMerContactImportExportModel forImport(Locale locale, - ObsProgram obsProgram, - List<WaoUser> waoUsers, - List<SampleRow> sampleRows, - List<Boat> boats, - List<ContactStateMotif> motives) { - - Preconditions.checkState(waoUsers != null, "To import must have waoUsers"); - Preconditions.checkState(boats != null, "To import must have boats"); - Preconditions.checkState(sampleRows != null, "To import must have sampleRows"); - Preconditions.checkState(motives != null, "To import must have motives"); - return new ObsMerContactImportExportModel(locale, obsProgram, waoUsers, sampleRows, boats, motives); - } - - protected ObsMerContactImportExportModel(Locale locale, - ObsProgram obsProgram, - List<WaoUser> waoUsers, - List<SampleRow> sampleRows, - List<Boat> boats, - List<ContactStateMotif> motives) { - this.locale = locale; - this.obsProgram = obsProgram; - this.waoUsers = waoUsers; - this.sampleRows = sampleRows; - this.boats = boats; - this.motives = motives; - } - - @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<>(); - modelBuilder.newColumnForImportExport("CONTACT_ID", Contact.PROPERTY_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(locale, waoUsers)); - modelBuilder.newColumnForImportExport("CONTACT_OBSERVATEURS_SECONDAIRES", Contact.PROPERTY_SECONDARY_OBSERVERS, new UsersParserFormatter(locale, waoUsers)); - - modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_NOMS"); - modelBuilder.newColumnForExport( - "CONTACT_OBSERVATEURS_NOMS", - "allObservers", - new ValueFormatter<List<WaoUser>>() { - @Override - public String format(List<WaoUser> value) { - List<String> fullNames = new LinkedList<>(); - for (WaoUser waoUser : value) { - fullNames.add(waoUser.getFullName()); - } - return StringUtils.join(fullNames, ", "); - } - } - ); - modelBuilder.newIgnoredColumn("CONTACT_OBSERVATEURS_SOCIETE"); - modelBuilder.newColumnForExport( - "CONTACT_OBSERVATEURS_SOCIETE", - new ValueGetter<Contact, Company>() { - @Override - public Company get(Contact contact) { - return contact.getMainObserver().getCompany(); - } - }, - new CompanyParserFormatter(locale, null) - ); - modelBuilder.newColumnForImportExport("CONTACT_ETAT", "contactState", new I18nAbleParserFormatter<>(locale, 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("NAVIRE_IMMATRICULATION", Contact.PROPERTY_BOAT, new BoatParserFormatter(boats, locale)); - modelBuilder.newIgnoredColumn("NAVIRE_NOM"); - modelBuilder.newColumnForExport("NAVIRE_NOM", new ValueGetter<Contact, String>() { - @Override - public String get(Contact contact) throws Exception { - return contact.getBoat().getName(); - } - }); - modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_SOCIETE", Contact.PROPERTY_VALIDATION_COMPANY, Common.BOOLEAN); - modelBuilder.newColumnForImportExport("CONTACT_VALIDATION_PROGRAMME", Contact.PROPERTY_VALIDATION_PROGRAM, Common.BOOLEAN); - - modelBuilder.newColumnForImportExport("PLAN_CODE", Contact.PROPERTY_SAMPLE_ROW, new SampleRowParserFormatter(locale, sampleRows)); - - modelBuilder.newColumnForImportExport("CONTACT_QUALITE_DONNEE", "dataReliability", - new I18nAbleParserFormatter<>(locale, DataReliability.values())); - modelBuilder.newColumnForImportExport("CONTACT_OBSERVATION_MAMMIFERE", Contact.PROPERTY_MAMMALS_OBSERVATION, Common.BOOLEAN); - modelBuilder.newColumnForImportExport("CONTACT_CAPTURE_ACCIDENTELLE", Contact.PROPERTY_MAMMALS_CAPTURE, Common.BOOLEAN); - modelBuilder.newIgnoredColumn("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS"); - modelBuilder.newColumnForExport("CONTACT_CAPTURE_ACCIDENTELLE_DETAILS", Contact.PROPERTY_MAMMALS_INFO); - modelBuilder.newColumnForImportExport("CONTACT_ETAT_MOTIF_CODE", Contact.PROPERTY_CONTACT_STATE_MOTIF, new ContactStateMotivesParserFormatter(locale, motives)); - modelBuilder.newIgnoredColumn("CONTACT_ETAT_MOTIF_NOM"); - modelBuilder.newColumnForExport("CONTACT_ETAT_MOTIF_NOM", new ValueGetter<Contact, String>() { - @Override - public String get(Contact contact) throws Exception { - String name = ""; - if (contact.getContactStateMotif() != null) { - name = contact.getContactStateMotif().getName(); - } - return name; - } - }); - modelBuilder.newColumnForImportExport("CONTACT_TRANSMISSION_RESTITUTION", Contact.PROPERTY_RESTITUTION, Common.DAY); - - List<ObservedDataControl> observedDataControlsValues = new LinkedList<>(); - Collections.addAll(observedDataControlsValues, ObservedDataControl.values()); - observedDataControlsValues.add(null); - I18nAbleParserFormatter<ObservedDataControl> valueParserFormatter = new I18nAbleParserFormatter<>(locale, observedDataControlsValues); - valueParserFormatter.setAcceptNullValues(true); - modelBuilder.newColumnForImportExport("CONTACT_DONNEES_ALLEGRO_VALIDEES", Contact.PROPERTY_OBSERVED_DATA_CONTROL, valueParserFormatter); - - return modelBuilder; - } - - @Override - public Iterable<ExportableColumn<Contact, Object>> getColumnsForExport() { - return (Iterable) getModel().getColumnsForExport(); - } - - @Override - public Iterable<ImportableColumn<Contact, Object>> getColumnsForImport() { - return (Iterable) getModel().getColumnsForImport(); - } - -} Modified: branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_en_GB.properties =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_en_GB.properties 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_en_GB.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -57,6 +57,7 @@ wao.import.contact.failure.missingObservedDataControl=You must provide a value for observed data control wao.import.contact.failure.missingObserver=Il ne peut y avoir aucun observateur pour l'état '%s' wao.import.contact.failure.missingRestitution=You must provide the restitution forward date +wao.import.contact.failure.missingTerrestrialLocation= wao.import.contact.failure.not.updatable=Insufficient credentials to update contact wao.import.contact.failure.observationEndDateAfterToday=La date de fin de la marée ne peut pas être postérieure à la date du jour wao.import.contact.failure.observationEndDateBeforeBeginDate=La date de fin d'observation ne peut pas être antérieure à celle du début Modified: branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_fr_FR.properties =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_fr_FR.properties 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/main/resources/i18n/wao-services_fr_FR.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -54,6 +54,7 @@ wao.import.contact.failure.missingObservedDataControl=Ligne %s \: Il faut préciser une valeur pour le contrôle des données observées wao.import.contact.failure.missingObserver=Ligne %s \: Il ne peut y avoir aucun observateur pour l'état '%s' wao.import.contact.failure.missingRestitution=Ligne %s \: Il faut préciser une date de transmission de la restitution de la donnée avant de valider +wao.import.contact.failure.missingTerrestrialLocation= wao.import.contact.failure.not.updatable=Ligne %s \: Vous n'avez pas les droits suffisants pour modifier le contact wao.import.contact.failure.observationEndDateAfterToday=Ligne %s \: La date de fin de la marée doit être antérieure à la date du jour wao.import.contact.failure.observationEndDateBeforeBeginDate=Ligne %s \: La date de fin d'observation doit être postérieure à celle du début Copied: branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ContactsServiceTest.java (from rev 2075, branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ObsMerContactsServiceTest.java) =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ContactsServiceTest.java (rev 0) +++ branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ContactsServiceTest.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,101 @@ +package fr.ifremer.wao.services.service; + +/* + * #%L + * Wao :: Services + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import fr.ifremer.wao.ContactsFilter; +import fr.ifremer.wao.services.AbstractWaoServiceTest; +import fr.ifremer.wao.services.ObsMerFixtures; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.util.DateUtil; +import org.nuiton.util.pagination.PaginationParameter; + +import java.io.InputStream; + +public class ContactsServiceTest extends AbstractWaoServiceTest { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ContactsServiceTest.class); + + protected ContactsService service; + + protected ObsMerFixtures fixtures; + + @Before + public void setUp() { + service = newService(ContactsService.class); + fixtures = new ObsMerFixtures(newServiceContext()); + } + + protected boolean isDatabaseWithReferential() { + return true; + } + + @Test + public void testGetContactsFilterValues() { + + ContactsFilter filter = service.newContactFilter(fixtures.admin()); + + ContactsFilterValues filterValues = service.getContactsFilterValues(fixtures.admin(), filter); + } + + @Test + public void testGetContactsList() { + + ContactsFilter filter = service.newContactFilter(fixtures.admin()); + + PaginationParameter pager = service.newContactsPaginationParameter(0, 50); + + ObsMerContactsList contactsList = service.getContactsList(fixtures.admin(), filter, pager); + } + + @Test + public void testImportContacts() { + fixtures.samplingPlan(); + fixtures.jmichmuche(); + fixtures.navires(); + + // today must be after the observation end date + applicationContext.setDate(DateUtil.createDate(1, 2, 2011)); + + InputStream input = null; + try { + + Assert.assertEquals(0, service.getContactDao().count()); + input = getClass().getResourceAsStream("/import/contacts.csv"); + service.importContacts(fixtures.admin(), input); + Assert.assertEquals(2, service.getContactDao().count()); + } catch (ImportErrorException e) { + if (log.isDebugEnabled()) { + log.debug("unexpected exception raised", e); + } + Assert.fail("exception should not be raised"); + } finally { + IOUtils.closeQuietly(input); + } + } + +} Deleted: branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ObsMerContactsServiceTest.java =================================================================== --- branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ObsMerContactsServiceTest.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-services/src/test/java/fr/ifremer/wao/services/service/ObsMerContactsServiceTest.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,101 +0,0 @@ -package fr.ifremer.wao.services.service; - -/* - * #%L - * Wao :: Services - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.services.AbstractWaoServiceTest; -import fr.ifremer.wao.services.ObsMerFixtures; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.util.DateUtil; -import org.nuiton.util.pagination.PaginationParameter; - -import java.io.InputStream; - -public class ObsMerContactsServiceTest extends AbstractWaoServiceTest { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ObsMerContactsServiceTest.class); - - protected ObsMerContactsService service; - - protected ObsMerFixtures fixtures; - - @Before - public void setUp() { - service = newService(ObsMerContactsService.class); - fixtures = new ObsMerFixtures(newServiceContext()); - } - - protected boolean isDatabaseWithReferential() { - return true; - } - - @Test - public void testGetContactsFilterValues() { - - ContactsFilter filter = service.newContactFilter(fixtures.admin()); - - ContactsFilterValues filterValues = service.getContactsFilterValues(fixtures.admin(), filter); - } - - @Test - public void testGetContactsList() { - - ContactsFilter filter = service.newContactFilter(fixtures.admin()); - - PaginationParameter pager = service.newContactsPaginationParameter(0, 50); - - ObsMerContactsList contactsList = service.getContactsList(fixtures.admin(), filter, pager); - } - - @Test - public void testImportContacts() { - fixtures.samplingPlan(); - fixtures.jmichmuche(); - fixtures.navires(); - - // today must be after the observation end date - applicationContext.setDate(DateUtil.createDate(1, 2, 2011)); - - InputStream input = null; - try { - - Assert.assertEquals(0, service.getContactDao().count()); - input = getClass().getResourceAsStream("/import/contacts.csv"); - service.importContacts(fixtures.admin(), input); - Assert.assertEquals(2, service.getContactDao().count()); - } catch (ImportErrorException e) { - if (log.isDebugEnabled()) { - log.debug("unexpected exception raised", e); - } - Assert.fail("exception should not be raised"); - } finally { - IOUtils.closeQuietly(input); - } - } - -} Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,249 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.google.common.base.Objects; +import com.opensymphony.xwork2.Preparable; +import fr.ifremer.wao.ContactsFilter; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.entity.ContactState; +import fr.ifremer.wao.entity.DCF5Code; +import fr.ifremer.wao.entity.FishingZone; +import fr.ifremer.wao.entity.SampleRow; +import fr.ifremer.wao.services.service.ContactsFilterValues; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.services.service.ObsMerContactsList; +import fr.ifremer.wao.web.WaoJspActionSupport; +import org.apache.commons.lang3.time.DateUtils; +import org.nuiton.util.pagination.PaginationParameter; +import org.nuiton.util.pagination.PaginationResult; + +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +public class ContactsAction extends WaoJspActionSupport implements Preparable { + + private static final long serialVersionUID = 1L; + + protected transient ContactsService service; + + protected int pageNumber; + + protected long firstRangePage; + + protected long lastRangePage; + + /** + * Contacts filter. + */ + protected ContactsFilter filter; + + /** + * List of contacts according to the input pager and filter. + */ + protected ObsMerContactsList contactsList; + + public void setService(ContactsService service) { + this.service = service; + } + + public void setPageNumber(int pageNumber) { + this.pageNumber = pageNumber; + } + + public long getFirstRangePage() { + return firstRangePage; + } + + public long getLastRangePage() { + return lastRangePage; + } + + public ContactsFilter getFilter() { + if (filter == null) { + prepare(); + } + return filter; + } + + public List<Contact> getContacts() { + return contactsList.getContacts().getElements(); + } + + public ContactsFilterValues getFilterValues() { + return contactsList.getFilterValues(); + } + + public PaginationResult<Contact> getPagination() { + return contactsList.getContacts(); + } + + @Override + public void prepare() { + + if (filter == null) { + filter = service.newContactFilter(getAuthenticatedWaoUser()); + } + + } + + @Override + public String execute() { + + filter = Objects.firstNonNull(session.getContactsFilter(), filter); + + return applyFilter(); + + } + + public String resetFilter() { + + filter = service.newContactFilter(getAuthenticatedWaoUser()); + + return applyFilter(); + + } + + public String applyFilter() { + + getSession().setContactsFilter(filter); + + PaginationParameter pager = service.newContactsPaginationParameter(pageNumber, 25); + contactsList = service.getContactsList(getAuthenticatedWaoUser(), filter, pager); + + firstRangePage = getPaginationFirstPage(contactsList.getContacts(), 10); + lastRangePage = getPaginationLastPage(contactsList.getContacts(), 10, firstRangePage); + + return SUCCESS; + + } + + protected Date now = new Date(); + + public String getFilterPeriodFromPlaceholder() { + String placeholder = formatDateTime(DateUtils.addMonths(now, 1)); + return placeholder; + } + + public String getFilterPeriodToPlaceholder() { + String placeholder = formatDateTime(DateUtils.addYears(now, 1)); + return placeholder; + } + + public boolean isFullView() { + boolean fullView = getAuthenticatedWaoUser().isAdmin() || getAuthenticatedWaoUser().isProfessional(); + return fullView; + } + + public String getMammalsInfo(Contact contact) { + return escapeForToolTip(contact.getMammalsInfo()); + } + + public boolean isBoardingDone(Contact contact) { + return ContactState.OBSERVATION_DONE == contact.getContactState(); + } + + public String getDivision(SampleRow sampleRow) { + String result = ""; + for (FishingZone zone : sampleRow.getFishingZone()) { + result += zone.getDistrictCode() + " "; + } + return result; + } + + /** + * Devrait résoudre un problème que pose le composant ck/tooltip. + * <p/> + * Voir ANO#606 + */ + public static String escapeForToolTip(String str) { + String result = str.replaceAll("\r\n", "\n"); + result = result.replaceAll("\n", "<br />"); + result = result.replaceAll("'", "’"); + result = result.replaceAll("\"", """); + result = result.replaceAll("%", "%"); + return result; + } + + public String getContactToHighlightId() { + return session.getContactToHighlightId(); + } + + public Map<String, String> getDcf5CodesAndDescriptions(SampleRow sampleRow) { + Map<String, String> dcf5CodesAndDescriptions = new LinkedHashMap<>(); + for (DCF5Code dcf5Code : sampleRow.getdCF5Code()) { + String key = dcf5Code.getCode(); + String description = dcf5Code.getFishingGearCode() + " - " + WaoUtils.l(getLocale(), dcf5Code.getFishingGearDCF()); + if (dcf5Code.getTargetSpeciesCode() != null) { + description += " ; " + dcf5Code.getTargetSpeciesCode() + " - " + WaoUtils.l(getLocale(), dcf5Code.getTargetSpeciesDCF()); + } + dcf5CodesAndDescriptions.put(key, description); + } + return dcf5CodesAndDescriptions; + } + + public boolean isAcceptable(Contact contact) { + boolean acceptable; + if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + acceptable = contact.isAcceptableByCompany(); + } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + acceptable = contact.isAcceptableByProgram(); + } else { + throw new IllegalStateException(); + } + return acceptable; + } + + public boolean isRefusable(Contact contact) { + boolean refuseable; + if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + refuseable = contact.isRefusableByCompany(); + } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + refuseable = contact.isRefusableByProgram(); + } else { + throw new IllegalStateException(); + } + return refuseable; + } + + public boolean isUnacceptable(Contact contact) { + boolean unacceptable; + if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + unacceptable = contact.isUnacceptableByCompany(); + } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + unacceptable = contact.isUnacceptableByProgram(); + } else { + throw new IllegalStateException(); + } + return unacceptable; + } + +} \ No newline at end of file Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsFilterValuesJsonAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsFilterValuesJsonAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsFilterValuesJsonAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ContactsFilterValuesJsonAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,76 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.opensymphony.xwork2.Preparable; +import fr.ifremer.wao.ContactsFilter; +import fr.ifremer.wao.services.service.ContactsFilterValues; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.web.WaoJsonActionSupport; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +public class ContactsFilterValuesJsonAction extends WaoJsonActionSupport implements Preparable { + + private static final long serialVersionUID = 1L; + + protected transient ContactsService service; + + protected ContactsFilter filter; + + protected ContactsFilterValues filterValues; + + public void setService(ContactsService service) { + this.service = service; + } + + public ContactsFilter getFilter() { + if (filter == null) { + prepare(); + } + return filter; + } + + public ContactsFilterValues getFilterValues() { + return filterValues; + } + + @Override + public void prepare() { + + filter = service.newContactFilter(session.getAuthenticatedWaoUser()); + } + + @Override + public String execute() { + + filterValues = service.getContactsFilterValues(session.getAuthenticatedWaoUser(), filter); + + return SUCCESS; + + } + +} \ No newline at end of file Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/CreateContactAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/CreateContactAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/CreateContactAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/CreateContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,45 @@ +package fr.ifremer.wao.web.action; + +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.web.WaoJspActionSupport; +import org.apache.struts2.convention.annotation.Result; +import org.apache.struts2.convention.annotation.Results; + +@Results({ + @Result(name="success", type="redirectAction", params = { "actionName", "contacts" }) +}) +public class CreateContactAction extends WaoJspActionSupport { + + protected ContactsService service; + + protected String boatId; + + protected String sampleRowId; + + public void setService(ContactsService service) { + this.service = service; + } + + public void setBoatId(String boatId) { + this.boatId = boatId; + } + + public void setSampleRowId(String sampleRowId) { + this.sampleRowId = sampleRowId; + } + + @Override + public String execute() { + + Contact contact = service.createContact(getAuthenticatedWaoUser(), sampleRowId, boatId); + + session.setStartBoatSelectionForSampleRowId(null); + + session.setContactToHighlightId(contact.getTopiaId()); + + return SUCCESS; + + } + +} Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/DeleteContactAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/DeleteContactAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/DeleteContactAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/DeleteContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,84 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.services.service.IllegalDeletionException; +import fr.ifremer.wao.web.WaoJspActionSupport; +import org.apache.struts2.convention.annotation.Result; +import org.apache.struts2.convention.annotation.Results; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +@Results({ + @Result(name = "error", type = "redirectAction", params = {"actionName", "edit-contact!input", "contactId", "%{contactId}"}), + @Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"}) + }) +public class DeleteContactAction extends WaoJspActionSupport { + + private static final long serialVersionUID = 1L; + + protected String contactId; + + protected transient ContactsService service; + + public void setService(ContactsService service) { + this.service = service; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public String getContactId() { + return contactId; + } + + @Override + public String execute() { + + Contact contact = service.getContact(contactId); + String contactCode = contact.getMainObserver().getFullName(); + + String result; + try { + service.delete(contactId); + + session.addMessage(t("wao.ui.action.deleteContact.success", contactCode)); + + result = SUCCESS; + + } catch (IllegalDeletionException e) { + + session.addErrorMessages(t("wao.ui.action.deleteContact.failure", contactCode)); + session.addErrorMessages(e.getExplanation(getLocale())); + + result = ERROR; + } + return result; + } +} Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/EditContactAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/EditContactAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/EditContactAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/EditContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,351 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.google.common.base.Optional; +import com.google.common.base.Strings; +import com.google.common.collect.Sets; +import com.opensymphony.xwork2.Preparable; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.ContactState; +import fr.ifremer.wao.entity.ContactStateMotif; +import fr.ifremer.wao.entity.DataReliability; +import fr.ifremer.wao.entity.ObservedDataControl; +import fr.ifremer.wao.entity.SamplingStrategy; +import fr.ifremer.wao.entity.TerrestrialLocation; +import fr.ifremer.wao.entity.WaoUser; +import fr.ifremer.wao.entity.WaoUsers; +import fr.ifremer.wao.services.AuthenticatedWaoUser; +import fr.ifremer.wao.services.service.ContactDataInputDateAfterTodayException; +import fr.ifremer.wao.services.service.ContactDataInputDateBeforeObservationEndDateException; +import fr.ifremer.wao.services.service.ContactNotUpdatableException; +import fr.ifremer.wao.services.service.ContactObservationEndDateAfterTodayException; +import fr.ifremer.wao.services.service.ContactObservationEndDateBeforeBeginDateException; +import fr.ifremer.wao.services.service.ContactRestitutionDateBeforeDataInputDateException; +import fr.ifremer.wao.services.service.ContactWithObservedDataControlToCorrectionAskedException; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.services.service.DuplicatedContactMainObserverInSecondaryObserversException; +import fr.ifremer.wao.services.service.InvalidContactObservationBeginDateException; +import fr.ifremer.wao.services.service.MismatchContactMainObserverCompanyException; +import fr.ifremer.wao.services.service.MismatchContactSecondaryObserverCompanyException; +import fr.ifremer.wao.services.service.MissingContactCommentAdminException; +import fr.ifremer.wao.services.service.MissingContactCommentException; +import fr.ifremer.wao.services.service.MissingContactDataInputDateException; +import fr.ifremer.wao.services.service.MissingContactDataReliabilityException; +import fr.ifremer.wao.services.service.MissingContactMainObserverException; +import fr.ifremer.wao.services.service.MissingContactMammalsInfoException; +import fr.ifremer.wao.services.service.MissingContactNbObservantsException; +import fr.ifremer.wao.services.service.MissingContactObservationBeginDateException; +import fr.ifremer.wao.services.service.MissingContactObservationEndDateException; +import fr.ifremer.wao.services.service.MissingContactObservedDataControlException; +import fr.ifremer.wao.services.service.MissingContactRestitutionException; +import fr.ifremer.wao.services.service.MissingContactStateMotifException; +import fr.ifremer.wao.services.service.MissingContactTerrestrialLocationException; +import fr.ifremer.wao.services.service.UnwantedContactContactStateMotifException; +import fr.ifremer.wao.services.service.UpdateContactCommand; +import fr.ifremer.wao.services.service.administration.ReferentialService; +import fr.ifremer.wao.services.service.administration.WaoUsersService; +import fr.ifremer.wao.web.WaoJspActionSupport; +import org.apache.struts2.convention.annotation.Result; +import org.apache.struts2.convention.annotation.Results; + +import java.util.Date; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Created on 4/6/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +@Results({@Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"})}) +public class EditContactAction extends WaoJspActionSupport implements Preparable { + + private static final long serialVersionUID = 1L; + + /** + * Id of contact to edit. + */ + protected Optional<String> optionalContactId = Optional.absent(); + + protected Map<String, String> observers; + + protected Map<String, String> terrestrialLocations; + + protected Map<ContactState, String> contactStates; + + protected Map<String, String> contactStateMotives; + + protected Map<ObservedDataControl, String> observedDataControls; + + protected Map<DataReliability, String> dataReliabilities; + + protected Map<SamplingStrategy, String> samplingStrategies; + + protected transient ContactsService service; + + protected transient WaoUsersService waoUsersService; + + protected transient ReferentialService referentialService; + + protected UpdateContactCommand updateContactCommand; + + public void setService(ContactsService service) { + this.service = service; + } + + public void setWaoUsersService(WaoUsersService waoUsersService) { + this.waoUsersService = waoUsersService; + } + + public void setReferentialService(ReferentialService referentialService) { + this.referentialService = referentialService; + } + + public void setContactId(String contactId) { + this.optionalContactId = Optional.fromNullable(Strings.emptyToNull(contactId)); + } + + public String getContactId() { + return optionalContactId.orNull(); + } + + public UpdateContactCommand getUpdateContactCommand() { + if (updateContactCommand == null) { + prepare(); + } + return updateContactCommand; + } + + public Map<String, String> getObservers() { + if (observers == null) { + prepare(); + } + return observers; + } + + public Map<ContactState, String> getContactStates() { + if (contactStates == null) { + prepare(); + } + return contactStates; + } + + public Map<String, String> getContactStateMotives() { + if (contactStateMotives == null) { + prepare(); + } + return contactStateMotives; + } + + public Map<ObservedDataControl, String> getObservedDataControls() { + if (observedDataControls == null) { + prepare(); + } + return observedDataControls; + } + + public Map<DataReliability, String> getDataReliabilities() { + if (dataReliabilities == null) { + prepare(); + } + return dataReliabilities; + } + + public Map<String, String> getTerrestrialLocations() { + if (terrestrialLocations == null) { + prepare(); + } + return terrestrialLocations; + } + + public Map<SamplingStrategy, String> getSamplingStrategies() { + if (samplingStrategies == null) { + prepare(); + } + return samplingStrategies; + } + + public String getDateTimePlaceholder() { + return formatDateTime(new Date()); + } + + public String getDatePlaceholder() { + return formatDate(new Date()); + } + + @Override + public void prepare() { + + updateContactCommand = service.newUpdateContactCommand(getAuthenticatedWaoUser(), optionalContactId); + + List<WaoUser> waoUsers = waoUsersService.getActiveWaoUsers(Optional.of(updateContactCommand.getContact().getSampleRow().getCompany().getTopiaId())); + Set<WaoUser> sortedWaoUsers = Sets.newTreeSet(WaoUsers.fullNameComparator()); + sortedWaoUsers.addAll(waoUsers); + observers = new LinkedHashMap<>(); + for (WaoUser waoUser : sortedWaoUsers) { + observers.put(waoUser.getTopiaId(), waoUser.getFullName()); + } + contactStates = new EnumMap<>(ContactState.class); + for (ContactState contactState : ContactState.getAllowedStates(getAuthenticatedWaoUser().getObsProgram())) { + contactStates.put(contactState, WaoUtils.l(getLocale(), contactState)); + } + + contactStateMotives = new TreeMap<>(); + for (ContactStateMotif contactStateMotif : referentialService.getAllContactStateMotifs(null)) { + contactStateMotives.put(contactStateMotif.getTopiaId(), contactStateMotif.getName()); + } + + observedDataControls = new EnumMap<>(ObservedDataControl.class); + for (ObservedDataControl observedDataControl : ObservedDataControl.values()) { + observedDataControls.put(observedDataControl, WaoUtils.l(getLocale(), observedDataControl)); + } + + dataReliabilities = new EnumMap<>(DataReliability.class); + for (DataReliability dataReliability : DataReliability.values()) { + dataReliabilities.put(dataReliability, WaoUtils.l(getLocale(), dataReliability)); + } + + samplingStrategies = new EnumMap<>(SamplingStrategy.class); + for (SamplingStrategy samplingStrategy : SamplingStrategy.values()) { + samplingStrategies.put(samplingStrategy, WaoUtils.l(getLocale(), samplingStrategy)); + } + + terrestrialLocations = new LinkedHashMap<>(); + List<TerrestrialLocation> terrestrialLocationInDistricts = referentialService.getTerrestrialLocationInDistricts(updateContactCommand.getContact().getSampleRow().getTerrestrialLocations()); + for (TerrestrialLocation terrestrialLocation : terrestrialLocationInDistricts) { + terrestrialLocations.put(terrestrialLocation.getTopiaId(), terrestrialLocation.getDescription()); + } + } + + @Override + public void validate() { + + service.preValidate(updateContactCommand); + + AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); + + try { + service.validate(authenticatedWaoUser, updateContactCommand, true); + } catch (ContactNotUpdatableException e) { + session.addErrorMessages(t("wao.ui.contacts.validation.failure.not.updatable")); + + } catch (UnwantedContactContactStateMotifException e) { + addFieldError("updateContactCommand.contact.contactStateMotif", t("wao.ui.form.Contact.error.unwantedContactStateMotif")); + + } catch (MissingContactNbObservantsException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + addFieldError("updateContactCommand.contact.nbObservants", t("wao.ui.form.Contact.error.missingObserver", state)); + + } catch (MissingContactObservationEndDateException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.missingObservationEndDate", state)); + + } catch (ContactDataInputDateBeforeObservationEndDateException e) { + addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.dataInputDateBeforeObservationEndDate")); + + } catch (InvalidContactObservationBeginDateException e) { + addFieldError("updateContactCommand.contact.observationBeginDate", t("wao.ui.form.Contact.error.invalidObservationBeginDate")); + + } catch (MissingContactRestitutionException e) { + addFieldError("updateContactCommand.contact.restitution", t("wao.ui.form.Contact.error.missingRestitution")); + + } catch (ContactDataInputDateAfterTodayException e) { + addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.dataInputDateAfterToday")); + + } catch (MissingContactCommentException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + addFieldError("updateContactCommand.contact.comment", t("wao.ui.form.Contact.error.missingComment", state)); + + } catch (MismatchContactMainObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + addFieldError("updateContactCommand.contact.mainObserver", t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName)); + + } catch (ContactRestitutionDateBeforeDataInputDateException e) { + addFieldError("updateContactCommand.contact.restitution", t("wao.ui.form.Contact.error.transmissionDateBeforeDataInputDate")); + + } catch (ContactObservationEndDateBeforeBeginDateException e) { + addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.observationEndDateBeforeBeginDate")); + + } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { + addFieldError("updateContactCommand.contact.secondaryObservers", t("wao.ui.form.Contact.error.duplicatedMainObserverInSecondaryObservers")); + + } catch (MissingContactDataReliabilityException e) { + addFieldError("updateContactCommand.contact.dataReliability", t("wao.ui.form.Contact.error.missingDataReliability")); + + } catch (MismatchContactSecondaryObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + addFieldError("updateContactCommand.contact.secondaryObservers", t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName)); + + } catch (MissingContactObservedDataControlException e) { + addFieldError("updateContactCommand.contact.observedDataControl", t("wao.ui.form.Contact.error.missingObservedDataControl")); + + } catch (ContactWithObservedDataControlToCorrectionAskedException e) { + addFieldError("updateContactCommand.contact.observedDataControl", t("wao.ui.form.Contact.error.observedDataControlToCorrectionAsked")); + + } catch (MissingContactStateMotifException e) { + addFieldError("updateContactCommand.contact.contactStateMotif", t("wao.ui.form.Contact.error.missingContactStateMotif")); + + } catch (MissingContactDataInputDateException e) { + addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.missingDataInputDate")); + + } catch (MissingContactMainObserverException e) { + addFieldError("updateContactCommand.contact.mainObserver", t("wao.ui.form.Contact.error.missingMainObserver")); + + } catch (MissingContactCommentAdminException e) { + String dataReliability = WaoUtils.l(getLocale(), e.getContact().getDataReliability()); + addFieldError("updateContactCommand.contact.commentAdmin", t("wao.ui.form.Contact.error.missingCommentAdmin", dataReliability)); + + } catch (ContactObservationEndDateAfterTodayException e) { + addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.observationEndDateAfterToday")); + + } catch (MissingContactObservationBeginDateException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + addFieldError("updateContactCommand.contact.observationBeginDate", t("wao.ui.form.Contact.error.missingObservationBeginDate", state)); + + } catch (MissingContactMammalsInfoException e) { + addFieldError("updateContactCommand.contact.mammalsInfo", t("wao.ui.form.Contact.error.missingMammalsInfo")); + + } catch (MissingContactTerrestrialLocationException e) { + throw new UnsupportedOperationException(); + } + } + + @Override + public String execute() throws Exception { + + service.save(updateContactCommand, false); + + session.addMessage(t("wao.ui.form.updateContactCommand.success")); + + session.setContactToHighlightId(updateContactCommand.getContact().getTopiaId()); + return SUCCESS; + } + +} \ No newline at end of file Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ExportContactsAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ExportContactsAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ExportContactsAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ExportContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,74 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.opensymphony.xwork2.Preparable; +import fr.ifremer.wao.ContactsFilter; +import fr.ifremer.wao.services.service.ContactsService; + +import java.io.InputStream; +import java.util.Date; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +public class ExportContactsAction extends AbstractDownloadCsvAction implements Preparable { + + private static final long serialVersionUID = 1L; + + protected transient ContactsService service; + + protected ContactsFilter filter; + + public void setService(ContactsService service) { + this.service = service; + } + + public ContactsFilter getFilter() { + if (filter == null) { + prepare(); + } + return filter; + } + + @Override + public void prepare() { + + filter = service.newContactFilter(getAuthenticatedWaoUser()); + } + + @Override + public String getFileName() { + + return "contacts_" + getObsProgram().name() + "_" + dateFormat.format(new Date()) + ".csv"; + } + + @Override + public InputStream getInputStream() { + + return service.exportContacts(filter); + } + +} \ No newline at end of file Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ImportContactsAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ImportContactsAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ImportContactsAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ImportContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,61 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.services.service.ImportErrorException; +import org.apache.struts2.convention.annotation.Result; +import org.apache.struts2.convention.annotation.Results; + +import java.io.InputStream; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +@Results({ + @Result(name = "error", type = "redirectAction", params = {"actionName", "import-contacts!input"}), + @Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"}) + }) +public class ImportContactsAction extends AbstractImportCsvAction { + + private static final long serialVersionUID = 1L; + + protected transient ContactsService contactsService; + + public void setContactsService(ContactsService contactsService) { + this.contactsService = contactsService; + } + + @Override + protected void importCsv(InputStream csvInputStream) throws ImportErrorException { + contactsService.importContacts(getAuthenticatedWaoUser(), csvInputStream); + } + + @Override + protected String getSuccessMessage() { + return t("wao.ui.import.contacts.success"); + } + +} \ No newline at end of file Copied: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ValidateContactJsonAction.java (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ValidateContactJsonAction.java) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ValidateContactJsonAction.java (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/ValidateContactJsonAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,306 @@ +package fr.ifremer.wao.web.action; + +/* + * #%L + * Wao :: Web + * %% + * Copyright (C) 2009 - 2014 Ifremer + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * #L% + */ + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.opensymphony.xwork2.Preparable; +import fr.ifremer.wao.WaoTechnicalException; +import fr.ifremer.wao.WaoUtils; +import fr.ifremer.wao.entity.Contact; +import fr.ifremer.wao.services.AuthenticatedWaoUser; +import fr.ifremer.wao.services.service.ContactDataInputDateBeforeObservationEndDateException; +import fr.ifremer.wao.services.service.ContactDataInputDateAfterTodayException; +import fr.ifremer.wao.services.service.ContactNotUpdatableException; +import fr.ifremer.wao.services.service.ContactObservationEndDateAfterTodayException; +import fr.ifremer.wao.services.service.ContactObservationEndDateBeforeBeginDateException; +import fr.ifremer.wao.services.service.ContactRestitutionDateBeforeDataInputDateException; +import fr.ifremer.wao.services.service.ContactWithObservedDataControlToCorrectionAskedException; +import fr.ifremer.wao.services.service.ContactsService; +import fr.ifremer.wao.services.service.DuplicatedContactMainObserverInSecondaryObserversException; +import fr.ifremer.wao.services.service.InvalidContactObservationBeginDateException; +import fr.ifremer.wao.services.service.MismatchContactMainObserverCompanyException; +import fr.ifremer.wao.services.service.MismatchContactSecondaryObserverCompanyException; +import fr.ifremer.wao.services.service.MissingContactCommentAdminException; +import fr.ifremer.wao.services.service.MissingContactCommentException; +import fr.ifremer.wao.services.service.MissingContactDataInputDateException; +import fr.ifremer.wao.services.service.MissingContactDataReliabilityException; +import fr.ifremer.wao.services.service.MissingContactMainObserverException; +import fr.ifremer.wao.services.service.MissingContactMammalsInfoException; +import fr.ifremer.wao.services.service.MissingContactNbObservantsException; +import fr.ifremer.wao.services.service.MissingContactObservationBeginDateException; +import fr.ifremer.wao.services.service.MissingContactObservationEndDateException; +import fr.ifremer.wao.services.service.MissingContactObservedDataControlException; +import fr.ifremer.wao.services.service.MissingContactRestitutionException; +import fr.ifremer.wao.services.service.MissingContactStateMotifException; +import fr.ifremer.wao.services.service.MissingContactTerrestrialLocationException; +import fr.ifremer.wao.services.service.UnwantedContactContactStateMotifException; +import fr.ifremer.wao.services.service.UpdateContactCommand; +import fr.ifremer.wao.web.WaoJsonActionSupport; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 4/3/14. + * + * @author Tony Chemit <chemit@codelutin.com> + * @since 4.0 + */ +public class ValidateContactJsonAction extends WaoJsonActionSupport implements Preparable { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ValidateContactJsonAction.class); + + /** + * Id of contact to treat. + */ + protected String contactId; + + /** + * New validation state. + */ + protected Boolean validationState; + + /** + * Success message + */ + protected String successMessage; + + /** + * Error message if validation, or any was wrong while update. + */ + protected String errorMessage; + + protected transient ContactsService service; + + protected UpdateContactCommand updateContactCommand; + + public void setService(ContactsService service) { + this.service = service; + } + + public void setContactId(String contactId) { + this.contactId = contactId; + } + + public void setValidationState(Boolean validationState) { + this.validationState = validationState; + } + + public String getContactId() { + return contactId; + } + + public Boolean getValidationState() { + return validationState; + } + + public String getSuccessMessage() { + return successMessage; + } + + public String getErrorMessage() { + return errorMessage; + } + + public boolean isSuccessful() { + return errorMessage == null; + } + + @Override + public void prepare() { + + Preconditions.checkState(StringUtils.isNotEmpty(contactId)); + + AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); + + updateContactCommand = service.newUpdateContactCommand( + session.getAuthenticatedWaoUser(), + Optional.of(contactId)); + + if (authenticatedWaoUser.isAdmin()) { + updateContactCommand.setValidationProgram(validationState); + } else { + updateContactCommand.setValidationCompany(validationState); + } + } + + @Override + public String execute() { + + AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); + + try { + service.validate(authenticatedWaoUser, updateContactCommand, true); + } catch (ContactNotUpdatableException e) { + session.addErrorMessages(t("wao.ui.contacts.validation.failure.not.updatable")); + + } catch (UnwantedContactContactStateMotifException e) { + errorMessage = t("wao.ui.form.Contact.error.unwantedContactStateMotif"); + + } catch (MissingContactNbObservantsException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + errorMessage = t("wao.ui.form.Contact.error.missingObserver", state); + + } catch (MissingContactObservationEndDateException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + errorMessage = t("wao.ui.form.Contact.error.missingObservationEndDate", state); + + } catch (ContactDataInputDateBeforeObservationEndDateException e) { + errorMessage = t("wao.ui.form.Contact.error.dataInputDateBeforeObservationEndDate"); + + } catch (InvalidContactObservationBeginDateException e) { + errorMessage = t("wao.ui.form.Contact.error.invalidObservationBeginDate"); + + } catch (MissingContactRestitutionException e) { + errorMessage = t("wao.ui.form.Contact.error.missingRestitution"); + + } catch (ContactDataInputDateAfterTodayException e) { + errorMessage = t("wao.ui.form.Contact.error.dataInputDateAfterToday"); + + } catch (MissingContactCommentException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + errorMessage = t("wao.ui.form.Contact.error.missingComment", state); + + } catch (MismatchContactMainObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + errorMessage = t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName); + + } catch (ContactRestitutionDateBeforeDataInputDateException e) { + errorMessage = t("wao.ui.form.Contact.error.transmissionDateBeforeDataInputDate"); + + } catch (ContactObservationEndDateBeforeBeginDateException e) { + errorMessage = t("wao.ui.form.Contact.error.observationEndDateBeforeBeginDate"); + + } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { + errorMessage = t("wao.ui.form.Contact.error.duplicatedMainObserverInSecondaryObservers"); + + } catch (MissingContactDataReliabilityException e) { + errorMessage = t("wao.ui.form.Contact.error.missingDataReliability"); + + } catch (MismatchContactSecondaryObserverCompanyException e) { + String companyName = e.getCompany().getName(); + String observerLogin = e.getObserver().getLogin(); + errorMessage = t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName); + + } catch (MissingContactObservedDataControlException e) { + errorMessage = t("wao.ui.form.Contact.error.missingObservedDataControl"); + + } catch (ContactWithObservedDataControlToCorrectionAskedException e) { + errorMessage = t("wao.ui.form.Contact.error.observedDataControlToCorrectionAsked"); + + } catch (MissingContactStateMotifException e) { + errorMessage = t("wao.ui.form.Contact.error.missingContactStateMotif"); + + } catch (MissingContactDataInputDateException e) { + errorMessage = t("wao.ui.form.Contact.error.missingDataInputDate"); + + } catch (MissingContactMainObserverException e) { + errorMessage = t("wao.ui.form.Contact.error.missingMainObserver"); + + } catch (MissingContactCommentAdminException e) { + String dataReliability = WaoUtils.l(getLocale(), e.getContact().getDataReliability()); + errorMessage = t("wao.ui.form.Contact.error.missingCommentAdmin", dataReliability); + + } catch (ContactObservationEndDateAfterTodayException e) { + errorMessage = t("wao.ui.form.Contact.error.observationEndDateAfterToday"); + + } catch (MissingContactObservationBeginDateException e) { + String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); + errorMessage = t("wao.ui.form.Contact.error.missingObservationBeginDate", state); + + } catch (MissingContactTerrestrialLocationException e) { + errorMessage = t("wao.ui.form.Contact.error.missingContactTerrestrialLocation"); + + } catch (MissingContactMammalsInfoException e) { + errorMessage = t("wao.ui.form.Contact.error.missingContactMammalsInfo"); + + } + + if (isSuccessful()) { + + try { + service.save(updateContactCommand, true); + } catch (ContactNotUpdatableException e) { + throw new WaoTechnicalException("should never occur", e); + } + if (validationState == null) { + successMessage = t("wao.ui.contacts.validation.to.unvalidate.state.success"); + } else if (validationState) { + successMessage = t("wao.ui.contacts.validation.to.accept.state.success"); + } else { + successMessage = t("wao.ui.contacts.validation.to.reject.state.success"); + } + } + + return SUCCESS; + } + + public boolean isAcceptable(Contact contact) { + boolean acceptable; + if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + acceptable = contact.isAcceptableByCompany(); + } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + acceptable = contact.isAcceptableByProgram(); + } else { + throw new IllegalStateException(); + } + return acceptable; + } + + public boolean isRefusable(Contact contact) { + boolean refuseable; + if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + refuseable = contact.isRefusableByCompany(); + } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + refuseable = contact.isRefusableByProgram(); + } else { + throw new IllegalStateException(); + } + return refuseable; + } + + public boolean isUnacceptable(Contact contact) { + boolean unacceptable; + if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { + unacceptable = contact.isUnacceptableByCompany(); + } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { + unacceptable = contact.isUnacceptableByProgram(); + } else { + throw new IllegalStateException(); + } + return unacceptable; + } + + public Boolean getValidationProgram() { + return updateContactCommand.getContact().getValidationProgram(); + } + + public Boolean getValidationCompany() { + return updateContactCommand.getContact().getValidationCompany(); + } + +} Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,249 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.base.Objects; -import com.opensymphony.xwork2.Preparable; -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.WaoUtils; -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.entity.ContactState; -import fr.ifremer.wao.entity.DCF5Code; -import fr.ifremer.wao.entity.FishingZone; -import fr.ifremer.wao.entity.SampleRow; -import fr.ifremer.wao.services.service.ContactsFilterValues; -import fr.ifremer.wao.services.service.ObsMerContactsList; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.WaoJspActionSupport; -import org.apache.commons.lang3.time.DateUtils; -import org.nuiton.util.pagination.PaginationParameter; -import org.nuiton.util.pagination.PaginationResult; - -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -public class ContactsAction extends WaoJspActionSupport implements Preparable { - - private static final long serialVersionUID = 1L; - - protected transient ObsMerContactsService service; - - protected int pageNumber; - - protected long firstRangePage; - - protected long lastRangePage; - - /** - * Contacts filter. - */ - protected ContactsFilter filter; - - /** - * List of contacts according to the input pager and filter. - */ - protected ObsMerContactsList contactsList; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public void setPageNumber(int pageNumber) { - this.pageNumber = pageNumber; - } - - public long getFirstRangePage() { - return firstRangePage; - } - - public long getLastRangePage() { - return lastRangePage; - } - - public ContactsFilter getFilter() { - if (filter == null) { - prepare(); - } - return filter; - } - - public List<Contact> getContacts() { - return contactsList.getContacts().getElements(); - } - - public ContactsFilterValues getFilterValues() { - return contactsList.getFilterValues(); - } - - public PaginationResult<Contact> getPagination() { - return contactsList.getContacts(); - } - - @Override - public void prepare() { - - if (filter == null) { - filter = service.newContactFilter(getAuthenticatedWaoUser()); - } - - } - - @Override - public String execute() { - - filter = Objects.firstNonNull(session.getContactsFilter(), filter); - - return applyFilter(); - - } - - public String resetFilter() { - - filter = service.newContactFilter(getAuthenticatedWaoUser()); - - return applyFilter(); - - } - - public String applyFilter() { - - getSession().setContactsFilter(filter); - - PaginationParameter pager = service.newContactsPaginationParameter(pageNumber, 25); - contactsList = service.getContactsList(getAuthenticatedWaoUser(), filter, pager); - - firstRangePage = getPaginationFirstPage(contactsList.getContacts(), 10); - lastRangePage = getPaginationLastPage(contactsList.getContacts(), 10, firstRangePage); - - return SUCCESS; - - } - - protected Date now = new Date(); - - public String getFilterPeriodFromPlaceholder() { - String placeholder = formatDateTime(DateUtils.addMonths(now, 1)); - return placeholder; - } - - public String getFilterPeriodToPlaceholder() { - String placeholder = formatDateTime(DateUtils.addYears(now, 1)); - return placeholder; - } - - public boolean isFullView() { - boolean fullView = getAuthenticatedWaoUser().isAdmin() || getAuthenticatedWaoUser().isProfessional(); - return fullView; - } - - public String getMammalsInfo(Contact contact) { - return escapeForToolTip(contact.getMammalsInfo()); - } - - public boolean isBoardingDone(Contact contact) { - return ContactState.OBSERVATION_DONE == contact.getContactState(); - } - - public String getDivision(SampleRow sampleRow) { - String result = ""; - for (FishingZone zone : sampleRow.getFishingZone()) { - result += zone.getDistrictCode() + " "; - } - return result; - } - - /** - * Devrait résoudre un problème que pose le composant ck/tooltip. - * <p/> - * Voir ANO#606 - */ - public static String escapeForToolTip(String str) { - String result = str.replaceAll("\r\n", "\n"); - result = result.replaceAll("\n", "<br />"); - result = result.replaceAll("'", "’"); - result = result.replaceAll("\"", """); - result = result.replaceAll("%", "%"); - return result; - } - - public String getContactToHighlightId() { - return session.getContactToHighlightId(); - } - - public Map<String, String> getDcf5CodesAndDescriptions(SampleRow sampleRow) { - Map<String, String> dcf5CodesAndDescriptions = new LinkedHashMap<>(); - for (DCF5Code dcf5Code : sampleRow.getdCF5Code()) { - String key = dcf5Code.getCode(); - String description = dcf5Code.getFishingGearCode() + " - " + WaoUtils.l(getLocale(), dcf5Code.getFishingGearDCF()); - if (dcf5Code.getTargetSpeciesCode() != null) { - description += " ; " + dcf5Code.getTargetSpeciesCode() + " - " + WaoUtils.l(getLocale(), dcf5Code.getTargetSpeciesDCF()); - } - dcf5CodesAndDescriptions.put(key, description); - } - return dcf5CodesAndDescriptions; - } - - public boolean isAcceptable(Contact contact) { - boolean acceptable; - if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - acceptable = contact.isAcceptableByCompany(); - } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - acceptable = contact.isAcceptableByProgram(); - } else { - throw new IllegalStateException(); - } - return acceptable; - } - - public boolean isRefusable(Contact contact) { - boolean refuseable; - if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - refuseable = contact.isRefusableByCompany(); - } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - refuseable = contact.isRefusableByProgram(); - } else { - throw new IllegalStateException(); - } - return refuseable; - } - - public boolean isUnacceptable(Contact contact) { - boolean unacceptable; - if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - unacceptable = contact.isUnacceptableByCompany(); - } else if (getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - unacceptable = contact.isUnacceptableByProgram(); - } else { - throw new IllegalStateException(); - } - return unacceptable; - } - -} \ No newline at end of file Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsFilterValuesJsonAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsFilterValuesJsonAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ContactsFilterValuesJsonAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,77 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.opensymphony.xwork2.Preparable; -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.services.service.ContactsFilterValues; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.WaoJsonActionSupport; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -public class ContactsFilterValuesJsonAction extends WaoJsonActionSupport implements Preparable { - - private static final long serialVersionUID = 1L; - - protected transient ObsMerContactsService service; - - protected ContactsFilter filter; - - protected ContactsFilterValues filterValues; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - - public ContactsFilter getFilter() { - if (filter == null) { - prepare(); - } - return filter; - } - - public ContactsFilterValues getFilterValues() { - return filterValues; - } - - @Override - public void prepare() { - - filter = service.newContactFilter(session.getAuthenticatedWaoUser()); - } - - @Override - public String execute() { - - filterValues = service.getContactsFilterValues(session.getAuthenticatedWaoUser(), filter); - - return SUCCESS; - - } - -} \ No newline at end of file Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/CreateContactAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/CreateContactAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/CreateContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,45 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.WaoJspActionSupport; -import org.apache.struts2.convention.annotation.Result; -import org.apache.struts2.convention.annotation.Results; - -@Results({ - @Result(name="success", type="redirectAction", params = { "actionName", "contacts" }) -}) -public class CreateContactAction extends WaoJspActionSupport { - - protected ObsMerContactsService service; - - protected String boatId; - - protected String sampleRowId; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public void setBoatId(String boatId) { - this.boatId = boatId; - } - - public void setSampleRowId(String sampleRowId) { - this.sampleRowId = sampleRowId; - } - - @Override - public String execute() { - - Contact contact = service.createContact(getAuthenticatedWaoUser(), sampleRowId, boatId); - - session.setStartBoatSelectionForSampleRowId(null); - - session.setContactToHighlightId(contact.getTopiaId()); - - return SUCCESS; - - } - -} Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/DeleteContactAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/DeleteContactAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/DeleteContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,84 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.services.service.IllegalDeletionException; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.WaoJspActionSupport; -import org.apache.struts2.convention.annotation.Result; -import org.apache.struts2.convention.annotation.Results; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -@Results({ - @Result(name = "error", type = "redirectAction", params = {"actionName", "edit-contact!input", "contactId", "%{contactId}"}), - @Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"}) - }) -public class DeleteContactAction extends WaoJspActionSupport { - - private static final long serialVersionUID = 1L; - - protected String contactId; - - protected transient ObsMerContactsService service; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public void setContactId(String contactId) { - this.contactId = contactId; - } - - public String getContactId() { - return contactId; - } - - @Override - public String execute() { - - Contact contact = service.getContact(contactId); - String contactCode = contact.getMainObserver().getFullName(); - - String result; - try { - service.delete(contactId); - - session.addMessage(t("wao.ui.action.deleteContact.success", contactCode)); - - result = SUCCESS; - - } catch (IllegalDeletionException e) { - - session.addErrorMessages(t("wao.ui.action.deleteContact.failure", contactCode)); - session.addErrorMessages(e.getExplanation(getLocale())); - - result = ERROR; - } - return result; - } -} Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/EditContactAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/EditContactAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/EditContactAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,317 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.base.Optional; -import com.google.common.base.Strings; -import com.google.common.collect.Sets; -import com.opensymphony.xwork2.Preparable; -import fr.ifremer.wao.WaoUtils; -import fr.ifremer.wao.entity.ContactState; -import fr.ifremer.wao.entity.ContactStateMotif; -import fr.ifremer.wao.entity.DataReliability; -import fr.ifremer.wao.entity.ObservedDataControl; -import fr.ifremer.wao.entity.WaoUser; -import fr.ifremer.wao.entity.WaoUsers; -import fr.ifremer.wao.services.AuthenticatedWaoUser; -import fr.ifremer.wao.services.service.ContactDataInputDateAfterTodayException; -import fr.ifremer.wao.services.service.ContactDataInputDateBeforeObservationEndDateException; -import fr.ifremer.wao.services.service.ContactNotUpdatableException; -import fr.ifremer.wao.services.service.ContactObservationEndDateAfterTodayException; -import fr.ifremer.wao.services.service.ContactObservationEndDateBeforeBeginDateException; -import fr.ifremer.wao.services.service.ContactRestitutionDateBeforeDataInputDateException; -import fr.ifremer.wao.services.service.ContactWithObservedDataControlToCorrectionAskedException; -import fr.ifremer.wao.services.service.DuplicatedContactMainObserverInSecondaryObserversException; -import fr.ifremer.wao.services.service.InvalidContactObservationBeginDateException; -import fr.ifremer.wao.services.service.MismatchContactMainObserverCompanyException; -import fr.ifremer.wao.services.service.MismatchContactSecondaryObserverCompanyException; -import fr.ifremer.wao.services.service.MissingContactCommentAdminException; -import fr.ifremer.wao.services.service.MissingContactCommentException; -import fr.ifremer.wao.services.service.MissingContactDataInputDateException; -import fr.ifremer.wao.services.service.MissingContactDataReliabilityException; -import fr.ifremer.wao.services.service.MissingContactMainObserverException; -import fr.ifremer.wao.services.service.MissingContactMammalsInfoException; -import fr.ifremer.wao.services.service.MissingContactNbObservantsException; -import fr.ifremer.wao.services.service.MissingContactObservationBeginDateException; -import fr.ifremer.wao.services.service.MissingContactObservationEndDateException; -import fr.ifremer.wao.services.service.MissingContactObservedDataControlException; -import fr.ifremer.wao.services.service.MissingContactRestitutionException; -import fr.ifremer.wao.services.service.MissingContactStateMotifException; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.services.service.UnwantedContactContactStateMotifException; -import fr.ifremer.wao.services.service.UpdateContactCommand; -import fr.ifremer.wao.services.service.administration.ReferentialService; -import fr.ifremer.wao.services.service.administration.WaoUsersService; -import fr.ifremer.wao.web.WaoJspActionSupport; -import org.apache.struts2.convention.annotation.Result; -import org.apache.struts2.convention.annotation.Results; - -import java.util.Date; -import java.util.EnumMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Created on 4/6/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -@Results({@Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"})}) -public class EditContactAction extends WaoJspActionSupport implements Preparable { - - private static final long serialVersionUID = 1L; - - /** - * Id of contact to edit. - */ - protected Optional<String> optionalContactId = Optional.absent(); - - protected Map<String, String> observers; - - protected Map<ContactState, String> contactStates; - - protected Map<String, String> contactStateMotives; - - protected Map<ObservedDataControl, String> observedDataControls; - - protected Map<DataReliability, String> dataReliabilities; - - protected transient ObsMerContactsService service; - - protected transient WaoUsersService waoUsersService; - - protected transient ReferentialService referentialService; - - protected UpdateContactCommand updateContactCommand; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public void setWaoUsersService(WaoUsersService waoUsersService) { - this.waoUsersService = waoUsersService; - } - - public void setReferentialService(ReferentialService referentialService) { - this.referentialService = referentialService; - } - - public void setContactId(String contactId) { - this.optionalContactId = Optional.fromNullable(Strings.emptyToNull(contactId)); - } - - public String getContactId() { - return optionalContactId.orNull(); - } - - public UpdateContactCommand getUpdateContactCommand() { - if (updateContactCommand == null) { - prepare(); - } - return updateContactCommand; - } - - public Map<String, String> getObservers() { - if (observers == null) { - prepare(); - } - return observers; - } - - public Map<ContactState, String> getContactStates() { - if (contactStates == null) { - prepare(); - } - return contactStates; - } - - public Map<String, String> getContactStateMotives() { - if (contactStateMotives == null) { - prepare(); - } - return contactStateMotives; - } - - public Map<ObservedDataControl, String> getObservedDataControls() { - if (observedDataControls == null) { - prepare(); - } - return observedDataControls; - } - - public Map<DataReliability, String> getDataReliabilities() { - if (dataReliabilities == null) { - prepare(); - } - return dataReliabilities; - } - - public String getDateTimePlaceholder() { - return formatDateTime(new Date()); - } - - public String getDatePlaceholder() { - return formatDate(new Date()); - } - - @Override - public void prepare() { - - updateContactCommand = service.newUpdateContactCommand(getAuthenticatedWaoUser(), optionalContactId); - - List<WaoUser> waoUsers = waoUsersService.getActiveWaoUsers(Optional.of(updateContactCommand.getContact().getSampleRow().getCompany().getTopiaId())); - Set<WaoUser> sortedWaoUsers = Sets.newTreeSet(WaoUsers.fullNameComparator()); - sortedWaoUsers.addAll(waoUsers); - observers = new LinkedHashMap<>(); - for (WaoUser waoUser : sortedWaoUsers) { - observers.put(waoUser.getTopiaId(), waoUser.getFullName()); - } - contactStates = new EnumMap<>(ContactState.class); - for (ContactState contactState : ContactState.getAllowedStates(getAuthenticatedWaoUser().getObsProgram())) { - contactStates.put(contactState, WaoUtils.l(getLocale(), contactState)); - } - - contactStateMotives = new TreeMap<>(); - for (ContactStateMotif contactStateMotif : referentialService.getAllContactStateMotifs(null)) { - contactStateMotives.put(contactStateMotif.getTopiaId(), contactStateMotif.getName()); - } - - observedDataControls = new EnumMap<>(ObservedDataControl.class); - for (ObservedDataControl observedDataControl : ObservedDataControl.values()) { - observedDataControls.put(observedDataControl, WaoUtils.l(getLocale(), observedDataControl)); - } - - dataReliabilities = new EnumMap<>(DataReliability.class); - for (DataReliability dataReliability : DataReliability.values()) { - dataReliabilities.put(dataReliability, WaoUtils.l(getLocale(), dataReliability)); - } - } - - @Override - public void validate() { - - service.preValidate(updateContactCommand); - - AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); - - try { - service.validate(authenticatedWaoUser, updateContactCommand, true); - } catch (ContactNotUpdatableException e) { - session.addErrorMessages(t("wao.ui.contacts.validation.failure.not.updatable")); - - } catch (UnwantedContactContactStateMotifException e) { - addFieldError("updateContactCommand.contact.contactStateMotif", t("wao.ui.form.Contact.error.unwantedContactStateMotif")); - - } catch (MissingContactNbObservantsException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - addFieldError("updateContactCommand.contact.nbObservants", t("wao.ui.form.Contact.error.missingObserver", state)); - - } catch (MissingContactObservationEndDateException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.missingObservationEndDate", state)); - - } catch (ContactDataInputDateBeforeObservationEndDateException e) { - addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.dataInputDateBeforeObservationEndDate")); - - } catch (InvalidContactObservationBeginDateException e) { - addFieldError("updateContactCommand.contact.observationBeginDate", t("wao.ui.form.Contact.error.invalidObservationBeginDate")); - - } catch (MissingContactRestitutionException e) { - addFieldError("updateContactCommand.contact.restitution", t("wao.ui.form.Contact.error.missingRestitution")); - - } catch (ContactDataInputDateAfterTodayException e) { - addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.dataInputDateAfterToday")); - - } catch (MissingContactCommentException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - addFieldError("updateContactCommand.contact.comment", t("wao.ui.form.Contact.error.missingComment", state)); - - } catch (MismatchContactMainObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - addFieldError("updateContactCommand.contact.mainObserver", t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName)); - - } catch (ContactRestitutionDateBeforeDataInputDateException e) { - addFieldError("updateContactCommand.contact.restitution", t("wao.ui.form.Contact.error.transmissionDateBeforeDataInputDate")); - - } catch (ContactObservationEndDateBeforeBeginDateException e) { - addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.observationEndDateBeforeBeginDate")); - - } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { - addFieldError("updateContactCommand.contact.secondaryObservers", t("wao.ui.form.Contact.error.duplicatedMainObserverInSecondaryObservers")); - - } catch (MissingContactDataReliabilityException e) { - addFieldError("updateContactCommand.contact.dataReliability", t("wao.ui.form.Contact.error.missingDataReliability")); - - } catch (MismatchContactSecondaryObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - addFieldError("updateContactCommand.contact.secondaryObservers", t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName)); - - } catch (MissingContactObservedDataControlException e) { - addFieldError("updateContactCommand.contact.observedDataControl", t("wao.ui.form.Contact.error.missingObservedDataControl")); - - } catch (ContactWithObservedDataControlToCorrectionAskedException e) { - addFieldError("updateContactCommand.contact.observedDataControl", t("wao.ui.form.Contact.error.observedDataControlToCorrectionAsked")); - - } catch (MissingContactStateMotifException e) { - addFieldError("updateContactCommand.contact.contactStateMotif", t("wao.ui.form.Contact.error.missingContactStateMotif")); - - } catch (MissingContactDataInputDateException e) { - addFieldError("updateContactCommand.contact.dataInputDate", t("wao.ui.form.Contact.error.missingDataInputDate")); - - } catch (MissingContactMainObserverException e) { - addFieldError("updateContactCommand.contact.mainObserver", t("wao.ui.form.Contact.error.missingMainObserver")); - - } catch (MissingContactCommentAdminException e) { - String dataReliability = WaoUtils.l(getLocale(), e.getContact().getDataReliability()); - addFieldError("updateContactCommand.contact.commentAdmin", t("wao.ui.form.Contact.error.missingCommentAdmin", dataReliability)); - - } catch (ContactObservationEndDateAfterTodayException e) { - addFieldError("updateContactCommand.contact.observationEndDate", t("wao.ui.form.Contact.error.observationEndDateAfterToday")); - - } catch (MissingContactObservationBeginDateException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - addFieldError("updateContactCommand.contact.observationBeginDate", t("wao.ui.form.Contact.error.missingObservationBeginDate", state)); - - } catch (MissingContactMammalsInfoException e) { - addFieldError("updateContactCommand.contact.mammalsInfo", t("wao.ui.form.Contact.error.missingMammalsInfo")); - - } - } - - @Override - public String execute() throws Exception { - - service.save(updateContactCommand, false); - - session.addMessage(t("wao.ui.form.updateContactCommand.success")); - - session.setContactToHighlightId(updateContactCommand.getContact().getTopiaId()); - return SUCCESS; - } - -} \ No newline at end of file Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ExportContactsAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ExportContactsAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ExportContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,75 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.opensymphony.xwork2.Preparable; -import fr.ifremer.wao.ContactsFilter; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.action.AbstractDownloadCsvAction; - -import java.io.InputStream; -import java.util.Date; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -public class ExportContactsAction extends AbstractDownloadCsvAction implements Preparable { - - private static final long serialVersionUID = 1L; - - protected transient ObsMerContactsService service; - - protected ContactsFilter filter; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public ContactsFilter getFilter() { - if (filter == null) { - prepare(); - } - return filter; - } - - @Override - public void prepare() { - - filter = service.newContactFilter(getAuthenticatedWaoUser()); - } - - @Override - public String getFileName() { - - return "contacts_" + getObsProgram().name() + "_" + dateFormat.format(new Date()) + ".csv"; - } - - @Override - public InputStream getInputStream() { - - return service.exportContacts(filter); - } - -} \ No newline at end of file Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ImportContactsAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ImportContactsAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ImportContactsAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,62 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import fr.ifremer.wao.services.service.ImportErrorException; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.web.action.AbstractImportCsvAction; -import org.apache.struts2.convention.annotation.Result; -import org.apache.struts2.convention.annotation.Results; - -import java.io.InputStream; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -@Results({ - @Result(name = "error", type = "redirectAction", params = {"actionName", "import-contacts!input"}), - @Result(name = "success", type = "redirectAction", params = {"actionName", "contacts"}) - }) -public class ImportContactsAction extends AbstractImportCsvAction { - - private static final long serialVersionUID = 1L; - - protected transient ObsMerContactsService contactsService; - - public void setService(ObsMerContactsService contactsService) { - this.contactsService = contactsService; - } - - @Override - protected void importCsv(InputStream csvInputStream) throws ImportErrorException { - contactsService.importContacts(getAuthenticatedWaoUser(), csvInputStream); - } - - @Override - protected String getSuccessMessage() { - return t("wao.ui.import.contacts.success"); - } - -} \ No newline at end of file Deleted: branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ValidateContactJsonAction.java =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ValidateContactJsonAction.java 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/java/fr/ifremer/wao/web/action/obsmer/ValidateContactJsonAction.java 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,303 +0,0 @@ -package fr.ifremer.wao.web.action.obsmer; - -/* - * #%L - * Wao :: Web - * %% - * Copyright (C) 2009 - 2014 Ifremer - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * #L% - */ - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.opensymphony.xwork2.Preparable; -import fr.ifremer.wao.WaoTechnicalException; -import fr.ifremer.wao.WaoUtils; -import fr.ifremer.wao.entity.Contact; -import fr.ifremer.wao.services.AuthenticatedWaoUser; -import fr.ifremer.wao.services.service.ContactDataInputDateBeforeObservationEndDateException; -import fr.ifremer.wao.services.service.ContactDataInputDateAfterTodayException; -import fr.ifremer.wao.services.service.ContactNotUpdatableException; -import fr.ifremer.wao.services.service.ContactObservationEndDateAfterTodayException; -import fr.ifremer.wao.services.service.ContactObservationEndDateBeforeBeginDateException; -import fr.ifremer.wao.services.service.ContactRestitutionDateBeforeDataInputDateException; -import fr.ifremer.wao.services.service.ContactWithObservedDataControlToCorrectionAskedException; -import fr.ifremer.wao.services.service.DuplicatedContactMainObserverInSecondaryObserversException; -import fr.ifremer.wao.services.service.InvalidContactObservationBeginDateException; -import fr.ifremer.wao.services.service.MismatchContactMainObserverCompanyException; -import fr.ifremer.wao.services.service.MismatchContactSecondaryObserverCompanyException; -import fr.ifremer.wao.services.service.MissingContactCommentAdminException; -import fr.ifremer.wao.services.service.MissingContactCommentException; -import fr.ifremer.wao.services.service.MissingContactDataInputDateException; -import fr.ifremer.wao.services.service.MissingContactDataReliabilityException; -import fr.ifremer.wao.services.service.MissingContactMainObserverException; -import fr.ifremer.wao.services.service.MissingContactNbObservantsException; -import fr.ifremer.wao.services.service.MissingContactObservationBeginDateException; -import fr.ifremer.wao.services.service.MissingContactObservationEndDateException; -import fr.ifremer.wao.services.service.MissingContactObservedDataControlException; -import fr.ifremer.wao.services.service.MissingContactRestitutionException; -import fr.ifremer.wao.services.service.MissingContactStateMotifException; -import fr.ifremer.wao.services.service.UnwantedContactContactStateMotifException; -import fr.ifremer.wao.services.service.ObsMerContactsService; -import fr.ifremer.wao.services.service.UpdateContactCommand; -import fr.ifremer.wao.web.WaoJsonActionSupport; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 4/3/14. - * - * @author Tony Chemit <chemit@codelutin.com> - * @since 4.0 - */ -public class ValidateContactJsonAction extends WaoJsonActionSupport implements Preparable { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ValidateContactJsonAction.class); - - /** - * Id of contact to treat. - */ - protected String contactId; - - /** - * New validation state. - */ - protected Boolean validationState; - - /** - * Success message - */ - protected String successMessage; - - /** - * Error message if validation, or any was wrong while update. - */ - protected String errorMessage; - - protected transient ObsMerContactsService service; - - protected UpdateContactCommand updateContactCommand; - - public void setService(ObsMerContactsService service) { - this.service = service; - } - - public void setContactId(String contactId) { - this.contactId = contactId; - } - - public void setValidationState(Boolean validationState) { - this.validationState = validationState; - } - - public String getContactId() { - return contactId; - } - - public Boolean getValidationState() { - return validationState; - } - - public String getSuccessMessage() { - return successMessage; - } - - public String getErrorMessage() { - return errorMessage; - } - - public boolean isSuccessful() { - return errorMessage == null; - } - - @Override - public void prepare() { - - Preconditions.checkState(StringUtils.isNotEmpty(contactId)); - - AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); - - updateContactCommand = service.newUpdateContactCommand( - session.getAuthenticatedWaoUser(), - Optional.of(contactId)); - - if (authenticatedWaoUser.isAdmin()) { - updateContactCommand.setValidationProgram(validationState); - } else { - updateContactCommand.setValidationCompany(validationState); - } - } - - @Override - public String execute() { - - AuthenticatedWaoUser authenticatedWaoUser = session.getAuthenticatedWaoUser(); - - try { - service.validate(authenticatedWaoUser, updateContactCommand, true); - } catch (ContactNotUpdatableException e) { - session.addErrorMessages(t("wao.ui.contacts.validation.failure.not.updatable")); - - } catch (UnwantedContactContactStateMotifException e) { - errorMessage = t("wao.ui.form.Contact.error.unwantedContactStateMotif"); - - } catch (MissingContactNbObservantsException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - errorMessage = t("wao.ui.form.Contact.error.missingObserver", state); - - } catch (MissingContactObservationEndDateException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - errorMessage = t("wao.ui.form.Contact.error.missingObservationEndDate", state); - - } catch (ContactDataInputDateBeforeObservationEndDateException e) { - errorMessage = t("wao.ui.form.Contact.error.dataInputDateBeforeObservationEndDate"); - - } catch (InvalidContactObservationBeginDateException e) { - errorMessage = t("wao.ui.form.Contact.error.invalidObservationBeginDate"); - - } catch (MissingContactRestitutionException e) { - errorMessage = t("wao.ui.form.Contact.error.missingRestitution"); - - } catch (ContactDataInputDateAfterTodayException e) { - errorMessage = t("wao.ui.form.Contact.error.dataInputDateAfterToday"); - - } catch (MissingContactCommentException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - errorMessage = t("wao.ui.form.Contact.error.missingComment", state); - - } catch (MismatchContactMainObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - errorMessage = t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName); - - } catch (ContactRestitutionDateBeforeDataInputDateException e) { - errorMessage = t("wao.ui.form.Contact.error.transmissionDateBeforeDataInputDate"); - - } catch (ContactObservationEndDateBeforeBeginDateException e) { - errorMessage = t("wao.ui.form.Contact.error.observationEndDateBeforeBeginDate"); - - } catch (DuplicatedContactMainObserverInSecondaryObserversException e) { - errorMessage = t("wao.ui.form.Contact.error.duplicatedMainObserverInSecondaryObservers"); - - } catch (MissingContactDataReliabilityException e) { - errorMessage = t("wao.ui.form.Contact.error.missingDataReliability"); - - } catch (MismatchContactSecondaryObserverCompanyException e) { - String companyName = e.getCompany().getName(); - String observerLogin = e.getObserver().getLogin(); - errorMessage = t("wao.ui.form.Contact.error.mismatchCompanyForObserver", observerLogin, companyName); - - } catch (MissingContactObservedDataControlException e) { - errorMessage = t("wao.ui.form.Contact.error.missingObservedDataControl"); - - } catch (ContactWithObservedDataControlToCorrectionAskedException e) { - errorMessage = t("wao.ui.form.Contact.error.observedDataControlToCorrectionAsked"); - - } catch (MissingContactStateMotifException e) { - errorMessage = t("wao.ui.form.Contact.error.missingContactStateMotif"); - - } catch (MissingContactDataInputDateException e) { - errorMessage = t("wao.ui.form.Contact.error.missingDataInputDate"); - - } catch (MissingContactMainObserverException e) { - errorMessage = t("wao.ui.form.Contact.error.missingMainObserver"); - - } catch (MissingContactCommentAdminException e) { - String dataReliability = WaoUtils.l(getLocale(), e.getContact().getDataReliability()); - errorMessage = t("wao.ui.form.Contact.error.missingCommentAdmin", dataReliability); - - } catch (ContactObservationEndDateAfterTodayException e) { - errorMessage = t("wao.ui.form.Contact.error.observationEndDateAfterToday"); - - } catch (MissingContactObservationBeginDateException e) { - String state = WaoUtils.l(getLocale(), e.getContact().getContactState()); - errorMessage = t("wao.ui.form.Contact.error.missingObservationBeginDate", state); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error(e); - } - errorMessage = t("wao.ui.contacts.validation.failure", e.getMessage()); - } - - if (isSuccessful()) { - - try { - service.save(updateContactCommand, true); - } catch (ContactNotUpdatableException e) { - throw new WaoTechnicalException("should never occur", e); - } - if (validationState == null) { - successMessage = t("wao.ui.contacts.validation.to.unvalidate.state.success"); - } else if (validationState) { - successMessage = t("wao.ui.contacts.validation.to.accept.state.success"); - } else { - successMessage = t("wao.ui.contacts.validation.to.reject.state.success"); - } - } - - return SUCCESS; - } - - public boolean isAcceptable(Contact contact) { - boolean acceptable; - if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - acceptable = contact.isAcceptableByCompany(); - } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - acceptable = contact.isAcceptableByProgram(); - } else { - throw new IllegalStateException(); - } - return acceptable; - } - - public boolean isRefusable(Contact contact) { - boolean refuseable; - if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - refuseable = contact.isRefusableByCompany(); - } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - refuseable = contact.isRefusableByProgram(); - } else { - throw new IllegalStateException(); - } - return refuseable; - } - - public boolean isUnacceptable(Contact contact) { - boolean unacceptable; - if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationCompany()) { - unacceptable = contact.isUnacceptableByCompany(); - } else if (session.getAuthenticatedWaoUser().isAuthorizedToChangeValidationProgram()) { - unacceptable = contact.isUnacceptableByProgram(); - } else { - throw new IllegalStateException(); - } - return unacceptable; - } - - public Boolean getValidationProgram() { - return updateContactCommand.getContact().getValidationProgram(); - } - - public Boolean getValidationCompany() { - return updateContactCommand.getContact().getValidationCompany(); - } - -} Copied: branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/ContactsAction-conversion.properties (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/obsmer/ContactsAction-conversion.properties) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/ContactsAction-conversion.properties (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/ContactsAction-conversion.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1 @@ +filter=org.nuiton.web.struts2.converters.JsonConverter Deleted: branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/obsmer/ContactsAction-conversion.properties =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/obsmer/ContactsAction-conversion.properties 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/resources/fr/ifremer/wao/web/action/obsmer/ContactsAction-conversion.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -1 +0,0 @@ -filter=org.nuiton.web.struts2.converters.JsonConverter Modified: branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_en_GB.properties =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_en_GB.properties 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_en_GB.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -290,7 +290,9 @@ wao.ui.form.Contact.error.mismatchCompanyForObserver=Observers must belong to the company attached to the sample row wao.ui.form.Contact.error.missingComment=The comment is mandatory wao.ui.form.Contact.error.missingCommentAdmin=The admin comment is mandatory +wao.ui.form.Contact.error.missingContactMammalsInfo= wao.ui.form.Contact.error.missingContactStateMotif=The contact state motif must be provided +wao.ui.form.Contact.error.missingContactTerrestrialLocation= wao.ui.form.Contact.error.missingDataInputDate=The data input date must be provided wao.ui.form.Contact.error.missingDataReliability=The data reliability must be provided wao.ui.form.Contact.error.missingMainObserver=The main observer must be provided Modified: branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_fr_FR.properties =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_fr_FR.properties 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/resources/i18n/wao-web_fr_FR.properties 2014-06-20 17:38:35 UTC (rev 2078) @@ -290,7 +290,9 @@ wao.ui.form.Contact.error.mismatchCompanyForObserver=L'observateur %s n'est pas membre de la société %s wao.ui.form.Contact.error.missingComment=Il faut préciser un commentaire pour l'état '%s' wao.ui.form.Contact.error.missingCommentAdmin=Il faut préciser dans le commentaire administrateur pourquoi la donnée est '%s' +wao.ui.form.Contact.error.missingContactMammalsInfo= wao.ui.form.Contact.error.missingContactStateMotif=Il faut préciser un motif de refus +wao.ui.form.Contact.error.missingContactTerrestrialLocation= wao.ui.form.Contact.error.missingDataInputDate=Il faut préciser une date de saisie des données en plus de la date de transmission de la restitution wao.ui.form.Contact.error.missingDataReliability=Il faut préciser la qualité de la donnée avant de valider wao.ui.form.Contact.error.missingMainObserver=Il faut au moins un observateur référant Copied: branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/contacts.jsp (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/contacts.jsp) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/contacts.jsp (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/contacts.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,593 @@ +<%-- + #%L + Wao :: Web + %% + Copyright (C) 2009 - 2014 Ifremer + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + #L% + --%> +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> +<%@taglib uri="/struts-tags" prefix="s" %> + +<html> + +<head> + <title> + <s:text name="wao.ui.page.Contacts.title"/> + </title> + + <script> + + $(document).ready(function () { + + var contactsFilterMappings = [ + <s:if test="authenticatedWaoUser.authorizedToViewOtherCompanies"> + { + filterName: 'sampleRowFilter.companyIds', + filterLabel: "<s:text name="wao.ui.entity.Company"/>", + filterValuesField: 'sampleRowsFilterValues.companies', + }, + </s:if> + { + filterName: 'sampleRowFilter.sampleRowCodes', + filterLabel: "<s:text name="wao.ui.field.SampleRow.code"/>", + filterValuesField: 'sampleRowsFilterValues.sampleRowCodes', + }, + { + filterName: 'sampleRowFilter.programNames', + filterLabel: "<s:text name="wao.ui.field.SampleRow.programName"/>", + filterValuesField: 'sampleRowsFilterValues.programNames', + }, + { + filterName: 'sampleRowFilter.fishingZoneFacadeNames', + filterLabel: "<s:text name="wao.ui.field.FishingZone.facadeName"/>", + filterValuesField: 'sampleRowsFilterValues.fishingZoneFacadeNames', + }, + { + filterName: 'sampleRowFilter.fishingZoneSectorNames', + filterLabel: "<s:text name="wao.ui.field.FishingZone.sectorName"/>", + filterValuesField: 'sampleRowsFilterValues.fishingZoneSectorNames', + }, + { + filterName: 'sampleRowFilter.fishingGearDcfIds', + filterLabel: "<s:text name="wao.ui.entity.fishingGearDCF"/>", + filterValuesField: 'sampleRowsFilterValues.fishingGearDcfs', + }, + { + filterName: 'sampleRowFilter.targetSpeciesDcfIds', + filterLabel: "<s:text name="wao.ui.entity.targetSpeciesDCF"/>", + filterValuesField: 'sampleRowsFilterValues.targetSpeciesDcfs', + }, + <s:if test="authenticatedWaoUser.authorizedToFilterOnBoats"> + { + filterName: 'boatFilter.boatIds', + filterLabel: "<s:text name="wao.ui.entity.Boat"/>", + filterValuesField: 'boatsFilterValues.boats', + minimumInputLength: 3 + }, + </s:if> + { + filterName: 'boatFilter.districtIds', + filterLabel: "<s:text name="wao.ui.field.Boat.district"/>", + filterValuesField: 'boatsFilterValues.districts' + }, + { + filterName: 'observerIds', + filterLabel: "<s:text name="wao.ui.misc.observer"/>", + filterValuesField: 'observers' + }, + { + filterName: 'contactStates', + filterLabel: "<s:text name="wao.ui.field.Contact.contactState"/>", + filterValuesField: 'contactStates' + }, + { + filterName: 'companyAcceptations', + filterLabel: "<s:text name="wao.ui.field.Contact.validationCompany"/>", + filterValuesField: 'companyAcceptations' + }, + { + filterName: 'programAcceptations', + filterLabel: "<s:text name="wao.ui.field.Contact.validationProgram"/>", + filterValuesField: 'programAcceptations' + }, + { + filterName: 'observedDataControls', + filterLabel: "<s:text name="wao.ui.field.Contact.observedDataControl"/>", + filterValuesField: 'observedDataControls' + }, + { + filterName: 'dataReliabilities', + filterLabel: "<s:text name="wao.ui.field.Contact.dataReliability"/>", + filterValuesField: 'dataReliabilities' + } + ]; + + filter = <s:property value="filter" escapeHtml="false"/>; + + contactsFilterController2 = new FilterController2(contactsFilterMappings, filter, WAO.CONTACTS_FILTER_VALUES_JSON_URL, $('#contacts-filters-form fieldset.extra-filters')); + contactsFilterController2.init(); + + $('#switch-compact-full-view').click(function () { + $('#switch-compact-full-view').toggleClass('full-view').toggleClass('compact-view'); + $('table.contacts-list').toggleClass('full-view').toggleClass('compact-view'); + }); + + $('.validation-action').click(function(e) { + e.preventDefault(); + var $action = $(this); + var url = $action.attr('href'); + var successCallback = function (data) { + var successful = data['successful']; + if (successful) { + var success = data['successMessage']; + WAO.notifications.success(success); + var $tr = $('#contacts-list').find('tr[data-contactId="' + data.contactId + '"]'); + $tr.removeClass('accepted-by-company refused-by-company accepted-by-program refused-by-program'); + if (data.validationCompany) { + $tr.addClass('accepted-by-company'); + } else if (data.validationCompany === false) { + $tr.addClass('refused-by-company'); + } + if (data.validationProgram) { + $tr.addClass('accepted-by-program'); + } else if (data.validationProgram === false) { + $tr.addClass('refused-by-program'); + } + } else { + var error = data['errorMessage']; + WAO.notifications.error(error); + } + }; + WAO.post(url, {}, successCallback); + }); + + // Do not expose any struts internal input fields + $('input[type="hidden"][id^="__"]').prop('disabled', true); + }); + + </script> + +</head> + +<content tag="mainClass">large</content> +<content tag="contactsMenuItemClass">active</content> + +<s:form method="GET" id="contacts-filters-form" cssClass="filters-form"> + + <fieldset> + + <s:textfield name="filter.periodFrom" + label="%{getText('wao.ui.form.periodFrom')}" + placeholder="%{getFilterPeriodFromPlaceholder()}" + cssClass="input-small"/> + + <s:textfield name="filter.periodTo" + label="%{getText('wao.ui.form.period.to')}" + placeholder="%{getFilterPeriodToPlaceholder()}" + cssClass="input-small"/> + + <div title="<s:text name="wao.ui.form.filterOnObservationBeginDate.tooltip"/>"> + <s:checkbox name="filter.filterOnObservationBeginDate" + label="%{getText('wao.ui.form.filterOnObservationBeginDate')}"/> + </div> + + </fieldset> + + <fieldset class="extra-filters"> + + </fieldset> + + <fieldset> + + <s:checkbox name="filter.mammalsObservationOnly" + label="%{getText('wao.ui.misc.observations')}"/> + + <s:checkbox name="filter.mammalsCaptureOnly" + label="%{getText('wao.ui.field.Contact.mammalsCapture')}"/> + + <s:checkbox name="filter.commentDefinedOnly" + label="%{getText('wao.ui.field.Contact.comment')}"/> + + <s:checkbox name="filter.commentCompanyDefinedOnly" + label="%{getText('wao.ui.field.Contact.commentCompany')}"/> + + <s:checkbox name="filter.commentAdminDefinedOnly" + label="%{getText('wao.ui.field.Contact.commentAdmin')}"/> + + </fieldset> + + <fieldset> + + <s:checkbox name="filter.sortedByBoardingDate" + label="%{getText('wao.ui.form.sortByTideBegin')}"/> + + </fieldset> + + <div class="form-actions"> + + <s:submit type="button" action="contacts!applyFilter" cssClass="btn btn-primary"> + <i class="icon-filter"></i> <s:text name="wao.ui.action.filter"/> + </s:submit> + + <s:submit type="button" action="contacts!resetFilter" cssClass="btn"> + <i class="icon-trash"></i> <s:text name="wao.ui.action.reset"/> + </s:submit> + + <s:if test="authenticatedWaoUser.authorizedToExportContacts"> + <s:submit action="export-contacts" type="button" cssClass="btn"> + <i class="icon-download"></i> <s:text name="wao.ui.action.csvExport"/> + </s:submit> + </s:if> + + </div> + +</s:form> + +<h3> + <s:text name="wao.ui.contacts.title"> + <s:param value="%{pagination.count}"/> + </s:text> +</h3> + +<s:set name="pagination"> + <%-- Pagination --%> + <div class="pagination"> + <ul> + <s:url var="fullUrl" includeParams="get"/> + <s:set var="paginationUrl" value="%{getPaginationUrl(#fullUrl)}"/> + <s:if test="firstRangePage > 2"> + <li> + <a href="${paginationUrl}0">1</a> + </li> + <li> + <a href="${paginationUrl}1">2</a> + </li> + <li> + <span>...</span> + </li> + </s:if> + + <s:iterator var="currentPage" begin="firstRangePage" end="lastRangePage"> + <li class="<s:if test="#currentPage - 1 == pagination.currentPage.pageNumber">active</s:if>"> + <a href="${paginationUrl}${currentPage - 1}"> + <s:property/> + </a> + </li> + </s:iterator> + + <s:if test="lastRangePage < pagination.pageCount - 1"> + <li> + <span>...</span> + </li> + <li> + <a href="${paginationUrl}${pagination.pageCount - 2}"> + <s:property value="pagination.pageCount - 1"/> + </a> + </li> + <li> + <a href="${paginationUrl}${pagination.pageCount - 1}"> + <s:property value="pagination.pageCount"/> + </a> + </li> + </s:if> + </ul> + </div> +</s:set> + +<s:set var="fullView" value="%{fullView}"/> + +<div class="sticky-buttons"> + <button type="button" id="switch-compact-full-view" class="btn <s:if test="fullView">full-view</s:if><s:else>compact-view</s:else>"> + <span class="only-in-compact-view"> + <i class="fa fa-expand"></i><span class="only-on-hover"> <s:text name="wao.ui.action.switchToFullView" /></span> + </span> + <span class="only-in-full-view"> + <i class="fa fa-compress"></i><span class="only-on-hover"> <s:text name="wao.ui.action.switchToCompactView" /></span> + </span> + </button> +</div> + + +<s:property value="#pagination" escapeHtml="false"/> + +<table id="contacts-list" class="contacts-list large-table table-striped <s:if test="fullView">full-view</s:if><s:else>compact-view</s:else>"> + <thead> + <tr> + <th><s:text name="wao.ui.field.Contact.creationDate"/></th> + <th><s:text name="wao.ui.contacts.boatName"/></th> + <th><s:text name="wao.ui.field.Contact.sampleRow"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.programName"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.professionCode"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.contacts.Profession.libelle"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.contacts.Profession.species"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.contacts.FishingZone.facadeName"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.contacts.FishingZone.sectorName"/></th> + <th class="only-in-full-view"><s:text name="wao.ui.contacts.division"/></th> + <s:if test="obsVente"> + <th><s:text name="wao.ui.field.Contact.terrestrialLocation"/></th> + </s:if> + <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.company"/></th> + <th><s:text name="wao.ui.contacts.observers"/></th> + <th><s:text name="wao.ui.field.Contact.contactState"/> (<s:text name="wao.ui.field.Contact.contactStateMotif"/>)</th> + <th class="date-time"><s:text name="wao.ui.field.Contact.beginDate"/></th> + <th class="date-time"><s:text name="wao.ui.field.Contact.endDate"/></th> + <s:if test="obsMer"> + <th class="date-time"><s:text name="wao.ui.field.Contact.observationTimeInDays"/></th> + </s:if> + <th class="date"><s:text name="wao.ui.field.Contact.dataInputDate"/></th> + <s:if test="obsMer"> + <th><s:text name="wao.ui.field.Contact.observedDataControl"/></th> + <th class="date"><s:text name="wao.ui.field.Contact.restitution"/></th> + <th><s:text name="wao.ui.contacts.observations"/></th> + </s:if> + <s:if test="obsVente"> + <th><s:text name="wao.ui.field.Contact.samplingStrategy"/></th> + <th><s:text name="wao.ui.field.Contact.completeSampling"/></th> + </s:if> + <s:if test="authenticatedWaoUser.authorizedToViewContactsComments"> + <th><s:text name="wao.ui.field.Contact.comment"/></th> + <th><s:text name="wao.ui.field.Contact.commentCompany"/></th> + <th><s:text name="wao.ui.field.Contact.commentAdmin"/></th> + </s:if> + <s:if test="obsMer"> + <th><s:text name="wao.ui.field.Contact.dataReliability"/></th> + </s:if> + <th><s:text name="wao.ui.contacts.validation"/></th> + <th><s:text name="wao.ui.actions"/></th> + </tr> + </thead> + <tbody> + + <s:iterator value="contacts" var="contact"> + <s:set name="trCssClasses">contact-row<s:if test="topiaId.equals(contactToHighlightId)"> highlight</s:if><s:if test="validationCompany==null"></s:if><s:elseif test="validationCompany"> accepted-by-company</s:elseif><s:else> refused-by-company</s:else><s:if test="validationProgram==null"></s:if><s:elseif test="validationProgram"> accepted-by-program</s:elseif><s:else> refused-by-program</s:else></s:set> + <tr class="<s:property value="#trCssClasses"/>" data-contactId="<s:property value="topiaId"/>"> + <td> + <s:property value="creationDate"/> + </td> + <td> + <s:set name="boatTooltip"> + <s:text name="wao.ui.boats.registrationCode"/> <s:property value="%{'' + boat.immatriculation}" escapeHtml="false"/> + <s:text name="wao.ui.boats.boatLength"/> <s:property value="boat.boatLength" escapeHtml="false"/> cm + <s:text name="wao.ui.boats.buildYear"/> <s:property value="%{'' + boat.buildYear}" escapeHtml="false"/> + <s:text name="wao.ui.boats.district"/> <s:property value="boat.district.districtName" escapeHtml="false"/> (<s:property value="boat.district.districtCode" escapeHtml="false"/>) + </s:set> + <span data-original-title="<s:property value="#boatTooltip"/>" data-toggle="tooltip" data-placement="right"> + <s:property value="boat.name"/> + </span> + </td> + <td class="only-in-compact-view"> + <s:set name="sampleRowTooltip"> + <s:text name="wao.ui.field.SampleRow.programName"/> <s:property value="sampleRow.programName" escapeHtml="false"/> + <s:text name="wao.ui.field.SampleRow.professionCode"/> <s:property value="sampleRow.professionDescription" escapeHtml="false"/> + <s:text name="wao.ui.contacts.Profession.libelle"/> <s:property value="sampleRow.profession.libelle" escapeHtml="false"/> + <s:text name="wao.ui.contacts.Profession.species"/> <s:property value="sampleRow.profession.species" escapeHtml="false"/> + <s:text name="wao.ui.contacts.FishingZone.facadeName"/> <s:property value="sampleRow.facade" escapeHtml="false"/> + <s:text name="wao.ui.contacts.FishingZone.sectorName"/> <s:property value="sampleRow.sectors" escapeHtml="false"/> + <s:text name="wao.ui.contacts.division"/> <s:property value="%{getDivision(sampleRow)}" escapeHtml="false"/> + </s:set> + <span data-original-title="<s:property value="#sampleRowTooltip"/>" data-toggle="tooltip" data-placement="right"> + <s:property value="sampleRow.code"/> + </span> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.code"/> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.programName"/> + </td> + <td class="only-in-full-view"> + <s:iterator value="getDcf5CodesAndDescriptions(sampleRow)"> + <abbr title="<s:property value="value"/>"><s:property value="key"/></abbr> + </s:iterator> + <s:property value="sampleRow.professionDescriptionWithoutDCF5" /> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.profession.libelle"/> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.profession.species"/> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.facade"/> + </td> + <td class="only-in-full-view"> + <s:property value="sampleRow.sectors"/> + </td> + <td class="only-in-full-view"> + <s:property value="%{getDivision(sampleRow)}"/> + </td> + <s:if test="obsVente"> + <td> + <s:property value="terrestrialLocation.description"/> + </td> + </s:if> + <td class="only-in-full-view"> + <s:property value="sampleRow.company.name"/> + </td> + <td> + <ul> + <s:iterator value="allObservers"> + <li><s:property value="fullName"/></li> + </s:iterator> + </ul> + </td> + <td> + <s:text name="%{contactState.i18nKey}"/> + <s:if test="contactStateMotif != null"> + <s:property value="contactStateMotif.name"/> + </s:if> + </td> + <td class="date-time"> + <s:if test="observationBeginDate != null"> + <s:property value="observationBeginDate"/> + </s:if> + </td> + <td class="date-time"> + <s:if test="observationEndDate != null"> + <s:property value="observationEndDate"/> + </s:if> + </td> + <s:if test="obsMer"> + <td> + <s:if test="observationTimeInDays != null"> + <s:property value="observationTimeInDays"/> + </s:if> + </td> + </s:if> + <td class="date"> + <s:if test="dataInputDate != null"> + <s:property value="dataInputDate"/> + </s:if> + </td> + <s:if test="obsMer"> + <td> + <s:if test="observedDataControl != null"> + <s:text name="%{observedDataControl.i18nKey}"/> + </s:if> + </td> + <td class="date"> + <s:if test="restitution != null"> + <s:property value="restitution"/> + </s:if> + </td> + <td class="align-center"> + <s:if test="mammalsObservation"> + <i class="fa fa-eye" + title="<s:text name="wao.ui.field.Contact.mammalsObservation"/>"></i> + </s:if> + <s:if test="mammalsCapture"> + <img src="<s:url value="/img/hook-22px.png"/>" + alt="<s:text name="wao.ui.field.Contact.mammalsCapture"/>" + title="<s:property value="mammalsInfo" escapeHtml="false"/>"/> + </s:if> + </td> + </s:if> + <s:if test="obsVente"> + <td> + <s:if test="samplingStrategy != null"> + <s:text name="%{samplingStrategy.i18nKey}"/> + </s:if> + </td> + <td> + <s:if test="completeSampling == null"> + </s:if> + <s:elseif test="completeSampling"> + <s:text name="wao.ui.misc.yes"/> + </s:elseif> + <s:else> + <s:text name="wao.ui.misc.no"/> + </s:else> + </td> + </s:if> + <s:if test="authenticatedWaoUser.authorizedToViewContactsComments"> + <td class="align-center"> + <s:if test=" ! comment.empty"> + <i title="<s:property value="comment" escapeHtml="false"/>" class="fa fa-comment"></i> + </s:if> + </td> + <td class="align-center"> + <s:if test=" ! commentCoordinator.empty"> + <i title="<s:property value="commentCoordinator" escapeHtml="false"/>" class="fa fa-comment"></i> + </s:if> + </td> + <td class="align-center"> + <s:if test=" ! commentAdmin.empty"> + <i title="<s:property value="commentAdmin" escapeHtml="false"/>" class="fa fa-comment"></i> + </s:if> + </td> + </s:if> + <s:if test="obsMer"> + <td> + <s:if test="isBoardingDone(#contact)"> + <s:if test="validationCompany"> + <s:text name="%{dataReliability.i18nKey}"/> + </s:if> + </s:if> + </td> + </s:if> + <td> + <span class="fa-stack fa-lg" title="<s:text name="wao.ui.misc.validated"/>"> + <i class="fa fa-square-o fa-stack-2x"></i> + <i class="fa fa-check fa-stack-1x only-if-accepted-by-company"></i> + <i class="fa fa-times fa-stack-1x only-if-refused-by-company"></i> + </span> + <span class="fa-stack fa-lg" title="<s:text name="wao.ui.misc.validated"/>"> + <i class="fa fa-square-o fa-stack-2x"></i> + <i class="fa fa-check fa-stack-1x only-if-accepted-by-program"></i> + <i class="fa fa-times fa-stack-1x only-if-refused-by-program"></i> + </span> + </td> + <td class="actions"> + <div class="dropdown"> + <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> + <s:text name="wao.ui.actions"/> + <b class="caret"></b> + </a> + <ul class="dropdown-menu"> + <li> + <s:if test="authenticatedWaoUser.admin"> + <s:set name="focusAnchor">adminFocus</s:set> + </s:if> + <s:else> + <s:set name="focusAnchor">coordinatorOrObserverFocus</s:set> + </s:else> + <s:url action="edit-contact!input" id="editContactUrl" anchor='%{focusAnchor}'> + <s:param name="contactId" value="topiaId"/> + </s:url> + <s:a href="%{editContactUrl}"> + <i class="icon-edit"></i> <s:text name="wao.ui.action.editOrDeleteContact"/> + </s:a> + </li> + <s:if test="authenticatedWaoUser.authorizedToChangeContactValidation"> + <li> + <s:url action="validate-contact-json" id="acceptContactUrl" escapeAmp="false"> + <s:param name="contactId" value="topiaId"/> + <s:param name="validationState">true</s:param> + </s:url> + <s:set name="disabled"><s:if test="%{ ! isAcceptable(#contact)}">disabled</s:if></s:set> + <s:a cssClass="validation-action" href="%{acceptContactUrl}"> + <s:text name="wao.ui.action.acceptContact"/> + </s:a> + </li> + <li> + <s:url action="validate-contact-json" id="refuseContactUrl" escapeAmp="false"> + <s:param name="contactId" value="topiaId"/> + <s:param name="validationState">false</s:param> + </s:url> + <s:a cssClass="validation-action" href="%{refuseContactUrl}"> + <s:text name="wao.ui.action.refuseContact"/> + </s:a> + </li> + <li> + <s:url action="validate-contact-json" id="unvalidateContactUrl"> + <s:param name="contactId" value="topiaId"/> + </s:url> + <s:a cssClass="validation-action" href="%{unvalidateContactUrl}"> + <s:text name="wao.ui.action.unvalidateContact"/> + </s:a> + </li> + </s:if> + </ul> + </div> + </td> + </tr> + </s:iterator> + </todby> +</table> + +<s:property value="#pagination" escapeHtml="false"/> + +</html> Copied: branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/edit-contact-input.jsp (from rev 2075, branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/edit-contact-input.jsp) =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/edit-contact-input.jsp (rev 0) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/edit-contact-input.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -0,0 +1,366 @@ +<%-- + #%L + Wao :: Web + %% + Copyright (C) 2009 - 2014 Ifremer + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + #L% + --%> +<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> +<%@taglib uri="/struts-tags" prefix="s" %> + +<html> +<head> + <title> + <s:if test="updateContactCommand.creation"> + <s:text name="wao.ui.contact.creation"/> + </s:if> + <s:else> + <s:text name="wao.ui.contact.edition"/> + </s:else> + </title> + <script> + + $(document).ready(function () { + + <s:if test="contact.obsProgram.obsMer"> + var $mammalsCaptureCheckbox = $('#mammalsCaptureCheckbox'); + var $mammalsInfo = $('#mammalsInfo'); + + var showHideMammalsInfo = function () { + if ($mammalsCaptureCheckbox.prop('checked')) { + $mammalsInfo.show(); + } else { + $mammalsInfo.hide(); + } + }; + + $mammalsCaptureCheckbox.change(showHideMammalsInfo); + showHideMammalsInfo(); + + var $contactStateMotif = $('#contactStateMotif'); + var $contactStateSelect = $('select[name="updateContactCommand.contact.contactState"]'); + + var showHideContactStateMotif = function () { + var contactState = $contactStateSelect.val(); + if (contactState === 'CONTACT_REFUSED' || contactState === 'CONTACT_DEFINITELY_REFUSED') { + $contactStateMotif.show(); + } else { + $contactStateMotif.hide(); + } + }; + + $contactStateSelect.change(showHideContactStateMotif); + showHideContactStateMotif(); + + </s:if> + + $('#delete-contact-link').click(function (e) { + if ( ! confirm("<s:text name="wao.ui.action.deleteContact.confirm"/>")) { + e.preventDefault(); + } + }) + + }); + + </script> + <content tag="mainClass">form</content> +</head> + + <div class="form-wrapper"> + <h1> + <s:if test="updateContactCommand.creation"> + <s:text name="wao.ui.contact.creation"/> + </s:if> + <s:else> + <s:text name="wao.ui.contact.edition"/> + </s:else> + </h1> + + <aside class="well"> + + <h2><s:text name="wao.ui.misc.information"/></h2> + + <s:text name="wao.ui.form.Contact.contactCreatedOn"> + <s:param value="%{formatDate(updateContactCommand.contact.creationDate)}"/> + </s:text> + + <h3><s:text name="wao.ui.field.Contact.boat"/></h3> + + <table class="table"> + <tbody> + <tr> + <th> + <s:text name="wao.ui.field.Boat.name"/> + </th> + <td> + <s:property value="updateContactCommand.contact.boat.name"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.Boat.immatriculation"/> + </th> + <td> + <s:property value="updateContactCommand.contact.boat.immatriculation"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.Boat.districtCode"/> + </th> + <td> + <s:property value="updateContactCommand.contact.boat.districtCode"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.Boat.boatLength"/> + </th> + <td> + <s:property value="%{'' + updateContactCommand.contact.boat.boatLength}"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.Boat.buildYear"/> + </th> + <td> + <s:property value="%{'' + updateContactCommand.contact.boat.buildYear}"/> + </td> + </tr> + </tbody> + </table> + + <h3><s:text name="wao.ui.field.Contact.sampleRow"/></h3> + + <table class="table"> + <tbody> + <tr> + <th> + <s:text name="wao.ui.field.SampleRow.profession"/> + </th> + <td> + <s:property value="updateContactCommand.contact.sampleRow.professionDescription"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.SampleRow.programName"/> + </th> + <td> + <s:property value="updateContactCommand.contact.sampleRow.programName"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.SampleRow.periodBegin"/> + </th> + <td> + <s:property value="%{formatMonth(updateContactCommand.contact.sampleRow.periodBegin)}"/> + </td> + </tr> + <tr> + <th> + <s:text name="wao.ui.field.SampleRow.periodEnd"/> + </th> + <td> + <s:property value="%{formatMonth(updateContactCommand.contact.sampleRow.periodEnd)}"/> + </td> + </tr> + </tbody> + </table> + + </aside> + + <s:form> + + <s:set name="editObservationReport" + value="%{authenticatedWaoUser.isAuthorizedToEditObservationReport(updateContactCommand.contact)}"/> + + <s:hidden name="contactId" value="%{contactId}"/> + + <fieldset> + <legend><s:text name="wao.ui.misc.observers"/></legend> + + <s:select name="updateContactCommand.mainObserverId" + value="%{updateContactCommand.mainObserverId}" + label="%{getText('wao.ui.field.Contact.mainObserver')}" + list="observers" + emptyOption="true" + disabled="%{!#editObservationReport}" + cssClass="input-large" + /> + + <s:select name="updateContactCommand.secondaryObserverIds" + value="%{updateContactCommand.secondaryObserverIds}" + label="%{getText('wao.ui.field.Contact.secondaryObservers')}" + list="observers" + multiple="true" + disabled="%{!#editObservationReport}" + cssClass="input-xlarge" + /> + + </fieldset> + + <%--Do not remove the id (use by contacts page)--%> + <fieldset id="coordinatorOrObserverFocus"> + <legend><s:text name="wao.ui.misc.observationReport"/></legend> + + <s:textfield name="updateContactCommand.contact.observationBeginDate" + label="%{getText('wao.ui.field.Contact.beginDate')}" + placeholder="%{getDateTimePlaceholder()}" + disabled="%{!#editObservationReport}"/> + + <s:textfield name="updateContactCommand.contact.observationEndDate" + label="%{getText('wao.ui.field.Contact.endDate')}" + placeholder="%{getDateTimePlaceholder()}" + disabled="%{!#editObservationReport}"/> + + <s:select name="updateContactCommand.contact.contactState" + label="%{getText('wao.ui.field.Contact.contactState')}" + requiredLabel="true" + list="contactStates" + disabled="%{!#editObservationReport}"/> + + <s:if test="updateContactCommand.contact.obsProgram.obsVente"> + + <s:select name="updateContactCommand.terrestrialLocationId" + value="%{updateContactCommand.terrestrialLocationId}" + label="%{getText('wao.ui.field.Contact.terrestrialLocation')}" + list="terrestrialLocations" + emptyOption="true" + disabled="%{!#editObservationReport}" + cssClass="input-xxlarge select2" + /> + + <s:select name="updateContactCommand.contact.samplingStrategy" + label="%{getText('wao.ui.field.Contact.samplingStrategy')}" + list="samplingStrategies" + emptyOption="true" + disabled="%{!#editObservationReport}"/> + + <s:checkbox name="updateContactCommand.contact.completeSampling" + label="%{getText('wao.ui.field.Contact.completeSampling')}" + disabled="%{!#editObservationReport}"/> + + </s:if> + + <s:if test="updateContactCommand.contact.obsProgram.obsMer"> + + <div id="contactStateMotif"> + <s:select name="updateContactCommand.contact.contactStateMotif" + value="%{updateContactCommand.contact.contactState.topiaId}" + label="%{getText('wao.ui.field.Contact.contactStateMotif')}" + list="contactStateMotives" + emptyOption="true" + disabled="%{!#editObservationReport}"/> + </div> + + <s:checkbox name="updateContactCommand.contact.mammalsObservation" + label="%{getText('wao.ui.field.Contact.mammalsObservation')}" + disabled="%{!#editObservationReport}"/> + + <s:checkbox name="updateContactCommand.contact.mammalsCapture" + id="mammalsCaptureCheckbox" + label="%{getText('wao.ui.field.Contact.mammalsCapture')}" + disabled="%{!#editObservationReport}"/> + + <div id="mammalsInfo"> + <s:textarea name="updateContactCommand.contact.mammalsInfo" + label="%{getText('wao.ui.field.Contact.mammalsInfo')}" + disabled="%{!#editObservationReport}"/> + <div class="alert"> + <s:text name="wao.ui.page.ContactForm.mammalsInfo.disclaimer"/> + </div> + </div> + + </s:if> + + <s:textfield name="updateContactCommand.contact.dataInputDate" + label="%{getText('wao.ui.field.Contact.dataInputDate')}" + placeholder="%{getDatePlaceholder()}" + disabled="%{!#editObservationReport}"/> + + <s:if test="updateContactCommand.contact.obsProgram.obsMer"> + + <s:select name="updateContactCommand.contact.observedDataControl" + label="%{getText('wao.ui.field.Contact.observedDataControl')}" + list="observedDataControls" + emptyOption="true" + disabled="%{!#editObservationReport || !authenticatedWaoUser.coordinator}"/> + + <s:textfield name="updateContactCommand.contact.restitution" + label="%{getText('wao.ui.field.Contact.restitution')}" + placeholder="%{getDatePlaceholder()}" + disabled="%{!#editObservationReport}"/> + + </s:if> + + <s:textarea name="updateContactCommand.contact.comment" + label="%{getText('wao.ui.field.Contact.comment')}" + placeholder="%{getText('wao.ui.misc.noComment')}" + disabled="%{!#editObservationReport || !authenticatedWaoUser.observer}"/> + + <s:textarea name="updateContactCommand.contact.commentCoordinator" + label="%{getText('wao.ui.field.Contact.commentCoordinator')}" + placeholder="%{getText('wao.ui.misc.noComment')}" + disabled="%{!#editObservationReport || !authenticatedWaoUser.coordinator}"/> + + </fieldset> + + <%--Do not remove the id (use by contacts page)--%> + <fieldset id="adminFocus"> + <legend><s:text name="wao.ui.form.programEvaluation"/></legend> + + <s:if test="authenticatedWaoUser.authorizedToDisplayContactDataReliability"> + <s:select name="updateContactCommand.contact.dataReliability" + label="%{getText('wao.ui.field.Contact.dataReliability')}" + list="dataReliabilities" + emptyOption="true" + disabled="%{!authenticatedWaoUser.isAuthorizedToEditContactDataReliability(updateContactCommand.contact)}"/> + </s:if> + + <s:textarea name="updateContactCommand.contact.commentAdmin" + label="%{getText('wao.ui.field.Contact.commentAdmin')}" + placeholder="%{getText('wao.ui.misc.noComment')}" + disabled="%{!authenticatedWaoUser.admin}"/> + </fieldset> + + <div class="form-actions"> + <s:url action="contacts" id="contactsUrl"/> + <s:a href="%{contactsUrl}" cssClass="btn"> + <i class="icon-chevron-left"></i> <s:text name="wao.ui.action.cancel"/> + </s:a> + <s:if test="authenticatedWaoUser.isAuthorizedToEditContact(updateContactCommand.contact)"> + <s:submit type="button" cssClass="btn"> + <i class="icon-hdd"></i> <s:text name="wao.ui.action.save"/> + </s:submit> + </s:if> + + <s:if test=" ! updateContactCommand.creation && authenticatedWaoUser.isAuthorizedToDeleteContact(updateContactCommand.contact)"> + <s:url action="delete-contact" id="deleteContactUrl"> + <s:param name="contactId" value="contactId"/> + </s:url> + <s:a href="%{deleteContactUrl}" cssClass="btn pull-right" id="delete-contact-link"> + <i class="icon-trash"></i> <s:text name="wao.ui.action.deleteContact"/> + </s:a> + </s:if> + </div> + + </s:form> + </div> +</html> + Deleted: branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/contacts.jsp =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/contacts.jsp 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/contacts.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,552 +0,0 @@ -<%-- - #%L - Wao :: Web - %% - Copyright (C) 2009 - 2014 Ifremer - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. - #L% - --%> -<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> -<%@taglib uri="/struts-tags" prefix="s" %> - -<html> - -<head> - <title> - <s:text name="wao.ui.page.Contacts.title"/> - </title> - - <script> - - $(document).ready(function () { - - var contactsFilterMappings = [ - <s:if test="authenticatedWaoUser.authorizedToViewOtherCompanies"> - { - filterName: 'sampleRowFilter.companyIds', - filterLabel: "<s:text name="wao.ui.entity.Company"/>", - filterValuesField: 'sampleRowsFilterValues.companies', - }, - </s:if> - { - filterName: 'sampleRowFilter.sampleRowCodes', - filterLabel: "<s:text name="wao.ui.field.SampleRow.code"/>", - filterValuesField: 'sampleRowsFilterValues.sampleRowCodes', - }, - { - filterName: 'sampleRowFilter.programNames', - filterLabel: "<s:text name="wao.ui.field.SampleRow.programName"/>", - filterValuesField: 'sampleRowsFilterValues.programNames', - }, - { - filterName: 'sampleRowFilter.fishingZoneFacadeNames', - filterLabel: "<s:text name="wao.ui.field.FishingZone.facadeName"/>", - filterValuesField: 'sampleRowsFilterValues.fishingZoneFacadeNames', - }, - { - filterName: 'sampleRowFilter.fishingZoneSectorNames', - filterLabel: "<s:text name="wao.ui.field.FishingZone.sectorName"/>", - filterValuesField: 'sampleRowsFilterValues.fishingZoneSectorNames', - }, - { - filterName: 'sampleRowFilter.fishingGearDcfIds', - filterLabel: "<s:text name="wao.ui.entity.fishingGearDCF"/>", - filterValuesField: 'sampleRowsFilterValues.fishingGearDcfs', - }, - { - filterName: 'sampleRowFilter.targetSpeciesDcfIds', - filterLabel: "<s:text name="wao.ui.entity.targetSpeciesDCF"/>", - filterValuesField: 'sampleRowsFilterValues.targetSpeciesDcfs', - }, - <s:if test="authenticatedWaoUser.authorizedToFilterOnBoats"> - { - filterName: 'boatFilter.boatIds', - filterLabel: "<s:text name="wao.ui.entity.Boat"/>", - filterValuesField: 'boatsFilterValues.boats', - minimumInputLength: 3 - }, - </s:if> - { - filterName: 'boatFilter.districtIds', - filterLabel: "<s:text name="wao.ui.field.Boat.district"/>", - filterValuesField: 'boatsFilterValues.districts' - }, - { - filterName: 'observerIds', - filterLabel: "<s:text name="wao.ui.misc.observer"/>", - filterValuesField: 'observers' - }, - { - filterName: 'contactStates', - filterLabel: "<s:text name="wao.ui.field.Contact.contactState"/>", - filterValuesField: 'contactStates' - }, - { - filterName: 'companyAcceptations', - filterLabel: "<s:text name="wao.ui.field.Contact.validationCompany"/>", - filterValuesField: 'companyAcceptations' - }, - { - filterName: 'programAcceptations', - filterLabel: "<s:text name="wao.ui.field.Contact.validationProgram"/>", - filterValuesField: 'programAcceptations' - }, - { - filterName: 'observedDataControls', - filterLabel: "<s:text name="wao.ui.field.Contact.observedDataControl"/>", - filterValuesField: 'observedDataControls' - }, - { - filterName: 'dataReliabilities', - filterLabel: "<s:text name="wao.ui.field.Contact.dataReliability"/>", - filterValuesField: 'dataReliabilities' - } - ]; - - filter = <s:property value="filter" escapeHtml="false"/>; - - contactsFilterController2 = new FilterController2(contactsFilterMappings, filter, WAO.OBSMER_CONTACTS_FILTER_VALUES_JSON_URL, $('#contacts-filters-form fieldset.extra-filters')); - contactsFilterController2.init(); - - $('#switch-compact-full-view').click(function () { - $('#switch-compact-full-view').toggleClass('full-view').toggleClass('compact-view'); - $('table.contacts-list').toggleClass('full-view').toggleClass('compact-view'); - }); - - $('.validation-action').click(function(e) { - e.preventDefault(); - var $action = $(this); - var url = $action.attr('href'); - var successCallback = function (data) { - var successful = data['successful']; - if (successful) { - var success = data['successMessage']; - WAO.notifications.success(success); - var $tr = $('#contacts-list').find('tr[data-contactId="' + data.contactId + '"]'); - $tr.removeClass('accepted-by-company refused-by-company accepted-by-program refused-by-program'); - if (data.validationCompany) { - $tr.addClass('accepted-by-company'); - } else if (data.validationCompany === false) { - $tr.addClass('refused-by-company'); - } - if (data.validationProgram) { - $tr.addClass('accepted-by-program'); - } else if (data.validationProgram === false) { - $tr.addClass('refused-by-program'); - } - } else { - var error = data['errorMessage']; - WAO.notifications.error(error); - } - }; - WAO.post(url, {}, successCallback); - }); - - // Do not expose any struts internal input fields - $('input[type="hidden"][id^="__"]').prop('disabled', true); - }); - - </script> - -</head> - -<content tag="mainClass">large</content> -<content tag="contactsMenuItemClass">active</content> - -<s:form method="GET" id="contacts-filters-form" cssClass="filters-form"> - - <fieldset> - - <s:textfield name="filter.periodFrom" - label="%{getText('wao.ui.form.periodFrom')}" - placeholder="%{getFilterPeriodFromPlaceholder()}" - cssClass="input-small"/> - - <s:textfield name="filter.periodTo" - label="%{getText('wao.ui.form.period.to')}" - placeholder="%{getFilterPeriodToPlaceholder()}" - cssClass="input-small"/> - - <div title="<s:text name="wao.ui.form.filterOnObservationBeginDate.tooltip"/>"> - <s:checkbox name="filter.filterOnObservationBeginDate" - label="%{getText('wao.ui.form.filterOnObservationBeginDate')}"/> - </div> - - </fieldset> - - <fieldset class="extra-filters"> - - </fieldset> - - <fieldset> - - <s:checkbox name="filter.mammalsObservationOnly" - label="%{getText('wao.ui.misc.observations')}"/> - - <s:checkbox name="filter.mammalsCaptureOnly" - label="%{getText('wao.ui.field.Contact.mammalsCapture')}"/> - - <s:checkbox name="filter.commentDefinedOnly" - label="%{getText('wao.ui.field.Contact.comment')}"/> - - <s:checkbox name="filter.commentCompanyDefinedOnly" - label="%{getText('wao.ui.field.Contact.commentCompany')}"/> - - <s:checkbox name="filter.commentAdminDefinedOnly" - label="%{getText('wao.ui.field.Contact.commentAdmin')}"/> - - </fieldset> - - <fieldset> - - <s:checkbox name="filter.sortedByBoardingDate" - label="%{getText('wao.ui.form.sortByTideBegin')}"/> - - </fieldset> - - <div class="form-actions"> - - <s:submit type="button" action="contacts!applyFilter" cssClass="btn btn-primary"> - <i class="icon-filter"></i> <s:text name="wao.ui.action.filter"/> - </s:submit> - - <s:submit type="button" action="contacts!resetFilter" cssClass="btn"> - <i class="icon-trash"></i> <s:text name="wao.ui.action.reset"/> - </s:submit> - - <s:if test="authenticatedWaoUser.authorizedToExportContacts"> - <s:submit action="export-contacts" type="button" cssClass="btn"> - <i class="icon-download"></i> <s:text name="wao.ui.action.csvExport"/> - </s:submit> - </s:if> - - </div> - -</s:form> - -<h3> - <s:text name="wao.ui.contacts.title"> - <s:param value="%{pagination.count}"/> - </s:text> -</h3> - -<s:set name="pagination"> - <%-- Pagination --%> - <div class="pagination"> - <ul> - <s:url var="fullUrl" includeParams="get"/> - <s:set var="paginationUrl" value="%{getPaginationUrl(#fullUrl)}"/> - <s:if test="firstRangePage > 2"> - <li> - <a href="${paginationUrl}0">1</a> - </li> - <li> - <a href="${paginationUrl}1">2</a> - </li> - <li> - <span>...</span> - </li> - </s:if> - - <s:iterator var="currentPage" begin="firstRangePage" end="lastRangePage"> - <li class="<s:if test="#currentPage - 1 == pagination.currentPage.pageNumber">active</s:if>"> - <a href="${paginationUrl}${currentPage - 1}"> - <s:property/> - </a> - </li> - </s:iterator> - - <s:if test="lastRangePage < pagination.pageCount - 1"> - <li> - <span>...</span> - </li> - <li> - <a href="${paginationUrl}${pagination.pageCount - 2}"> - <s:property value="pagination.pageCount - 1"/> - </a> - </li> - <li> - <a href="${paginationUrl}${pagination.pageCount - 1}"> - <s:property value="pagination.pageCount"/> - </a> - </li> - </s:if> - </ul> - </div> -</s:set> - -<s:set var="fullView" value="%{fullView}"/> - -<div class="sticky-buttons"> - <button type="button" id="switch-compact-full-view" class="btn <s:if test="fullView">full-view</s:if><s:else>compact-view</s:else>"> - <span class="only-in-compact-view"> - <i class="fa fa-expand"></i><span class="only-on-hover"> <s:text name="wao.ui.action.switchToFullView" /></span> - </span> - <span class="only-in-full-view"> - <i class="fa fa-compress"></i><span class="only-on-hover"> <s:text name="wao.ui.action.switchToCompactView" /></span> - </span> - </button> -</div> - - -<s:property value="#pagination" escapeHtml="false"/> - -<table id="contacts-list" class="contacts-list large-table table-striped <s:if test="fullView">full-view</s:if><s:else>compact-view</s:else>"> - <thead> - <tr> - <th><s:text name="wao.ui.field.Contact.creationDate"/></th> - <th><s:text name="wao.ui.contacts.boatName"/></th> - <th><s:text name="wao.ui.field.Contact.sampleRow"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.programName"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.professionCode"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.contacts.Profession.libelle"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.contacts.Profession.species"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.contacts.FishingZone.facadeName"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.contacts.FishingZone.sectorName"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.contacts.division"/></th> - <th class="only-in-full-view"><s:text name="wao.ui.field.SampleRow.company"/></th> - <th><s:text name="wao.ui.contacts.observers"/></th> - <th><s:text name="wao.ui.field.Contact.contactState"/> (<s:text name="wao.ui.field.Contact.contactStateMotif"/>)</th> - <th class="date-time"><s:text name="wao.ui.field.Contact.beginDate"/></th> - <th class="date-time"><s:text name="wao.ui.field.Contact.endDate"/></th> - <th class="date-time"><s:text name="wao.ui.field.Contact.observationTimeInDays"/></th> - <th class="date"><s:text name="wao.ui.field.Contact.dataInputDate"/></th> - <th><s:text name="wao.ui.field.Contact.observedDataControl"/></th> - <th class="date"><s:text name="wao.ui.field.Contact.restitution"/></th> - <th><s:text name="wao.ui.contacts.observations"/></th> - <s:if test="authenticatedWaoUser.authorizedToViewContactsComments"> - <th><s:text name="wao.ui.field.Contact.comment"/></th> - <th><s:text name="wao.ui.field.Contact.commentCompany"/></th> - <th><s:text name="wao.ui.field.Contact.commentAdmin"/></th> - </s:if> - <th><s:text name="wao.ui.field.Contact.dataReliability"/></th> - <th><s:text name="wao.ui.contacts.validation"/></th> - <th><s:text name="wao.ui.actions"/></th> - </tr> - </thead> - <tbody> - - <s:iterator value="contacts" var="contact"> - <s:set name="trCssClasses">contact-row<s:if test="topiaId.equals(contactToHighlightId)"> highlight</s:if><s:if test="validationCompany==null"></s:if><s:elseif test="validationCompany"> accepted-by-company</s:elseif><s:else> refused-by-company</s:else><s:if test="validationProgram==null"></s:if><s:elseif test="validationProgram"> accepted-by-program</s:elseif><s:else> refused-by-program</s:else></s:set> - <tr class="<s:property value="#trCssClasses"/>" data-contactId="<s:property value="topiaId"/>"> - <td> - <s:property value="creationDate"/> - </td> - <td> - <s:set name="boatTooltip"> - <s:text name="wao.ui.boats.registrationCode"/> <s:property value="%{'' + boat.immatriculation}" escapeHtml="false"/> - <s:text name="wao.ui.boats.boatLength"/> <s:property value="boat.boatLength" escapeHtml="false"/> cm - <s:text name="wao.ui.boats.buildYear"/> <s:property value="%{'' + boat.buildYear}" escapeHtml="false"/> - <s:text name="wao.ui.boats.district"/> <s:property value="boat.district.districtName" escapeHtml="false"/> (<s:property value="boat.district.districtCode" escapeHtml="false"/>) - </s:set> - <span data-original-title="<s:property value="#boatTooltip"/>" data-toggle="tooltip" data-placement="right"> - <s:property value="boat.name"/> - </span> - </td> - <td class="only-in-compact-view"> - <s:set name="sampleRowTooltip"> - <s:text name="wao.ui.field.SampleRow.programName"/> <s:property value="sampleRow.programName" escapeHtml="false"/> - <s:text name="wao.ui.field.SampleRow.professionCode"/> <s:property value="sampleRow.professionDescription" escapeHtml="false"/> - <s:text name="wao.ui.contacts.Profession.libelle"/> <s:property value="sampleRow.profession.libelle" escapeHtml="false"/> - <s:text name="wao.ui.contacts.Profession.species"/> <s:property value="sampleRow.profession.species" escapeHtml="false"/> - <s:text name="wao.ui.contacts.FishingZone.facadeName"/> <s:property value="sampleRow.facade" escapeHtml="false"/> - <s:text name="wao.ui.contacts.FishingZone.sectorName"/> <s:property value="sampleRow.sectors" escapeHtml="false"/> - <s:text name="wao.ui.contacts.division"/> <s:property value="%{getDivision(sampleRow)}" escapeHtml="false"/> - </s:set> - <span data-original-title="<s:property value="#sampleRowTooltip"/>" data-toggle="tooltip" data-placement="right"> - <s:property value="sampleRow.code"/> - </span> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.code"/> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.programName"/> - </td> - <td class="only-in-full-view"> - <s:iterator value="getDcf5CodesAndDescriptions(sampleRow)"> - <abbr title="<s:property value="value"/>"><s:property value="key"/></abbr> - </s:iterator> - <s:property value="sampleRow.professionDescriptionWithoutDCF5" /> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.profession.libelle"/> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.profession.species"/> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.facade"/> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.sectors"/> - </td> - <td class="only-in-full-view"> - <s:property value="%{getDivision(sampleRow)}"/> - </td> - <td class="only-in-full-view"> - <s:property value="sampleRow.company.name"/> - </td> - <td> - <ul> - <s:iterator value="allObservers"> - <li><s:property value="fullName"/></li> - </s:iterator> - </ul> - </td> - <td> - <s:text name="%{contactState.i18nKey}"/> - <s:if test="contactStateMotif != null"> - <s:property value="contactStateMotif.name"/> - </s:if> - </td> - <td class="date-time"> - <s:if test="observationBeginDate != null"> - <s:property value="observationBeginDate"/> - </s:if> - </td> - <td class="date-time"> - <s:if test="observationEndDate != null"> - <s:property value="observationEndDate"/> - </s:if> - </td> - <td> - <s:if test="observationTimeInDays != null"> - <s:property value="observationTimeInDays"/> - </s:if> - </td> - <td class="date"> - <s:if test="dataInputDate != null"> - <s:property value="dataInputDate"/> - </s:if> - </td> - <td> - <s:if test="observedDataControl != null"> - <s:text name="%{observedDataControl.i18nKey}"/> - </s:if> - </td> - <td class="date"> - <s:if test="restitution != null"> - <s:property value="restitution"/> - </s:if> - </td> - <td class="align-center"> - <s:if test="mammalsObservation"> - <i class="fa fa-eye" - title="<s:text name="wao.ui.field.Contact.mammalsObservation"/>"></i> - </s:if> - <s:if test="mammalsCapture"> - <img src="<s:url value="/img/hook-22px.png"/>" - alt="<s:text name="wao.ui.field.Contact.mammalsCapture"/>" - title="<s:property value="mammalsInfo" escapeHtml="false"/>"/> - </s:if> - </td> - <s:if test="authenticatedWaoUser.authorizedToViewContactsComments"> - <td class="align-center"> - <s:if test=" ! comment.empty"> - <i title="<s:property value="comment" escapeHtml="false"/>" class="fa fa-comment"></i> - </s:if> - </td> - <td class="align-center"> - <s:if test=" ! commentCoordinator.empty"> - <i title="<s:property value="commentCoordinator" escapeHtml="false"/>" class="fa fa-comment"></i> - </s:if> - </td> - <td class="align-center"> - <s:if test=" ! commentAdmin.empty"> - <i title="<s:property value="commentAdmin" escapeHtml="false"/>" class="fa fa-comment"></i> - </s:if> - </td> - </s:if> - <td> - <s:if test="isBoardingDone(#contact)"> - <s:if test="validationCompany"> - <s:text name="%{dataReliability.i18nKey}"/> - </s:if> - </s:if> - </td> - <td> - <span class="fa-stack fa-lg" title="<s:text name="wao.ui.misc.validated"/>"> - <i class="fa fa-square-o fa-stack-2x"></i> - <i class="fa fa-check fa-stack-1x only-if-accepted-by-company"></i> - <i class="fa fa-times fa-stack-1x only-if-refused-by-company"></i> - </span> - <span class="fa-stack fa-lg" title="<s:text name="wao.ui.misc.validated"/>"> - <i class="fa fa-square-o fa-stack-2x"></i> - <i class="fa fa-check fa-stack-1x only-if-accepted-by-program"></i> - <i class="fa fa-times fa-stack-1x only-if-refused-by-program"></i> - </span> - </td> - <td class="actions"> - <div class="dropdown"> - <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> - <s:text name="wao.ui.actions"/> - <b class="caret"></b> - </a> - <ul class="dropdown-menu"> - <li> - <s:if test="authenticatedWaoUser.admin"> - <s:set name="focusAnchor">adminFocus</s:set> - </s:if> - <s:else> - <s:set name="focusAnchor">coordinatorOrObserverFocus</s:set> - </s:else> - <s:url action="edit-contact!input" id="editContactUrl" anchor='%{focusAnchor}'> - <s:param name="contactId" value="topiaId"/> - </s:url> - <s:a href="%{editContactUrl}"> - <i class="icon-edit"></i> <s:text name="wao.ui.action.editOrDeleteContact"/> - </s:a> - </li> - <s:if test="authenticatedWaoUser.authorizedToChangeContactValidation"> - <li> - <s:url action="validate-contact-json" id="acceptContactUrl" escapeAmp="false"> - <s:param name="contactId" value="topiaId"/> - <s:param name="validationState">true</s:param> - </s:url> - <s:set name="disabled"><s:if test="%{ ! isAcceptable(#contact)}">disabled</s:if></s:set> - <s:a cssClass="validation-action" href="%{acceptContactUrl}"> - <s:text name="wao.ui.action.acceptContact"/> - </s:a> - </li> - <li> - <s:url action="validate-contact-json" id="refuseContactUrl" escapeAmp="false"> - <s:param name="contactId" value="topiaId"/> - <s:param name="validationState">false</s:param> - </s:url> - <s:a cssClass="validation-action" href="%{refuseContactUrl}"> - <s:text name="wao.ui.action.refuseContact"/> - </s:a> - </li> - <li> - <s:url action="validate-contact-json" id="unvalidateContactUrl"> - <s:param name="contactId" value="topiaId"/> - </s:url> - <s:a cssClass="validation-action" href="%{unvalidateContactUrl}"> - <s:text name="wao.ui.action.unvalidateContact"/> - </s:a> - </li> - </s:if> - </ul> - </div> - </td> - </tr> - </s:iterator> - </todby> -</table> - -<s:property value="#pagination" escapeHtml="false"/> - -</html> Deleted: branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/edit-contact-input.jsp =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/edit-contact-input.jsp 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/obsmer/edit-contact-input.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -1,332 +0,0 @@ -<%-- - #%L - Wao :: Web - %% - Copyright (C) 2009 - 2014 Ifremer - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. - #L% - --%> -<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %> -<%@taglib uri="/struts-tags" prefix="s" %> - -<html> -<head> - <title> - <s:if test="updateContactCommand.creation"> - <s:text name="wao.ui.contact.creation"/> - </s:if> - <s:else> - <s:text name="wao.ui.contact.edition"/> - </s:else> - </title> - <script> - - $(document).ready(function () { - - var $mammalsCaptureCheckbox = $('#mammalsCaptureCheckbox'); - var $mammalsInfo = $('#mammalsInfo'); - - var showHideMammalsInfo = function () { - if ($mammalsCaptureCheckbox.prop('checked')) { - $mammalsInfo.show(); - } else { - $mammalsInfo.hide(); - } - }; - - $mammalsCaptureCheckbox.change(showHideMammalsInfo); - showHideMammalsInfo(); - - var $contactStateMotif = $('#contactStateMotif'); - var $contactStateSelect = $('select[name="updateContactCommand.contact.contactState"]'); - - var showHideContactStateMotif = function () { - var contactState = $contactStateSelect.val(); - if (contactState === 'CONTACT_REFUSED' || contactState === 'CONTACT_DEFINITELY_REFUSED') { - $contactStateMotif.show(); - } else { - $contactStateMotif.hide(); - } - }; - - $contactStateSelect.change(showHideContactStateMotif); - showHideContactStateMotif(); - - $('#delete-contact-link').click(function (e) { - if ( ! confirm("<s:text name="wao.ui.action.deleteContact.confirm"/>")) { - e.preventDefault(); - } - }) - - }); - - </script> - <content tag="mainClass">form</content> -</head> - - <div class="form-wrapper"> - <h1> - <s:if test="updateContactCommand.creation"> - <s:text name="wao.ui.contact.creation"/> - </s:if> - <s:else> - <s:text name="wao.ui.contact.edition"/> - </s:else> - </h1> - - <aside class="well"> - - <h2><s:text name="wao.ui.misc.information"/></h2> - - <s:text name="wao.ui.form.Contact.contactCreatedOn"> - <s:param value="%{formatDate(updateContactCommand.contact.creationDate)}"/> - </s:text> - - <h3><s:text name="wao.ui.field.Contact.boat"/></h3> - - <table class="table"> - <tbody> - <tr> - <th> - <s:text name="wao.ui.field.Boat.name"/> - </th> - <td> - <s:property value="updateContactCommand.contact.boat.name"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.Boat.immatriculation"/> - </th> - <td> - <s:property value="updateContactCommand.contact.boat.immatriculation"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.Boat.districtCode"/> - </th> - <td> - <s:property value="updateContactCommand.contact.boat.districtCode"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.Boat.boatLength"/> - </th> - <td> - <s:property value="%{'' + updateContactCommand.contact.boat.boatLength}"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.Boat.buildYear"/> - </th> - <td> - <s:property value="%{'' + updateContactCommand.contact.boat.buildYear}"/> - </td> - </tr> - </tbody> - </table> - - <h3><s:text name="wao.ui.field.Contact.sampleRow"/></h3> - - <table class="table"> - <tbody> - <tr> - <th> - <s:text name="wao.ui.field.SampleRow.profession"/> - </th> - <td> - <s:property value="updateContactCommand.contact.sampleRow.professionDescription"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.SampleRow.programName"/> - </th> - <td> - <s:property value="updateContactCommand.contact.sampleRow.programName"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.SampleRow.periodBegin"/> - </th> - <td> - <s:property value="%{formatMonth(updateContactCommand.contact.sampleRow.periodBegin)}"/> - </td> - </tr> - <tr> - <th> - <s:text name="wao.ui.field.SampleRow.periodEnd"/> - </th> - <td> - <s:property value="%{formatMonth(updateContactCommand.contact.sampleRow.periodEnd)}"/> - </td> - </tr> - </tbody> - </table> - - </aside> - - <s:form> - - <s:set name="editObservationReport" - value="%{authenticatedWaoUser.isAuthorizedToEditObservationReport(updateContactCommand.contact)}"/> - - <s:hidden name="contactId" value="%{contactId}"/> - - <fieldset> - <legend><s:text name="wao.ui.misc.observers"/></legend> - - <s:select name="updateContactCommand.mainObserverId" - value="%{updateContactCommand.mainObserverId}" - label="%{getText('wao.ui.field.Contact.mainObserver')}" - list="observers" - emptyOption="true" - disabled="%{!#editObservationReport}" - cssClass="input-large" - /> - - <s:select name="updateContactCommand.secondaryObserverIds" - value="%{updateContactCommand.secondaryObserverIds}" - label="%{getText('wao.ui.field.Contact.secondaryObservers')}" - list="observers" - multiple="true" - disabled="%{!#editObservationReport}" - cssClass="input-xlarge" - /> - - </fieldset> - - <%--Do not remove the id (use by contacts page)--%> - <fieldset id="coordinatorOrObserverFocus"> - <legend><s:text name="wao.ui.misc.observationReport"/></legend> - - <s:textfield name="updateContactCommand.contact.observationBeginDate" - label="%{getText('wao.ui.field.Contact.beginDate')}" - placeholder="%{getDateTimePlaceholder()}" - disabled="%{!#editObservationReport}"/> - - <s:textfield name="updateContactCommand.contact.observationEndDate" - label="%{getText('wao.ui.field.Contact.endDate')}" - placeholder="%{getDateTimePlaceholder()}" - disabled="%{!#editObservationReport}"/> - - <s:select name="updateContactCommand.contact.contactState" - label="%{getText('wao.ui.field.Contact.contactState')}" - requiredLabel="true" - list="contactStates" - disabled="%{!#editObservationReport}"/> - - <div id="contactStateMotif"> - <s:select name="updateContactCommand.contact.contactStateMotif" - value="%{updateContactCommand.contact.contactState.topiaId}" - label="%{getText('wao.ui.field.Contact.contactStateMotif')}" - list="contactStateMotives" - emptyOption="true" - disabled="%{!#editObservationReport}"/> - </div> - - <s:checkbox name="updateContactCommand.contact.mammalsObservation" - label="%{getText('wao.ui.field.Contact.mammalsObservation')}" - disabled="%{!#editObservationReport}"/> - - <s:checkbox name="updateContactCommand.contact.mammalsCapture" - id="mammalsCaptureCheckbox" - label="%{getText('wao.ui.field.Contact.mammalsCapture')}" - disabled="%{!#editObservationReport}"/> - - <div id="mammalsInfo"> - <s:textarea name="updateContactCommand.contact.mammalsInfo" - label="%{getText('wao.ui.field.Contact.mammalsInfo')}" - disabled="%{!#editObservationReport}"/> - <div class="alert"> - <s:text name="wao.ui.page.ContactForm.mammalsInfo.disclaimer"/> - </div> - </div> - - <s:textfield name="updateContactCommand.contact.dataInputDate" - label="%{getText('wao.ui.field.Contact.dataInputDate')}" - placeholder="%{getDatePlaceholder()}" - disabled="%{!#editObservationReport}"/> - - <s:select name="updateContactCommand.contact.observedDataControl" - label="%{getText('wao.ui.field.Contact.observedDataControl')}" - list="observedDataControls" - emptyOption="true" - disabled="%{!#editObservationReport || !authenticatedWaoUser.coordinator}"/> - - <s:textfield name="updateContactCommand.contact.restitution" - label="%{getText('wao.ui.field.Contact.restitution')}" - placeholder="%{getDatePlaceholder()}" - disabled="%{!#editObservationReport}"/> - - <s:textarea name="updateContactCommand.contact.comment" - label="%{getText('wao.ui.field.Contact.comment')}" - placeholder="%{getText('wao.ui.misc.noComment')}" - disabled="%{!#editObservationReport || !authenticatedWaoUser.observer}"/> - - <s:textarea name="updateContactCommand.contact.commentCoordinator" - label="%{getText('wao.ui.field.Contact.commentCoordinator')}" - placeholder="%{getText('wao.ui.misc.noComment')}" - disabled="%{!#editObservationReport || !authenticatedWaoUser.coordinator}"/> - - </fieldset> - - <%--Do not remove the id (use by contacts page)--%> - <fieldset id="adminFocus"> - <legend><s:text name="wao.ui.form.programEvaluation"/></legend> - - <s:if test="authenticatedWaoUser.authorizedToDisplayContactDataReliability"> - <s:select name="updateContactCommand.contact.dataReliability" - label="%{getText('wao.ui.field.Contact.dataReliability')}" - list="dataReliabilities" - emptyOption="true" - disabled="%{!authenticatedWaoUser.isAuthorizedToEditContactDataReliability(updateContactCommand.contact)}"/> - </s:if> - - <s:textarea name="updateContactCommand.contact.commentAdmin" - label="%{getText('wao.ui.field.Contact.commentAdmin')}" - placeholder="%{getText('wao.ui.misc.noComment')}" - disabled="%{!authenticatedWaoUser.admin}"/> - </fieldset> - - <div class="form-actions"> - <s:url action="contacts" id="contactsUrl"/> - <s:a href="%{contactsUrl}" cssClass="btn"> - <i class="icon-chevron-left"></i> <s:text name="wao.ui.action.cancel"/> - </s:a> - <s:if test="authenticatedWaoUser.isAuthorizedToEditContact(updateContactCommand.contact)"> - <s:submit type="button" cssClass="btn"> - <i class="icon-hdd"></i> <s:text name="wao.ui.action.save"/> - </s:submit> - </s:if> - - <s:if test=" ! updateContactCommand.creation && authenticatedWaoUser.isAuthorizedToDeleteContact(updateContactCommand.contact)"> - <s:url action="delete-contact" id="deleteContactUrl"> - <s:param name="contactId" value="contactId"/> - </s:url> - <s:a href="%{deleteContactUrl}" cssClass="btn pull-right" id="delete-contact-link"> - <i class="icon-trash"></i> <s:text name="wao.ui.action.deleteContact"/> - </s:a> - </s:if> - </div> - - </s:form> - </div> -</html> - Modified: branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/synthesis.jsp =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/synthesis.jsp 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/WEB-INF/content/synthesis.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -94,7 +94,7 @@ filter = <s:property value="filter" escapeHtml="false"/>; - contactsFilterController2 = new FilterController2(contactsFilterMappings, filter, WAO.OBSMER_CONTACTS_FILTER_VALUES_JSON_URL, $('#synthesis-filters-form fieldset.extra-filters')); + contactsFilterController2 = new FilterController2(contactsFilterMappings, filter, WAO.CONTACTS_FILTER_VALUES_JSON_URL, $('#synthesis-filters-form fieldset.extra-filters')); contactsFilterController2.init(); }); Modified: branches/wao-4.0-obsvente/wao-web/src/main/webapp/endpoints-js.jsp =================================================================== --- branches/wao-4.0-obsvente/wao-web/src/main/webapp/endpoints-js.jsp 2014-06-20 15:20:22 UTC (rev 2077) +++ branches/wao-4.0-obsvente/wao-web/src/main/webapp/endpoints-js.jsp 2014-06-20 17:38:35 UTC (rev 2078) @@ -34,7 +34,7 @@ WAO.GET_BOAT_CONTACTS_COUNT_JSON_URL = '<s:url namespace="/" action="get-boat-contacts-count-json"/>'; WAO.SEARCH_BOAT_JSON_URL = '<s:url namespace="/" action="search-boat-json"/>'; - WAO.OBSMER_CONTACTS_FILTER_VALUES_JSON_URL = '<s:url namespace="/obsmer" action="contacts-filter-values-json"/>'; + WAO.CONTACTS_FILTER_VALUES_JSON_URL = '<s:url namespace="/obsmer" action="contacts-filter-values-json"/>'; // fragments WAO.BOAT_DETAILS_URL = '<s:url namespace="/" action="boat-details"/>';