Project

General

Profile

Download (36.3 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
* Copyright (C) 2017 EDIT
3
* European Distributed Institute of Taxonomy
4
* http://www.e-taxonomy.eu
5
*
6
* The contents of this file are subject to the Mozilla Public License Version 1.1
7
* See LICENSE.TXT at the top of this package for the full license terms.
8
*/
9
package eu.etaxonomy.cdm.vaadin.view.registration;
10

    
11
import java.util.ArrayList;
12
import java.util.Arrays;
13
import java.util.Collection;
14
import java.util.EnumSet;
15
import java.util.HashMap;
16
import java.util.HashSet;
17
import java.util.List;
18
import java.util.Map;
19
import java.util.Objects;
20
import java.util.Set;
21
import java.util.Stack;
22
import java.util.UUID;
23

    
24
import org.apache.log4j.Logger;
25
import org.springframework.beans.factory.annotation.Autowired;
26
import org.springframework.transaction.TransactionStatus;
27
import org.vaadin.spring.events.EventScope;
28
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
29

    
30
import com.vaadin.server.SystemError;
31
import com.vaadin.spring.annotation.SpringComponent;
32
import com.vaadin.spring.annotation.ViewScope;
33
import com.vaadin.ui.AbstractField;
34
import com.vaadin.ui.Button;
35
import com.vaadin.ui.Label;
36
import com.vaadin.ui.UI;
37
import com.vaadin.ui.VerticalLayout;
38
import com.vaadin.ui.Window;
39

    
40
import eu.etaxonomy.cdm.api.service.INameService;
41
import eu.etaxonomy.cdm.api.service.IRegistrationService;
42
import eu.etaxonomy.cdm.api.service.config.RegistrationStatusTransitions;
43
import eu.etaxonomy.cdm.api.service.dto.RegistrationDTO;
44
import eu.etaxonomy.cdm.api.service.dto.RegistrationWorkingSet;
45
import eu.etaxonomy.cdm.api.service.exception.RegistrationValidationException;
46
import eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager.TypeDesignationWorkingSetType;
47
import eu.etaxonomy.cdm.api.service.registration.IRegistrationWorkingSetService;
48
import eu.etaxonomy.cdm.api.utility.RoleProber;
49
import eu.etaxonomy.cdm.api.utility.UserHelper;
50
import eu.etaxonomy.cdm.cache.CdmTransientEntityCacher;
51
import eu.etaxonomy.cdm.ext.common.ExternalServiceException;
52
import eu.etaxonomy.cdm.ext.registration.messages.IRegistrationMessageService;
53
import eu.etaxonomy.cdm.model.ICdmCacher;
54
import eu.etaxonomy.cdm.model.common.CdmBase;
55
import eu.etaxonomy.cdm.model.common.User;
56
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
57
import eu.etaxonomy.cdm.model.name.Rank;
58
import eu.etaxonomy.cdm.model.name.Registration;
59
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
60
import eu.etaxonomy.cdm.model.name.TaxonName;
61
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
62
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
63
import eu.etaxonomy.cdm.model.reference.Reference;
64
import eu.etaxonomy.cdm.model.reference.ReferenceType;
65
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
66
import eu.etaxonomy.cdm.ref.EntityReference;
67
import eu.etaxonomy.cdm.ref.TypedEntityReference;
68
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
69
import eu.etaxonomy.cdm.service.CdmStore;
70
import eu.etaxonomy.cdm.service.UserHelperAccess;
71
import eu.etaxonomy.cdm.vaadin.component.CdmBeanItemContainerFactory;
72
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationItem;
73
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationStatusFieldInstantiator;
74
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationStatusSelect;
75
import eu.etaxonomy.cdm.vaadin.event.AbstractEditorAction.EditorActionContext;
76
import eu.etaxonomy.cdm.vaadin.event.EditorActionTypeFilter;
77
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
78
import eu.etaxonomy.cdm.vaadin.event.ReferenceEditorAction;
79
import eu.etaxonomy.cdm.vaadin.event.RegistrationEditorAction;
80
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEvent;
81
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEventEntityTypeFilter;
82
import eu.etaxonomy.cdm.vaadin.event.TaxonNameEditorAction;
83
import eu.etaxonomy.cdm.vaadin.event.TypeDesignationWorkingsetEditorAction;
84
import eu.etaxonomy.cdm.vaadin.event.registration.RegistrationWorkingsetAction;
85
import eu.etaxonomy.cdm.vaadin.permission.RolesAndPermissions;
86
import eu.etaxonomy.cdm.vaadin.theme.EditValoTheme;
87
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
88
import eu.etaxonomy.cdm.vaadin.ui.config.TaxonNamePopupEditorConfig;
89
import eu.etaxonomy.cdm.vaadin.util.CdmTitleCacheCaptionGenerator;
90
import eu.etaxonomy.cdm.vaadin.view.name.CachingPresenter;
91
import eu.etaxonomy.cdm.vaadin.view.name.NameTypeDesignationPopupEditor;
92
import eu.etaxonomy.cdm.vaadin.view.name.SpecimenTypeDesignationWorkingsetPopupEditor;
93
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditor;
94
import eu.etaxonomy.cdm.vaadin.view.name.TypeDesignationWorkingsetEditorIdSet;
95
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
96
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
97
import eu.etaxonomy.vaadin.mvp.AbstractPresenter;
98
import eu.etaxonomy.vaadin.mvp.AbstractView;
99
import eu.etaxonomy.vaadin.mvp.BeanInstantiator;
100
import eu.etaxonomy.vaadin.ui.navigation.NavigationEvent;
101
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent;
102
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent.Reason;
103

    
104
/**
105
 * @author a.kohlbecker
106
 * @since Mar 3, 2017
107
 *
108
 */
109
@SpringComponent
110
@ViewScope
111
public class RegistrationWorkingsetPresenter extends AbstractPresenter<RegistrationWorkingsetView> implements CachingPresenter {
112

    
113
    private static final Logger logger = Logger.getLogger(RegistrationWorkingsetPresenter.class);
114

    
115
    private static final List<String> REGISTRATION_INIT_STRATEGY = Arrays.asList(
116
            "$",
117
            "blockedBy",
118
            "name.combinationAuthorship",
119
            "name.exCombinationAuthorship",
120
            "name.basionymAuthorship",
121
            "name.exBasionymAuthorship"
122
            );
123

    
124
    private static final long serialVersionUID = 1L;
125

    
126
    @Autowired
127
    private IRegistrationWorkingSetService regWorkingSetService;
128

    
129
    @Autowired
130
    private IRegistrationMessageService messageService;
131

    
132
    /**
133
     * @return the regWorkingSetService
134
     */
135
    public IRegistrationWorkingSetService getWorkingSetService() {
136
        return regWorkingSetService;
137
    }
138

    
139
    private RegistrationWorkingSet workingset;
140

    
141
    private TaxonNamePopupEditor newNameForRegistrationPopupEditor = null;
142

    
143
    private Map<NameTypeDesignationPopupEditor, UUID> nameTypeDesignationPopupEditorRegistrationUUIDMap = new HashMap<>();
144

    
145

    
146
    private ICdmCacher cache;
147

    
148
    private Collection<CdmBase> rootEntities = new HashSet<>();
149

    
150
    /**
151
     *
152
     */
153
    public RegistrationWorkingsetPresenter() {
154
    }
155

    
156
    /**
157
     * Always create a new Store
158
     *
159
     * @return
160
     */
161
    protected CdmStore<Registration, IRegistrationService> getRegistrationStore(){
162
        return new CdmStore<Registration, IRegistrationService>(getRepo(), getRepo().getRegistrationService());
163
    }
164

    
165
    /**
166
     * Always create a new Store
167
     *
168
     * @return
169
     */
170
    protected CdmStore<TaxonName, INameService> getTaxonNameStore(){
171
        return new  CdmStore<TaxonName, INameService>(getRepo(), getRepo().getNameService());
172
    }
173

    
174
    /**
175
     * Checks
176
     * <ol>
177
     * <li>if there is NOT any registration for this name created in the current registration system</li>
178
     * <li>Checks if the name belongs to the current workingset</li>
179
     * </ol>
180
     * If both checks are successful the method returns <code>true</code>.
181
     */
182
    public boolean canCreateNameRegistrationFor(TaxonName name) {
183
        return !getRepo().getRegistrationService().checkRegistrationExistsFor(name) && checkWokingsetContainsProtologe(name);
184
    }
185

    
186
    /**
187
     * @param name
188
     * @return
189
     */
190
    public boolean checkWokingsetContainsProtologe(TaxonName name) {
191
        Reference nomRef = name.getNomenclaturalReference();
192
        UUID citationUuid = workingset.getCitationUuid();
193
        // @formatter:off
194
        return nomRef != null && (
195
                // nomref matches
196
                nomRef.getUuid().equals(citationUuid) ||
197
                // nomref.inreference matches
198
                (nomRef.getType() != null && nomRef.getType() == ReferenceType.Section && nomRef.getInReference() != null && nomRef.getInReference().getUuid().equals(citationUuid))
199
                );
200
        // @formatter:on
201
    }
202

    
203
    /**
204
     * @param doReload TODO
205
     *
206
     */
207
    protected void refreshView(boolean doReload) {
208
        if(workingset == null){
209
            return; // nothing to do
210
        }
211
        if(doReload){
212
            loadWorkingSet(workingset.getCitationUuid());
213
        }
214
        applyWorkingset();
215
    }
216

    
217
    /**
218
     * {@inheritDoc}
219
     */
220
    @Override
221
    public void handleViewEntered() {
222
        super.handleViewEntered();
223
        // TODO currently cannot specify type more precisely, see AbstractSelect
224
        // FIXME externalize into class file!!!!!!!!!!!!
225
        getView().setStatusComponentInstantiator(new RegistrationStatusFieldInstantiator<Object>(){
226

    
227
            private static final long serialVersionUID = 7099181280977511048L;
228

    
229
            @Override
230
            public AbstractField<Object> create(RegistrationDTO regDto) {
231

    
232
                CdmBeanItemContainerFactory selectFieldFactory = new CdmBeanItemContainerFactory(getRepo());
233
                // submitters have GrantedAuthorities like REGISTRATION(PREPARATION).[UPDATE]{ab4459eb-3b96-40ba-bfaa-36915107d59e}
234
                UserHelper userHelper = UserHelperAccess.userHelper();
235
                Set<RegistrationStatus> availableStatus = new HashSet<>();
236

    
237
                boolean canChangeStatus = userHelper.userHasPermission(regDto.registration(), CRUD.UPDATE);
238
                availableStatus.add(regDto.getStatus());
239
                if(canChangeStatus){
240
                    if(userHelper.userIsAdmin()){
241
                        availableStatus.addAll(Arrays.asList(RegistrationStatus.values()));
242
                    } else {
243
                        availableStatus.addAll(RegistrationStatusTransitions.possibleTransitions(regDto.getStatus()));
244
                    }
245
                }
246

    
247
                RegistrationStatusSelect select = new RegistrationStatusSelect(null, selectFieldFactory.buildBeanItemContainer(
248
                        RegistrationStatus.class,
249
                        availableStatus.toArray(new RegistrationStatus[availableStatus.size()]))
250
                        );
251
                select.addValueChangeListener(e -> saveRegistrationStatusChange(regDto.getUuid(), e.getProperty().getValue()));
252
                select.setEnabled(canChangeStatus);
253
                select.setNullSelectionAllowed(false);
254
                return select;
255
            }
256

    
257

    
258
        });
259
        loadWorkingSet(getView().getCitationUuid());
260
        applyWorkingset();
261

    
262
    }
263

    
264
    private void applyWorkingset(){
265
         getView().setWorkingset(workingset);
266
        // PagingProviders and CacheGenerator for the existingNameCombobox
267
        activateComboboxes();
268
        // update the messages
269
        updateMessages();
270
    }
271

    
272
    /**
273
     *
274
     */
275
    protected void activateComboboxes() {
276
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
277
                getRepo().getNameService());
278
        pagingProvider.setInitStrategy(Arrays.asList("registrations", "nomenclaturalReference", "nomenclaturalReference.inReference"));
279
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
280
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
281
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
282
    }
283

    
284
    /**
285
     *
286
     */
287
    protected void updateMessages() {
288
        User user = UserHelperAccess.userHelper().user();
289
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
290
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
291

    
292
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
293
            try {
294
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
295

    
296
                boolean activeMessages = messageCount > 0;
297
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName() != null && regDto.getSubmitterUserName().equals(UserHelperAccess.userHelper().userName());
298
                boolean currentUserIsCurator = UserHelperAccess.userHelper().userIs(new RoleProber(RolesAndPermissions.ROLE_CURATION));
299
                messageButton.setEnabled(false);
300
                if(currentUserIsCurator){
301
                    if(currentUserIsSubmitter){
302
                        messageButton.setDescription("No point sending messages to your self.");
303
                    } else {
304
                        messageButton.setEnabled(true);
305
                        messageButton.setDescription("Open the messages dialog.");
306
                    }
307
                } else {
308
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
309
                }
310
                if(activeMessages){
311
                    messageButton.setEnabled(true);
312
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
313
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
314
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
315

    
316
                }
317
            } catch (ExternalServiceException e) {
318
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
319
            }
320
        }
321
    }
322

    
323

    
324
    /**
325
     * @param referenceID
326
     */
327
    protected void loadWorkingSet(UUID referenceUuid) {
328
        try {
329
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid, true);
330
        } catch (RegistrationValidationException error) {
331
            logger.error(error);
332
            Window errorDialog = new Window("Validation Error");
333
            errorDialog.setModal(true);
334
            VerticalLayout subContent = new VerticalLayout();
335
            subContent.setMargin(true);
336
            errorDialog.setContent(subContent);
337
            subContent.addComponent(new Label(error.getMessage()));
338
            UI.getCurrent().addWindow(errorDialog);
339
        }
340
        if(workingset == null || workingset.getCitationUuid() == null){
341
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
342
            workingset = new RegistrationWorkingSet(citation);
343
        }
344
        cache = new CdmTransientEntityCacher(this);
345
        for(Registration registration : workingset.getRegistrations()) {
346
            addRootEntity(registration);
347
        }
348
    }
349

    
350
    private void saveRegistrationStatusChange(UUID uuid, Object value) {
351
        Registration reg = getRepo().getRegistrationService().load(uuid);
352
        if(reg == null){
353
            // registration was not yet persisted, ignore
354
            return;
355
        }
356
        if(value != null && value instanceof RegistrationStatus){
357
            if(!Objects.equals(value, reg.getStatus())){
358
                reg.setStatus((RegistrationStatus)value);
359
                getRegistrationStore().saveBean(reg, (AbstractView)getView());
360
                refreshView(true);
361
            }
362
        } else {
363
            // only log here as error
364
            logger.error("Ivalid attempt to set RegistrationStatus to " + Objects.toString(value.toString(), "NULL"));
365
        }
366
    }
367

    
368

    
369
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
370
    public void onReferenceEditorActionAdd(ReferenceEditorAction event) {
371

    
372
        if(!checkFromOwnView(event)){
373
            return;
374
        }
375

    
376
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
377
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
378
        popup.loadInEditor(null);
379
    }
380

    
381
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
382
    public void onReferenceEditorActionEdit(ReferenceEditorAction event) {
383

    
384
        if(!checkFromOwnView(event)){
385
            return;
386
        }
387
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
388
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
389
        popup.withDeleteButton(true);
390
        popup.loadInEditor(event.getEntityUuid());
391
    }
392

    
393
    @EventBusListenerMethod
394
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
395
        if(event.getPopup() instanceof ReferencePopupEditor){
396
            if(event.getReason().equals(Reason.SAVE)){
397
                refreshView(true);
398
            }
399
        }
400
    }
401

    
402
    @EventBusListenerMethod
403
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
404
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
405
            if(event.getReason().equals(Reason.SAVE)){
406
                refreshView(true);
407
            }
408
        }
409
    }
410

    
411
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
412
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
413

    
414
        if(!checkFromOwnView(event)){
415
            return;
416
        }
417

    
418
        RegistrationPopupEditor popup = openPopupEditor(RegistrationPopupEditor.class, event);
419
        popup.loadInEditor(event.getEntityUuid());
420
    }
421

    
422
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
423
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
424

    
425
        if(!checkFromOwnView(event)){
426
            return;
427
        }
428

    
429
        TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
430
        popup.setParentEditorActionContext(event.getContext());
431
        popup.withDeleteButton(true);
432
        TaxonNamePopupEditorConfig.configureForNomenclaturalAct(popup);
433
        popup.loadInEditor(event.getEntityUuid());
434
        if(event.hasSource() && event.getSource().isReadOnly()){
435
            // avoid resetting readonly to false
436
            popup.setReadOnly(true);
437
        }
438

    
439
    }
440

    
441

    
442
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
443
    public void onTaxonNameEditorActionAdd(TaxonNameEditorAction event) {
444

    
445
        if(!checkFromOwnView(event)){
446
            return;
447
        }
448

    
449
        getView().getAddNewNameRegistrationButton().setEnabled(false);
450
        if(newNameForRegistrationPopupEditor == null){
451
            TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
452
            newNameForRegistrationPopupEditor = popup;
453
            popup.setParentEditorActionContext(event.getContext());
454
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
455
            popup.withDeleteButton(true);
456
            popup.setCdmEntityInstantiator(new BeanInstantiator<TaxonName>() {
457

    
458
                @Override
459
                public TaxonName createNewBean() {
460
                    TaxonName newTaxonName = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
461
                    newTaxonName.setNomenclaturalReference(getRepo().getReferenceService().load(workingset.getCitationUuid()));
462
                    return newTaxonName;
463
                }
464
            });
465
            TaxonNamePopupEditorConfig.configureForNomenclaturalAct(popup);
466
            popup.loadInEditor(null);
467
        }
468
    }
469

    
470
    /**
471
     * Creates a new <code>Registration</code> for a new name that has just been edited
472
     * using the <code>TaxonNamePopupEditor</code>. The new name was previously created
473
     * in this presenter as <code>newTaxonNameForRegistration</code> (see {@link #onTaxonNameEditorActionAdd(TaxonNameEditorAction)})
474
     * and is either filled with data (<code>Reason.SAVE</code>) or it is still empty
475
     * (<code>Reason.CANCEL</code>).
476
     *
477
     *
478
     * @param event
479
     * @throws RegistrationValidationException
480
     */
481
    @EventBusListenerMethod
482
    public void onDoneWithTaxonnameEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
483
        if(event.getPopup() instanceof TaxonNamePopupEditor){
484
            try {
485
                if(event.getReason().equals(Reason.SAVE)){
486
                    TransactionStatus txStatus = getRepo().startTransaction();
487
                    if(newNameForRegistrationPopupEditor != null){
488
                        UUID taxonNameUuid = newNameForRegistrationPopupEditor.getBean().getUuid();
489
                        if(newNameForRegistrationPopupEditor.getBean().cdmEntity().isPersited()){
490
                            getRepo().getSession().refresh(newNameForRegistrationPopupEditor.getBean().cdmEntity());
491
                        }
492
                        Registration reg = getRepo().getRegistrationService().createRegistrationForName(taxonNameUuid);
493
                        // reload workingset into current session
494
                        loadWorkingSet(workingset.getCitationUuid());
495
                        workingset.add(reg);
496
                    }
497
                    refreshView(true);
498
                    getRepo().commitTransaction(txStatus);
499
                }
500
            } finally {
501
                getRepo().getSession().clear(); // #7702
502
            }
503
            newNameForRegistrationPopupEditor = null;
504
            getView().getAddNewNameRegistrationButton().setEnabled(true);
505
        }
506
    }
507

    
508

    
509
    /**
510
     * Creates a new Registration for an exiting (previously published) name.
511
     *
512
     * @param event
513
     * @throws RegistrationValidationException
514
     */
515
    @EventBusListenerMethod
516
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
517

    
518
        if(!event.isStart()){
519
            return;
520
        }
521

    
522
        getView().getAddExistingNameCombobox().commit(); // update the chosen value in the datasource
523
        TaxonName typifiedName = getView().getAddExistingNameCombobox().getValue();
524
        if(typifiedName != null){
525
            boolean doReloadWorkingSet = false;
526
            Reference citation = getRepo().getReferenceService().find(workingset.getCitationUuid());
527
            // here we completely ignore the ExistingNameRegistrationType since the user should not have the choice
528
            // to create a typification only registration in the working (publication) set which contains
529
            // the protologe. This is known from the nomenclatural reference.
530
            if(canCreateNameRegistrationFor(typifiedName)){
531
                // the citation which is the base for workingset contains the protologe of the name and the name has not
532
                // been registered before:
533
                // create a registration for the name and the first typifications
534
                Registration newRegistrationWithExistingName = getRepo().getRegistrationService().createRegistrationForName(typifiedName.getUuid());
535
                workingset.add(new RegistrationDTO(newRegistrationWithExistingName, typifiedName, citation));
536
                doReloadWorkingSet = true;
537
            } else {
538
                if(!checkWokingsetContainsProtologe(typifiedName)){
539
                    // create a typification only registration
540
                    Registration typificationOnlyRegistration = getRepo().getRegistrationService().newRegistration();
541
                    if(!getRepo().getRegistrationService().checkRegistrationExistsFor(typifiedName)){
542
                        // oops, yet no registration for this name, so we create it as blocking registration:
543
                        Registration blockingNameRegistration = getRepo().getRegistrationService().createRegistrationForName(typifiedName.getUuid());
544
                        typificationOnlyRegistration.getBlockedBy().add(blockingNameRegistration);
545
                    }
546
                    RegistrationDTO regDTO = new RegistrationDTO(typificationOnlyRegistration, typifiedName, citation);
547
                    workingset.add(regDTO);
548
                }
549
            }
550
            // tell the view to update the workingset
551
            refreshView(doReloadWorkingSet);
552
            getView().getAddExistingNameRegistrationButton().setEnabled(false);
553
        } else {
554
            logger.error("Seletced name is NULL");
555
        }
556

    
557
    }
558

    
559

    
560
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
561
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
562

    
563
        if(!checkFromOwnView(event)){
564
            return;
565
        }
566

    
567
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
568
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
569
            popup.setParentEditorActionContext(event.getContext());
570
            popup.withDeleteButton(true);
571
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
572
            if(event.hasSource()){
573
                // propagate readonly state from source button to popup
574
                popup.setReadOnly(event.getSource().isReadOnly());
575
            }
576
        } else {
577
            NameTypeDesignationPopupEditor popup = openPopupEditor(NameTypeDesignationPopupEditor.class, event);
578
            popup.setParentEditorActionContext(event.getContext());
579
            popup.withDeleteButton(true);
580
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
581

    
582
            popup.getCitationCombobox().setEnabled(false);
583
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
584

    
585
            if(event.hasSource()){
586
                // propagate readonly state from source button to popup
587
                popup.setReadOnly(event.getSource().isReadOnly());
588
            }
589
            nameTypeDesignationPopupEditorRegistrationUUIDMap.put(popup, event.getRegistrationUuid());
590
        }
591
    }
592

    
593
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
594
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
595

    
596
        if(!event.hasSource()){
597
            return;
598
        }
599

    
600
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
601
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
602
            popup.setParentEditorActionContext(event.getContext());
603
            TypeDesignationWorkingsetEditorIdSet identifierSet;
604
            UUID typifiedNameUuid;
605

    
606
            RegistrationDTO registrationDTO = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
607
            EntityReference typifiedNameRef = registrationDTO.getTypifiedNameRef();
608
            if(typifiedNameRef != null){
609
                // case for registrations without name, in which case the typifiedName is only defined via the typedesignations
610
                typifiedNameUuid = typifiedNameRef.getUuid();
611
            } else {
612
                // case of registrations with a name in the nomenclatural act.
613
                typifiedNameUuid = registrationDTO.getNameRef().getUuid();
614
            }
615

    
616
            identifierSet = new TypeDesignationWorkingsetEditorIdSet(
617
                    event.getRegistrationUuid(),
618
                    getView().getCitationUuid(),
619
                    typifiedNameUuid
620
                    );
621
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
622
            popup.loadInEditor(identifierSet);
623
            popup.withDeleteButton(true);
624
            if(event.hasSource()){
625
                // propagate readonly state from source component to popup
626
                popup.setReadOnly(event.getSource().isReadOnly());
627
            }
628
        } else {
629
            NameTypeDesignationPopupEditor popup = openPopupEditor(NameTypeDesignationPopupEditor.class, event);
630
            popup.setParentEditorActionContext(event.getContext());
631
            popup.withDeleteButton(true);
632
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
633
            RegistrationDTO regDto = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
634
            Reference citation = regDto.getCitation();
635
            nameTypeDesignationPopupEditorRegistrationUUIDMap.put(popup, event.getRegistrationUuid());
636
            popup.setBeanInstantiator(new BeanInstantiator<NameTypeDesignation>() {
637

    
638
                @Override
639
                public NameTypeDesignation createNewBean() {
640

    
641
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
642
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
643
                    nameTypeDesignation.setCitation(citation);
644
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
645
                    return nameTypeDesignation;
646
                }
647
            });
648
            popup.loadInEditor(null);
649
            popup.getCitationCombobox().setEnabled(false);
650
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
651
            if(event.hasSource()){
652
                // propagate readonly state from source component to popup
653
                popup.setReadOnly(event.getSource().isReadOnly());
654
            }
655
        }
656
    }
657

    
658
    /**
659
     * Performs final actions after a TypeDesignationEditor which has been
660
     * opened to add a TypeDesignation to a Registration object which was
661
     * created for an previously published name. Prior adding a typedesignation,
662
     * the according Registration object is dangling, that has no association to
663
     * any entity denoting an nomenclatural act which has a reference to a
664
     * publication. This means that the registration object is not in the
665
     * working set.
666
     *
667
     *
668
     * @param event
669
     * @throws RegistrationValidationException
670
     */
671
    @EventBusListenerMethod
672
    public void onDoneWithTypeDesignationEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
673
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
674
            if(event.getReason().equals(Reason.SAVE)){
675
                // NOTE: adding the SpecimenTypeDesignations to the registration is done in the
676
                // SpecimenTypeDesignationWorkingSetServiceImpl.save(SpecimenTypeDesignationWorkingSetDTO dto) method
677
                refreshView(true);
678
            } else if(event.getReason().equals(Reason.CANCEL)){
679
                // noting to do
680
            }
681
        } else if(event.getPopup() instanceof NameTypeDesignationPopupEditor){
682
            if(event.getReason().equals(Reason.SAVE)){
683
                UUID typeDesignationUuid = ((NameTypeDesignationPopupEditor)event.getPopup()).getBean().getUuid();
684
                getRepo().getSession().clear();
685
                UUID regUUID = nameTypeDesignationPopupEditorRegistrationUUIDMap.get(event.getPopup());
686
                getRepo().getRegistrationService().addTypeDesignation(regUUID, typeDesignationUuid);
687
                getRepo().getSession().clear();
688
                nameTypeDesignationPopupEditorRegistrationUUIDMap.remove(event.getPopup());
689
                refreshView(true);
690
            } else if(event.getReason().equals(Reason.CANCEL)){
691
                // noting to do
692
            }
693

    
694
        }
695
        // ignore other editors
696
    }
697

    
698

    
699
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
700
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
701

    
702
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
703
            List<String> messages = new ArrayList<>();
704
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
705
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
706
            }
707
            getView().openDetailsPopup("Validation Problems", messages);
708
        }
709
    }
710

    
711
    @EventBusListenerMethod
712
    public void onEntityChangeEvent(EntityChangeEvent event){
713

    
714
        if(workingset == null){
715
            return;
716
        }
717
        if(Reference.class.isAssignableFrom(event.getEntityType())){
718

    
719
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
720
                if(event.isRemovedType()){
721
                    viewEventBus.publish(EventScope.UI, this, new NavigationEvent(StartRegistrationViewBean.NAME));
722
                } else {
723
                    refreshView(true);
724
                }
725
            }
726

    
727
        } else
728
        if(Registration.class.isAssignableFrom(event.getEntityType())){
729
            if(workingset.getRegistrations().stream().anyMatch(reg -> reg.getUuid() == event.getEntityUuid())){
730
                refreshView(true);
731
            }
732
        } else
733
        if(TaxonName.class.isAssignableFrom(event.getEntityType())){
734
            if(event.getType().equals(EntityChangeEvent.Type.CREATED)){
735
                Stack<EditorActionContext>context = ((AbstractPopupEditor)event.getSourceView()).getEditorActionContext();
736
                EditorActionContext rootContext = context.get(0);
737
                if(rootContext.getParentView().equals(getView())){
738
                    // new name! create a blocking registration
739
                    UUID taxonNameUUID = event.getEntityUuid();
740
                    Registration blockingRegistration = getRepo().getRegistrationService().createRegistrationForName(taxonNameUUID);
741
                    TypedEntityReference<Registration> regReference = (TypedEntityReference<Registration>)rootContext.getParentEntity();
742
                    RegistrationDTO registrationDTO = workingset.getRegistrationDTO(regReference.getUuid()).get();
743
                    Registration registration = registrationDTO.registration();
744
                    if(registration == null){
745
                        throw new NullPointerException("Registration not found for " + regReference + " which has been hold in the rootContext");
746
                    }
747
                    registration.getBlockedBy().add(blockingRegistration);
748
                    getRepo().getRegistrationService().saveOrUpdate(registration);
749
                    logger.debug("Blocking registration created");
750
                } else {
751
                    // in case of creating a new name for a registration the parent view is the TaxonNamePopupEditor
752
                    // this is set
753
                    logger.debug("Non blocking registration, since a new name for a new registration has been created");
754
                }
755
            }
756
            if(workingset.getRegistrationDTOs().stream().anyMatch(reg ->
757
                reg.getTypifiedNameRef() != null
758
                && reg.getTypifiedNameRef().getUuid().equals(event.getEntityUuid()))){
759
                    refreshView(true);
760
            }
761
        } else
762
        if(TypeDesignationBase.class.isAssignableFrom(event.getEntityType())){
763
            if(workingset.getRegistrationDTOs().stream().anyMatch(
764
                    reg -> reg.typeDesignations() != null && reg.typeDesignations().stream().anyMatch(
765
                            td -> td.getUuid() == event.getEntityUuid()
766
                            )
767
                        )
768
                    ){
769
                refreshView(true);
770
            }
771
        }
772
    }
773

    
774
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
775
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
776

    
777
        // FIXME check from own view!!!
778
        if(getView() == null){
779
            return;
780
        }
781

    
782
        UUID registrationUuid = event.getIdentifier();
783

    
784
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
785
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
786

    
787
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
788
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
789
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
790

    
791
            RegistrationMessagesPopup popup = openPopupEditor(RegistrationMessagesPopup.class, null);
792
            popup.loadMessagesFor(regDto.getUuid());
793

    
794
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
795
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
796
        }
797
    }
798

    
799
    /**
800
     * {@inheritDoc}
801
     */
802
    @Override
803
    public ICdmCacher getCache() {
804
        return cache;
805
    }
806

    
807
    /**
808
     * {@inheritDoc}
809
     */
810
    @Override
811
    public void addRootEntity(CdmBase entity) {
812
        rootEntities.add(entity);
813
        cache.put(entity);
814
    }
815

    
816

    
817
    /**
818
     * {@inheritDoc}
819
     */
820
    @Override
821
    public Collection<CdmBase> getRootEntities() {
822
        return rootEntities;
823
    }
824

    
825

    
826
    /**
827
     * {@inheritDoc}
828
     */
829
    @Override
830
    public void disposeCache() {
831
        cache.dispose();
832
    }
833

    
834
}
(13-13/20)