Project

General

Profile

Download (35 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.EnumSet;
14
import java.util.HashMap;
15
import java.util.HashSet;
16
import java.util.List;
17
import java.util.Map;
18
import java.util.Objects;
19
import java.util.Set;
20
import java.util.Stack;
21
import java.util.UUID;
22

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

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

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

    
99
/**
100
 * @author a.kohlbecker
101
 * @since Mar 3, 2017
102
 *
103
 */
104
@SpringComponent
105
@ViewScope
106
public class RegistrationWorkingsetPresenter extends AbstractPresenter<RegistrationWorkingsetView> {
107

    
108
    private static final Logger logger = Logger.getLogger(RegistrationWorkingsetPresenter.class);
109

    
110
    private static final List<String> REGISTRATION_INIT_STRATEGY = Arrays.asList(
111
            "$",
112
            "blockedBy",
113
            "name.combinationAuthorship",
114
            "name.exCombinationAuthorship",
115
            "name.basionymAuthorship",
116
            "name.exBasionymAuthorship"
117
            );
118

    
119
    private static final long serialVersionUID = 1L;
120

    
121
    @Autowired
122
    private IRegistrationWorkingSetService regWorkingSetService;
123

    
124
    @Autowired
125
    private IRegistrationMessageService messageService;
126

    
127
    /**
128
     * @return the regWorkingSetService
129
     */
130
    public IRegistrationWorkingSetService getWorkingSetService() {
131
        return regWorkingSetService;
132
    }
133

    
134
    private RegistrationWorkingSet workingset;
135

    
136
    private TaxonName newTaxonNameForRegistration = null;
137

    
138

    
139
    private Map<NameTypeDesignationPopupEditor, UUID> nameTypeDesignationPopupEditorRegistrationUUIDMap = new HashMap<>();
140

    
141

    
142
    /**
143
     *
144
     */
145
    public RegistrationWorkingsetPresenter() {
146
    }
147

    
148
    /**
149
     * Always create a new Store
150
     *
151
     * @return
152
     */
153
    protected CdmStore<Registration, IRegistrationService> getRegistrationStore(){
154
        return new CdmStore<Registration, IRegistrationService>(getRepo(), getRepo().getRegistrationService());
155
    }
156

    
157
    /**
158
     * Always create a new Store
159
     *
160
     * @return
161
     */
162
    protected CdmStore<TaxonName, INameService> getTaxonNameStore(){
163
        return new  CdmStore<TaxonName, INameService>(getRepo(), getRepo().getNameService());
164
    }
165

    
166
    /**
167
     * Checks
168
     * <ol>
169
     * <li>if there is NOT any registration for this name created in the current registration system</li>
170
     * <li>Checks if the name belongs to the current workingset</li>
171
     * </ol>
172
     * If both checks are successful the method returns <code>true</code>.
173
     */
174
    public boolean canCreateNameRegistrationFor(TaxonName name) {
175
        return !getRepo().getRegistrationService().checkRegistrationExistsFor(name) && checkWokingsetContainsProtologe(name);
176
    }
177

    
178
    /**
179
     * @param name
180
     * @return
181
     */
182
    public boolean checkWokingsetContainsProtologe(TaxonName name) {
183
        Reference nomRef = name.getNomenclaturalReference();
184
        UUID citationUuid = workingset.getCitationUuid();
185
        // @formatter:off
186
        return nomRef != null && (
187
                // nomref matches
188
                nomRef.getUuid().equals(citationUuid) ||
189
                // nomref.inreference matches
190
                (nomRef.getType() != null && nomRef.getType() == ReferenceType.Section && nomRef.getInReference() != null && nomRef.getInReference().getUuid().equals(citationUuid))
191
                );
192
        // @formatter:on
193
    }
194

    
195
    /**
196
     * @param doReload TODO
197
     *
198
     */
199
    protected void refreshView(boolean doReload) {
200
        if(workingset == null){
201
            return; // nothing to do
202
        }
203
        if(doReload){
204
            loadWorkingSet(workingset.getCitationUuid());
205
        }
206
        applyWorkingset();
207
    }
208

    
209
    /**
210
     * {@inheritDoc}
211
     */
212
    @Override
213
    public void handleViewEntered() {
214
        super.handleViewEntered();
215
        // TODO currently cannot specify type more precisely, see AbstractSelect
216
        // FIXME externalize into class file!!!!!!!!!!!!
217
        getView().setStatusComponentInstantiator(new RegistrationStatusFieldInstantiator<Object>(){
218

    
219
            private static final long serialVersionUID = 7099181280977511048L;
220

    
221
            @Override
222
            public AbstractField<Object> create(RegistrationDTO regDto) {
223

    
224
                CdmBeanItemContainerFactory selectFieldFactory = new CdmBeanItemContainerFactory(getRepo());
225
                // submitters have GrantedAuthorities like REGISTRATION(PREPARATION).[UPDATE]{ab4459eb-3b96-40ba-bfaa-36915107d59e}
226
                UserHelper userHelper = UserHelperAccess.userHelper();
227
                Set<RegistrationStatus> availableStatus = new HashSet<>();
228

    
229
                boolean canChangeStatus = userHelper.userHasPermission(regDto.registration(), CRUD.UPDATE);
230
                availableStatus.add(regDto.getStatus());
231
                if(canChangeStatus){
232
                    if(userHelper.userIsAdmin()){
233
                        availableStatus.addAll(Arrays.asList(RegistrationStatus.values()));
234
                    } else {
235
                        availableStatus.addAll(RegistrationStatusTransitions.possibleTransitions(regDto.getStatus()));
236
                    }
237
                }
238

    
239
                RegistrationStatusSelect select = new RegistrationStatusSelect(null, selectFieldFactory.buildBeanItemContainer(
240
                        RegistrationStatus.class,
241
                        availableStatus.toArray(new RegistrationStatus[availableStatus.size()]))
242
                        );
243
                select.addValueChangeListener(e -> saveRegistrationStatusChange(regDto.getUuid(), e.getProperty().getValue()));
244
                select.setEnabled(canChangeStatus);
245
                select.setNullSelectionAllowed(false);
246
                return select;
247
            }
248

    
249

    
250
        });
251
        loadWorkingSet(getView().getCitationUuid());
252
        applyWorkingset();
253

    
254
    }
255

    
256
    private void applyWorkingset(){
257
         getView().setWorkingset(workingset);
258
        // PagingProviders and CacheGenerator for the existingNameCombobox
259
        activateComboboxes();
260
        // update the messages
261
        updateMessages();
262
    }
263

    
264
    /**
265
     *
266
     */
267
    protected void activateComboboxes() {
268
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
269
                getRepo().getNameService());
270
        pagingProvider.setInitStrategy(Arrays.asList("registrations", "nomenclaturalReference", "nomenclaturalReference.inReference"));
271
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
272
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
273
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
274
    }
275

    
276
    /**
277
     *
278
     */
279
    protected void updateMessages() {
280
        User user = UserHelperAccess.userHelper().user();
281
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
282
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
283

    
284
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
285
            try {
286
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
287

    
288
                boolean activeMessages = messageCount > 0;
289
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName() != null && regDto.getSubmitterUserName().equals(UserHelperAccess.userHelper().userName());
290
                boolean currentUserIsCurator = UserHelperAccess.userHelper().userIs(new RegistrationCuratorRoleProbe());
291
                messageButton.setEnabled(false);
292
                if(currentUserIsCurator){
293
                    if(currentUserIsSubmitter){
294
                        messageButton.setDescription("No point sending messages to your self.");
295
                    } else {
296
                        messageButton.setEnabled(true);
297
                        messageButton.setDescription("Open the messages dialog.");
298
                    }
299
                } else {
300
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
301
                }
302
                if(activeMessages){
303
                    messageButton.setEnabled(true);
304
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
305
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
306
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
307

    
308
                }
309
            } catch (ExternalServiceException e) {
310
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
311
            }
312
        }
313
    }
314

    
315

    
316
    /**
317
     * @param referenceID
318
     */
319
    protected void loadWorkingSet(UUID referenceUuid) {
320
        try {
321
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid, true);
322
        } catch (RegistrationValidationException error) {
323
            logger.error(error);
324
            Window errorDialog = new Window("Validation Error");
325
            errorDialog.setModal(true);
326
            VerticalLayout subContent = new VerticalLayout();
327
            subContent.setMargin(true);
328
            errorDialog.setContent(subContent);
329
            subContent.addComponent(new Label(error.getMessage()));
330
            UI.getCurrent().addWindow(errorDialog);
331
        }
332
        if(workingset == null || workingset.getCitationUuid() == null){
333
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
334
            workingset = new RegistrationWorkingSet(citation);
335
        }
336
    }
337

    
338
    private void saveRegistrationStatusChange(UUID uuid, Object value) {
339
        Registration reg = getRepo().getRegistrationService().load(uuid);
340
        if(reg == null){
341
            // registration was not yet persisted, ignore
342
            return;
343
        }
344
        if(value != null && value instanceof RegistrationStatus){
345
            if(!Objects.equals(value, reg.getStatus())){
346
                reg.setStatus((RegistrationStatus)value);
347
                getRegistrationStore().saveBean(reg, (AbstractView)getView());
348
                refreshView(true);
349
            }
350
        } else {
351
            // only log here as error
352
            logger.error("Ivalid attempt to set RegistrationStatus to " + Objects.toString(value.toString(), "NULL"));
353
        }
354
    }
355

    
356

    
357
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
358
    public void onReferenceEditorActionAdd(ReferenceEditorAction event) {
359

    
360
        if(!checkFromOwnView(event)){
361
            return;
362
        }
363

    
364
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
365
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
366
        popup.loadInEditor(null);
367
    }
368

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

    
372
        if(!checkFromOwnView(event)){
373
            return;
374
        }
375
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
376
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
377
        popup.withDeleteButton(true);
378
        popup.loadInEditor(event.getEntityUuid());
379
    }
380

    
381
    @EventBusListenerMethod
382
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
383
        if(event.getPopup() instanceof ReferencePopupEditor){
384
            if(event.getReason().equals(Reason.SAVE)){
385
                refreshView(true);
386
            }
387
        }
388
    }
389

    
390
    @EventBusListenerMethod
391
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
392
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
393
            if(event.getReason().equals(Reason.SAVE)){
394
                refreshView(true);
395
            }
396
        }
397
    }
398

    
399
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
400
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
401

    
402
        if(!checkFromOwnView(event)){
403
            return;
404
        }
405

    
406
        RegistrationPopupEditor popup = openPopupEditor(RegistrationPopupEditor.class, event);
407
        popup.loadInEditor(event.getEntityUuid());
408
    }
409

    
410
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
411
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
412

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

    
417
        TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
418
        popup.setParentEditorActionContext(event.getContext());
419
        popup.withDeleteButton(true);
420
        configureTaxonNameEditor(popup);
421
        popup.loadInEditor(event.getEntityUuid());
422
        if(event.hasSource() && event.getSource().isReadOnly()){
423
            // avoid resetting readonly to false
424
            popup.setReadOnly(true);
425
        }
426

    
427
    }
428

    
429

    
430
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
431
    public void onTaxonNameEditorActionAdd(TaxonNameEditorAction event) {
432

    
433
        if(!checkFromOwnView(event)){
434
            return;
435
        }
436

    
437
        newTaxonNameForRegistration = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
438
        newTaxonNameForRegistration.setNomenclaturalReference(getRepo().getReferenceService().find(workingset.getCitationUuid()));
439
        EntityChangeEvent nameSaveEvent = getTaxonNameStore().saveBean(newTaxonNameForRegistration, (AbstractView) getView());
440
        newTaxonNameForRegistration = getRepo().getNameService().find(nameSaveEvent.getEntityUuid());
441
        TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
442
        popup.setParentEditorActionContext(event.getContext());
443
        popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
444
        popup.withDeleteButton(true);
445
        configureTaxonNameEditor(popup);
446
        popup.loadInEditor(newTaxonNameForRegistration.getUuid());
447
    }
448

    
449
    /**
450
     * TODO consider putting this into a Configurer Bean per UIScope.
451
     * In the configurator bean this methods popup papamerter should be of the type
452
     * AbstractPopupEditor
453
     *
454
     * @param popup
455
     */
456
    protected void configureTaxonNameEditor(TaxonNamePopupEditorView popup) {
457
        popup.enableMode(TaxonNamePopupEditorMode.AUTOFILL_AUTHORSHIP_DATA);
458
        popup.enableMode(TaxonNamePopupEditorMode.NOMENCLATURALREFERENCE_SECTION_EDITING_ONLY);
459
        popup.enableMode(TaxonNamePopupEditorMode.VALIDATE_AGAINST_HIGHER_NAME_PART);
460
        // popup.enableMode(TaxonNamePopupEditorMode.REQUIRE_NOMENCLATURALREFERENCE);
461
    }
462

    
463
    /**
464
     * Creates a new <code>Registration</code> for a new name that has just been edited
465
     * using the <code>TaxonNamePopupEditor</code>. The new name was previously created
466
     * in this presenter as <code>newTaxonNameForRegistration</code> (see {@link #onTaxonNameEditorActionAdd(TaxonNameEditorAction)})
467
     * and is either filled with data (<code>Reason.SAVE</code>) or it is still empty
468
     * (<code>Reason.CANCEL</code>).
469
     *
470
     *
471
     * @param event
472
     * @throws RegistrationValidationException
473
     */
474
    @EventBusListenerMethod
475
    public void onDoneWithTaxonnameEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
476
        if(event.getPopup() instanceof TaxonNamePopupEditor){
477
            TransactionStatus txStatus = getRepo().startTransaction();
478
            if(event.getReason().equals(Reason.SAVE)){
479
                if(newTaxonNameForRegistration != null){
480
                    UUID taxonNameUuid = newTaxonNameForRegistration.getUuid();
481
                    getRepo().getSession().refresh(newTaxonNameForRegistration);
482
                    Registration reg = getRepo().getRegistrationService().createRegistrationForName(taxonNameUuid);
483
                    // reload workingset into current session
484
                    loadWorkingSet(workingset.getCitationUuid());
485
                    workingset.add(reg);
486
                }
487
                refreshView(true);
488
            } else if(event.getReason().equals(Reason.CANCEL)){
489
                if(newTaxonNameForRegistration != null){
490
                    // clean up
491
                    getTaxonNameStore().deleteBean(newTaxonNameForRegistration, (AbstractView) getView());
492
                }
493
            }
494
            getRepo().commitTransaction(txStatus);
495
            newTaxonNameForRegistration = null;
496
        }
497
    }
498

    
499

    
500
    /**
501
     * Creates a new Registration for an exiting (previously published) name.
502
     *
503
     * @param event
504
     * @throws RegistrationValidationException
505
     */
506
    @EventBusListenerMethod
507
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
508

    
509
        if(!event.isStart()){
510
            return;
511
        }
512

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

    
548
    }
549

    
550

    
551
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
552
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
553

    
554
        if(!checkFromOwnView(event)){
555
            return;
556
        }
557

    
558
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
559
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
560
            popup.setParentEditorActionContext(event.getContext());
561
            popup.withDeleteButton(true);
562
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
563
            if(event.hasSource()){
564
                // propagate readonly state from source button to popup
565
                popup.setReadOnly(event.getSource().isReadOnly());
566
            }
567
        } else {
568
            NameTypeDesignationPopupEditor popup = openPopupEditor(NameTypeDesignationPopupEditor.class, event);
569
            popup.setParentEditorActionContext(event.getContext());
570
            popup.withDeleteButton(true);
571
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
572

    
573
            popup.getCitationCombobox().setEnabled(false);
574
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
575

    
576
            if(event.hasSource()){
577
                // propagate readonly state from source button to popup
578
                popup.setReadOnly(event.getSource().isReadOnly());
579
            }
580
            nameTypeDesignationPopupEditorRegistrationUUIDMap.put(popup, event.getRegistrationUuid());
581
        }
582
    }
583

    
584
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
585
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
586

    
587
        if(!event.hasSource()){
588
            return;
589
        }
590

    
591
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
592
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
593
            popup.setParentEditorActionContext(event.getContext());
594
            TypeDesignationWorkingsetEditorIdSet identifierSet;
595
            UUID typifiedNameUuid;
596

    
597
            RegistrationDTO registrationDTO = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
598
            EntityReference typifiedNameRef = registrationDTO.getTypifiedNameRef();
599
            if(typifiedNameRef != null){
600
                // case for registrations without name, in which case the typifiedName is only defined via the typedesignations
601
                typifiedNameUuid = typifiedNameRef.getUuid();
602
            } else {
603
                // case of registrations with a name in the nomenclatural act.
604
                typifiedNameUuid = registrationDTO.getNameRef().getUuid();
605
            }
606

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

    
629
                @Override
630
                public NameTypeDesignation createNewBean() {
631

    
632
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
633
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
634
                    nameTypeDesignation.setCitation(citation);
635
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
636
                    return nameTypeDesignation;
637
                }
638
            });
639
            popup.loadInEditor(null);
640
            popup.getCitationCombobox().setEnabled(false);
641
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
642
            if(event.hasSource()){
643
                // propagate readonly state from source component to popup
644
                popup.setReadOnly(event.getSource().isReadOnly());
645
            }
646
        }
647
    }
648

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

    
685
        }
686
        // ignore other editors
687
    }
688

    
689

    
690
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
691
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
692

    
693
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
694
            List<String> messages = new ArrayList<>();
695
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
696
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
697
            }
698
            getView().openDetailsPopup("Validation Problems", messages);
699
        }
700
    }
701

    
702
    @EventBusListenerMethod
703
    public void onEntityChangeEvent(EntityChangeEvent event){
704

    
705
        if(workingset == null){
706
            return;
707
        }
708
        if(Reference.class.isAssignableFrom(event.getEntityType())){
709

    
710
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
711
                if(event.isRemovedType()){
712
                    viewEventBus.publish(EventScope.UI, this, new NavigationEvent(StartRegistrationViewBean.NAME));
713
                } else {
714
                    refreshView(true);
715
                }
716
            }
717

    
718
        } else
719
        if(Registration.class.isAssignableFrom(event.getEntityType())){
720
            if(workingset.getRegistrations().stream().anyMatch(reg -> reg.getUuid() == event.getEntityUuid())){
721
                refreshView(true);
722
            }
723
        } else
724
        if(TaxonName.class.isAssignableFrom(event.getEntityType()) && isFromOwnView(event)){
725
            if(event.getType().equals(EntityChangeEvent.Type.CREATED)){
726
                // new name! create a blocking registration
727
                Stack<EditorActionContext>context = ((AbstractPopupEditor)event.getSourceView()).getEditorActionContext();
728
                EditorActionContext rootContext = context.get(0);
729
                if(rootContext.getParentView().equals(getView())){
730
                    Registration blockingRegistration = getRepo().getRegistrationService().createRegistrationForName(event.getEntityUuid());
731
                    TypedEntityReference<Registration> regReference = (TypedEntityReference<Registration>)rootContext.getParentEntity();
732
                    Registration registration = getRepo().getRegistrationService().load(regReference.getUuid(), REGISTRATION_INIT_STRATEGY);
733
                    registration.getBlockedBy().add(blockingRegistration);
734
                    getRepo().getRegistrationService().saveOrUpdate(registration);
735
                    logger.debug("Blocking registration created");
736
                } else {
737
                    logger.debug("Non blocking registration, since a new name for a new registration has been created");
738
                }
739
            }
740
            if(workingset.getRegistrationDTOs().stream().anyMatch(reg ->
741
                reg.getTypifiedNameRef() != null
742
                && reg.getTypifiedNameRef().getUuid().equals(event.getEntityUuid()))){
743
                    refreshView(true);
744
            }
745
        } else
746
        if(TypeDesignationBase.class.isAssignableFrom(event.getEntityType())){
747
            if(workingset.getRegistrationDTOs().stream().anyMatch(
748
                    reg -> reg.typeDesignations() != null && reg.typeDesignations().stream().anyMatch(
749
                            td -> td.getUuid() == event.getEntityUuid()
750
                            )
751
                        )
752
                    ){
753
                refreshView(true);
754
            }
755
        }
756
    }
757

    
758

    
759
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
760
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
761

    
762
        // FIXME check from own view!!!
763
        if(getView() == null){
764
            return;
765
        }
766

    
767
        UUID registrationUuid = event.getIdentifier();
768

    
769
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
770
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
771

    
772
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
773
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
774
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
775

    
776
            RegistrationMessagesPopup popup = openPopupEditor(RegistrationMessagesPopup.class, null);
777
            popup.loadMessagesFor(regDto.getUuid());
778

    
779
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
780
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
781
        }
782

    
783

    
784
    }
785

    
786
}
(12-12/19)