Project

General

Profile

Download (35.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.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.RoleProber;
48
import eu.etaxonomy.cdm.api.utility.UserHelper;
49
import eu.etaxonomy.cdm.ext.common.ExternalServiceException;
50
import eu.etaxonomy.cdm.ext.registration.messages.IRegistrationMessageService;
51
import eu.etaxonomy.cdm.model.common.User;
52
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
53
import eu.etaxonomy.cdm.model.name.Rank;
54
import eu.etaxonomy.cdm.model.name.Registration;
55
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
56
import eu.etaxonomy.cdm.model.name.TaxonName;
57
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
58
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
59
import eu.etaxonomy.cdm.model.reference.Reference;
60
import eu.etaxonomy.cdm.model.reference.ReferenceType;
61
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
62
import eu.etaxonomy.cdm.ref.EntityReference;
63
import eu.etaxonomy.cdm.ref.TypedEntityReference;
64
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
65
import eu.etaxonomy.cdm.service.CdmStore;
66
import eu.etaxonomy.cdm.service.UserHelperAccess;
67
import eu.etaxonomy.cdm.vaadin.component.CdmBeanItemContainerFactory;
68
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationItem;
69
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationStatusFieldInstantiator;
70
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationStatusSelect;
71
import eu.etaxonomy.cdm.vaadin.event.AbstractEditorAction.EditorActionContext;
72
import eu.etaxonomy.cdm.vaadin.event.EditorActionTypeFilter;
73
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
74
import eu.etaxonomy.cdm.vaadin.event.ReferenceEditorAction;
75
import eu.etaxonomy.cdm.vaadin.event.RegistrationEditorAction;
76
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEvent;
77
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEventEntityTypeFilter;
78
import eu.etaxonomy.cdm.vaadin.event.TaxonNameEditorAction;
79
import eu.etaxonomy.cdm.vaadin.event.TypeDesignationWorkingsetEditorAction;
80
import eu.etaxonomy.cdm.vaadin.event.registration.RegistrationWorkingsetAction;
81
import eu.etaxonomy.cdm.vaadin.permission.RolesAndPermissions;
82
import eu.etaxonomy.cdm.vaadin.theme.EditValoTheme;
83
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
84
import eu.etaxonomy.cdm.vaadin.util.CdmTitleCacheCaptionGenerator;
85
import eu.etaxonomy.cdm.vaadin.view.name.NameTypeDesignationPopupEditor;
86
import eu.etaxonomy.cdm.vaadin.view.name.SpecimenTypeDesignationWorkingsetPopupEditor;
87
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditor;
88
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorMode;
89
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorView;
90
import eu.etaxonomy.cdm.vaadin.view.name.TypeDesignationWorkingsetEditorIdSet;
91
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
92
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
93
import eu.etaxonomy.vaadin.mvp.AbstractPresenter;
94
import eu.etaxonomy.vaadin.mvp.AbstractView;
95
import eu.etaxonomy.vaadin.mvp.BeanInstantiator;
96
import eu.etaxonomy.vaadin.ui.navigation.NavigationEvent;
97
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent;
98
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent.Reason;
99

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

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

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

    
120
    private static final long serialVersionUID = 1L;
121

    
122
    @Autowired
123
    private IRegistrationWorkingSetService regWorkingSetService;
124

    
125
    @Autowired
126
    private IRegistrationMessageService messageService;
127

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

    
135
    private RegistrationWorkingSet workingset;
136

    
137
    private TaxonName newTaxonNameForRegistration = null;
138

    
139

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

    
142

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

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

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

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

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

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

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

    
220
            private static final long serialVersionUID = 7099181280977511048L;
221

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

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

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

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

    
250

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

    
255
    }
256

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

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

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

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

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

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

    
316

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

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

    
357

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

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

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

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

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

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

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

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

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

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

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

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

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

    
428
    }
429

    
430

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

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

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

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

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

    
504

    
505
    /**
506
     * Creates a new Registration for an exiting (previously published) name.
507
     *
508
     * @param event
509
     * @throws RegistrationValidationException
510
     */
511
    @EventBusListenerMethod
512
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
513

    
514
        if(!event.isStart()){
515
            return;
516
        }
517

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

    
553
    }
554

    
555

    
556
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
557
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
558

    
559
        if(!checkFromOwnView(event)){
560
            return;
561
        }
562

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

    
578
            popup.getCitationCombobox().setEnabled(false);
579
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
580

    
581
            if(event.hasSource()){
582
                // propagate readonly state from source button to popup
583
                popup.setReadOnly(event.getSource().isReadOnly());
584
            }
585
            nameTypeDesignationPopupEditorRegistrationUUIDMap.put(popup, event.getRegistrationUuid());
586
        }
587
    }
588

    
589
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
590
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
591

    
592
        if(!event.hasSource()){
593
            return;
594
        }
595

    
596
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
597
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
598
            popup.setParentEditorActionContext(event.getContext());
599
            TypeDesignationWorkingsetEditorIdSet identifierSet;
600
            UUID typifiedNameUuid;
601

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

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

    
634
                @Override
635
                public NameTypeDesignation createNewBean() {
636

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

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

    
690
        }
691
        // ignore other editors
692
    }
693

    
694

    
695
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
696
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
697

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

    
707
    @EventBusListenerMethod
708
    public void onEntityChangeEvent(EntityChangeEvent event){
709

    
710
        if(workingset == null){
711
            return;
712
        }
713
        if(Reference.class.isAssignableFrom(event.getEntityType())){
714

    
715
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
716
                if(event.isRemovedType()){
717
                    viewEventBus.publish(EventScope.UI, this, new NavigationEvent(StartRegistrationViewBean.NAME));
718
                } else {
719
                    refreshView(true);
720
                }
721
            }
722

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

    
763

    
764
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
765
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
766

    
767
        // FIXME check from own view!!!
768
        if(getView() == null){
769
            return;
770
        }
771

    
772
        UUID registrationUuid = event.getIdentifier();
773

    
774
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
775
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
776

    
777
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
778
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
779
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
780

    
781
            RegistrationMessagesPopup popup = openPopupEditor(RegistrationMessagesPopup.class, null);
782
            popup.loadMessagesFor(regDto.getUuid());
783

    
784
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
785
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
786
        }
787

    
788

    
789
    }
790

    
791
}
(12-12/19)