Project

General

Profile

Download (30.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.List;
15
import java.util.Set;
16
import java.util.Stack;
17
import java.util.UUID;
18

    
19
import org.hibernate.Session;
20
import org.hibernate.Transaction;
21
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.security.core.Authentication;
23
import org.springframework.transaction.TransactionStatus;
24
import org.vaadin.spring.events.annotation.EventBusListenerMethod;
25

    
26
import com.vaadin.server.SystemError;
27
import com.vaadin.spring.annotation.SpringComponent;
28
import com.vaadin.spring.annotation.ViewScope;
29
import com.vaadin.ui.Button;
30
import com.vaadin.ui.Label;
31
import com.vaadin.ui.UI;
32
import com.vaadin.ui.VerticalLayout;
33
import com.vaadin.ui.Window;
34

    
35
import eu.etaxonomy.cdm.api.service.INameService;
36
import eu.etaxonomy.cdm.api.service.IRegistrationService;
37
import eu.etaxonomy.cdm.api.service.idminter.IdentifierMinter.Identifier;
38
import eu.etaxonomy.cdm.api.service.idminter.RegistrationIdentifierMinter;
39
import eu.etaxonomy.cdm.ext.common.ExternalServiceException;
40
import eu.etaxonomy.cdm.ext.registration.messages.IRegistrationMessageService;
41
import eu.etaxonomy.cdm.model.common.User;
42
import eu.etaxonomy.cdm.model.name.NameTypeDesignation;
43
import eu.etaxonomy.cdm.model.name.Rank;
44
import eu.etaxonomy.cdm.model.name.Registration;
45
import eu.etaxonomy.cdm.model.name.RegistrationStatus;
46
import eu.etaxonomy.cdm.model.name.TaxonName;
47
import eu.etaxonomy.cdm.model.name.TaxonNameFactory;
48
import eu.etaxonomy.cdm.model.name.TypeDesignationBase;
49
import eu.etaxonomy.cdm.model.reference.Reference;
50
import eu.etaxonomy.cdm.persistence.hibernate.permission.CRUD;
51
import eu.etaxonomy.cdm.persistence.hibernate.permission.Operation;
52
import eu.etaxonomy.cdm.service.CdmFilterablePagingProvider;
53
import eu.etaxonomy.cdm.service.CdmStore;
54
import eu.etaxonomy.cdm.service.IRegistrationWorkingSetService;
55
import eu.etaxonomy.cdm.vaadin.component.registration.RegistrationItem;
56
import eu.etaxonomy.cdm.vaadin.event.AbstractEditorAction.EditorActionContext;
57
import eu.etaxonomy.cdm.vaadin.event.EditorActionTypeFilter;
58
import eu.etaxonomy.cdm.vaadin.event.EntityChangeEvent;
59
import eu.etaxonomy.cdm.vaadin.event.ReferenceEditorAction;
60
import eu.etaxonomy.cdm.vaadin.event.RegistrationEditorAction;
61
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEvent;
62
import eu.etaxonomy.cdm.vaadin.event.ShowDetailsEventEntityTypeFilter;
63
import eu.etaxonomy.cdm.vaadin.event.TaxonNameEditorAction;
64
import eu.etaxonomy.cdm.vaadin.event.TypeDesignationWorkingsetEditorAction;
65
import eu.etaxonomy.cdm.vaadin.event.registration.RegistrationWorkingsetAction;
66
import eu.etaxonomy.cdm.vaadin.model.EntityReference;
67
import eu.etaxonomy.cdm.vaadin.model.TypedEntityReference;
68
import eu.etaxonomy.cdm.vaadin.model.registration.RegistrationWorkingSet;
69
import eu.etaxonomy.cdm.vaadin.security.UserHelper;
70
import eu.etaxonomy.cdm.vaadin.theme.EditValoTheme;
71
import eu.etaxonomy.cdm.vaadin.ui.RegistrationUIDefaults;
72
import eu.etaxonomy.cdm.vaadin.util.CdmTitleCacheCaptionGenerator;
73
import eu.etaxonomy.cdm.vaadin.util.converter.TypeDesignationSetManager.TypeDesignationWorkingSetType;
74
import eu.etaxonomy.cdm.vaadin.view.name.NameTypeDesignationPopupEditor;
75
import eu.etaxonomy.cdm.vaadin.view.name.SpecimenTypeDesignationWorkingsetPopupEditor;
76
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditor;
77
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorMode;
78
import eu.etaxonomy.cdm.vaadin.view.name.TaxonNamePopupEditorView;
79
import eu.etaxonomy.cdm.vaadin.view.name.TypeDesignationWorkingsetEditorIdSet;
80
import eu.etaxonomy.cdm.vaadin.view.reference.ReferencePopupEditor;
81
import eu.etaxonomy.vaadin.mvp.AbstractPopupEditor;
82
import eu.etaxonomy.vaadin.mvp.AbstractPresenter;
83
import eu.etaxonomy.vaadin.mvp.AbstractView;
84
import eu.etaxonomy.vaadin.mvp.BeanInstantiator;
85
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent;
86
import eu.etaxonomy.vaadin.ui.view.DoneWithPopupEvent.Reason;
87

    
88
/**
89
 * @author a.kohlbecker
90
 * @since Mar 3, 2017
91
 *
92
 */
93
@SpringComponent
94
@ViewScope
95
public class RegistrationWorkingsetPresenter extends AbstractPresenter<RegistrationWorkingsetView> {
96

    
97
    private static final long serialVersionUID = 1L;
98

    
99
    @Autowired
100
    private IRegistrationWorkingSetService regWorkingSetService;
101

    
102
    @Autowired
103
    private RegistrationIdentifierMinter minter;
104

    
105
    @Autowired
106
    private IRegistrationMessageService messageService;
107

    
108
    /**
109
     * @return the regWorkingSetService
110
     */
111
    public IRegistrationWorkingSetService getWorkingSetService() {
112
        return regWorkingSetService;
113
    }
114

    
115
    private RegistrationWorkingSet workingset;
116

    
117
    private TaxonName newTaxonNameForRegistration = null;
118

    
119
    private RegistrationDTO newRegistrationDTOWithExistingName;
120

    
121
    private RegistrationDTO newNameTypeDesignationTarget;
122

    
123

    
124
    /**
125
     *
126
     */
127
    public RegistrationWorkingsetPresenter() {
128
    }
129

    
130
    /**
131
     * Always create a new Store
132
     *
133
     * @return
134
     */
135
    protected CdmStore<Registration, IRegistrationService> getRegistrationStore(){
136
        return new CdmStore<Registration, IRegistrationService>(getRepo(), getRepo().getRegistrationService());
137
    }
138

    
139
    /**
140
     * Always create a new Store
141
     *
142
     * @return
143
     */
144
    protected CdmStore<TaxonName, INameService> getTaxonNameStore(){
145
        return new  CdmStore<TaxonName, INameService>(getRepo(), getRepo().getNameService());
146
    }
147

    
148

    
149
    /**
150
     * @param taxonNameId
151
     * @return
152
     */
153
    protected Registration createNewRegistrationForName(UUID taxonNameUuid) {
154
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
155
        // move into RegistrationWorkflowStateMachine
156
        TransactionStatus txStatus = getRepo().startTransaction();
157

    
158
        Identifier<String> identifiers = minter.mint();
159
        if(identifiers.getIdentifier() == null){
160
            throw new RuntimeException("RegistrationIdentifierMinter configuration incomplete.");
161
        }
162
        Registration reg = Registration.NewInstance(
163
                identifiers.getIdentifier(),
164
                identifiers.getLocalId(),
165
                taxonNameUuid != null ? getRepo().getNameService().find(taxonNameUuid) : null,
166
                null);
167
        Authentication authentication = currentSecurityContext().getAuthentication();
168
        reg.setSubmitter((User)authentication.getPrincipal());
169
        EntityChangeEvent event = getRegistrationStore().saveBean(reg, (AbstractView) getView());
170
        UserHelper.fromSession().createAuthorityForCurrentUser(Registration.class, event.getEntityUuid(), Operation.UPDATE, RegistrationStatus.PREPARATION.name());
171
        getRepo().commitTransaction(txStatus);
172
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173
        return getRepo().getRegistrationService().load(event.getEntityUuid(), Arrays.asList(new String []{"blockedBy"}));
174
    }
175

    
176

    
177
    /**
178
     * @param doReload TODO
179
     *
180
     */
181
    protected void refreshView(boolean doReload) {
182
        if(workingset == null){
183
            return; // nothing to do
184
        }
185
        if(doReload){
186
            loadWorkingSet(workingset.getCitationUuid());
187
        }
188
        getView().setWorkingset(workingset);
189
    }
190

    
191

    
192
    /**
193
     * {@inheritDoc}
194
     */
195
    @Override
196
    public void handleViewEntered() {
197

    
198
        super.handleViewEntered();
199

    
200
        loadWorkingSet(getView().getCitationUuid());
201
        getView().setWorkingset(workingset);
202

    
203
        // PagingProviders and CacheGenerator for the existingNameCombobox
204
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
205
                getRepo().getNameService());
206
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
207
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
208
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
209

    
210
        // update the messages
211
        User user = UserHelper.fromSession().user();
212
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
213
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
214

    
215
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
216
            try {
217
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
218

    
219
                boolean activeMessages = messageCount > 0;
220
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName().equals(UserHelper.fromSession().userName());
221
                boolean currentUserIsCurator = UserHelper.fromSession().userIsRegistrationCurator();
222
                messageButton.setEnabled(false);
223
                if(currentUserIsCurator){
224
                    if(currentUserIsSubmitter){
225
                        messageButton.setDescription("No point sending messages to your self.");
226
                    } else {
227
                        messageButton.setEnabled(true);
228
                        messageButton.setDescription("Open the messages dialog.");
229
                    }
230
                } else {
231
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
232
                }
233
                if(activeMessages){
234
                    messageButton.setEnabled(true);
235
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
236
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
237
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
238

    
239
                }
240
            } catch (ExternalServiceException e) {
241
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
242
            }
243
        }
244

    
245
    }
246

    
247

    
248
    /**
249
     * @param referenceID
250
     */
251
    protected void loadWorkingSet(UUID referenceUuid) {
252
        try {
253
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid);
254
        } catch (RegistrationValidationException error) {
255
            logger.error(error);
256
            Window errorDialog = new Window("Validation Error");
257
            errorDialog.setModal(true);
258
            VerticalLayout subContent = new VerticalLayout();
259
            subContent.setMargin(true);
260
            errorDialog.setContent(subContent);
261
            subContent.addComponent(new Label(error.getMessage()));
262
            UI.getCurrent().addWindow(errorDialog);
263
        }
264
        if(workingset == null || workingset.getCitationUuid() == null){
265
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
266
            workingset = new RegistrationWorkingSet(citation);
267
        }
268
    }
269

    
270

    
271
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
272
    public void onReferenceEditorActionAdd(ReferenceEditorAction event) {
273

    
274
        if(!checkFromOwnView(event)){
275
            return;
276
        }
277

    
278
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView());
279
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
280
        popup.loadInEditor(null);
281
    }
282

    
283
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
284
    public void onReferenceEditorActionEdit(ReferenceEditorAction event) {
285

    
286
        if(!checkFromOwnView(event)){
287
            return;
288
        }
289
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView());
290
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
291
        popup.withDeleteButton(true);
292
        popup.loadInEditor(event.getEntityUuid());
293
    }
294

    
295
    @EventBusListenerMethod
296
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
297
        if(event.getPopup() instanceof ReferencePopupEditor){
298
            if(event.getReason().equals(Reason.SAVE)){
299
                refreshView(true);
300
            }
301
        }
302
    }
303

    
304
    @EventBusListenerMethod
305
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
306
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
307
            if(event.getReason().equals(Reason.SAVE)){
308
                refreshView(true);
309
            }
310
        }
311
    }
312

    
313
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
314
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
315

    
316
        if(!checkFromOwnView(event)){
317
            return;
318
        }
319

    
320
        RegistrationPopupEditor popup = getNavigationManager().showInPopup(RegistrationPopupEditor.class, getView());
321
        popup.loadInEditor(event.getEntityUuid());
322
    }
323

    
324
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
325
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
326

    
327
        if(!checkFromOwnView(event)){
328
            return;
329
        }
330

    
331
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView());
332
        popup.setParentEditorActionContext(event.getContext());
333
        popup.withDeleteButton(true);
334
        configureTaxonNameEditor(popup);
335
        popup.loadInEditor(event.getEntityUuid());
336
        if(event.getSourceComponent() != null){
337
            popup.setReadOnly(event.getSourceComponent().isReadOnly());
338
        }
339

    
340
    }
341

    
342

    
343
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
344
    public void onTaxonNameEditorActionAdd(TaxonNameEditorAction event) {
345

    
346
        if(!checkFromOwnView(event)){
347
            return;
348
        }
349

    
350
        newTaxonNameForRegistration = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
351
        newTaxonNameForRegistration.setNomenclaturalReference(getRepo().getReferenceService().find(workingset.getCitationUuid()));
352
        EntityChangeEvent nameSaveEvent = getTaxonNameStore().saveBean(newTaxonNameForRegistration, (AbstractView) getView());
353
        newTaxonNameForRegistration = getRepo().getNameService().find(nameSaveEvent.getEntityUuid());
354
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView());
355
        popup.setParentEditorActionContext(event.getContext());
356
        popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
357
        popup.withDeleteButton(true);
358
        configureTaxonNameEditor(popup);
359
        popup.loadInEditor(newTaxonNameForRegistration.getUuid());
360
    }
361

    
362
    /**
363
     * TODO consider putting this into a Configurer Bean per UIScope.
364
     * In the configurator bean this methods popup papamerter should be of the type
365
     * AbstractPopupEditor
366
     *
367
     * @param popup
368
     */
369
    protected void configureTaxonNameEditor(TaxonNamePopupEditorView popup) {
370
        popup.enableMode(TaxonNamePopupEditorMode.AUTOFILL_AUTHORSHIP_DATA);
371
        popup.enableMode(TaxonNamePopupEditorMode.NOMENCLATURALREFERENCE_SECTION_EDITING_ONLY);
372
        // popup.enableMode(TaxonNamePopupEditorMode.REQUIRE_NOMENCLATURALREFERENCE);
373
    }
374

    
375
    /**
376
     * Creates a new <code>Registration</code> for a new name that has just been edited
377
     * using the <code>TaxonNamePopupEditor</code>. The new name was previously created
378
     * in this presenter as <code>newTaxonNameForRegistration</code> (see {@link #onTaxonNameEditorActionAdd(TaxonNameEditorAction)})
379
     * and is either filled with data (<code>Reason.SAVE</code>) or it is still empty
380
     * (<code>Reason.CANCEL</code>).
381
     *
382
     *
383
     * @param event
384
     * @throws RegistrationValidationException
385
     */
386
    @EventBusListenerMethod
387
    public void onDoneWithTaxonnameEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
388
        if(event.getPopup() instanceof TaxonNamePopupEditor){
389
            TransactionStatus txStatus = getRepo().startTransaction();
390
            if(event.getReason().equals(Reason.SAVE)){
391
                if(newTaxonNameForRegistration != null){
392
                    UUID taxonNameUuid = newTaxonNameForRegistration.getUuid();
393
                    getRepo().getSession().refresh(newTaxonNameForRegistration);
394
                    Registration reg = createNewRegistrationForName(taxonNameUuid);
395
                    // reload workingset into current session
396
                    loadWorkingSet(workingset.getCitationUuid());
397
                    workingset.add(reg);
398
                }
399
                refreshView(true);
400
            } else if(event.getReason().equals(Reason.CANCEL)){
401
                if(newTaxonNameForRegistration != null){
402
                    // clean up
403
                    getTaxonNameStore().deleteBean(newTaxonNameForRegistration, (AbstractView) getView());
404
                }
405
            }
406
            getRepo().commitTransaction(txStatus);
407
            newTaxonNameForRegistration = null;
408
        }
409
    }
410

    
411

    
412
    /**
413
     * Creates a new Registration for an exiting (previously published name).
414
     *
415
     * @param event
416
     * @throws RegistrationValidationException
417
     */
418
    @EventBusListenerMethod
419
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
420

    
421
        if(!event.isStart()){
422
            return;
423
        }
424

    
425
        getView().getAddExistingNameCombobox().commit();
426
        TaxonName typifiedName = getView().getAddExistingNameCombobox().getValue();
427
        if(typifiedName != null){
428
            Registration newRegistrationWithExistingName = createNewRegistrationForName(null);
429
            Reference citation = getRepo().getReferenceService().find(workingset.getCitationUuid());
430
            newRegistrationDTOWithExistingName = new RegistrationDTO(newRegistrationWithExistingName, typifiedName, citation);
431
            workingset.add(newRegistrationDTOWithExistingName);
432
            // tell the view to update the workingset
433
            getView().setWorkingset(workingset);
434
            getView().getAddExistingNameRegistrationButton().setEnabled(false);
435
            getView().getAddExistingNameRegistrationButton().setDescription("You first need to add a type designation to the previously created registration.");
436
        } else {
437
            logger.error("Seletced name is NULL");
438
        }
439

    
440
    }
441

    
442

    
443
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
444
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
445

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

    
450
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
451
            SpecimenTypeDesignationWorkingsetPopupEditor popup = getNavigationManager().showInPopup(SpecimenTypeDesignationWorkingsetPopupEditor.class, getView());
452
            popup.setParentEditorActionContext(event.getContext());
453
            popup.withDeleteButton(true);
454
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
455
            if(event.getSourceComponent() != null){
456
                // propagate readonly state from source component to popup
457
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
458
            }
459
        } else {
460
            NameTypeDesignationPopupEditor popup = getNavigationManager().showInPopup(NameTypeDesignationPopupEditor.class, getView());
461
            popup.setParentEditorActionContext(event.getContext());
462
            popup.withDeleteButton(true);
463
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
464

    
465
            popup.getCitationCombobox().setEnabled(false);
466
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
467

    
468
            if(event.getSourceComponent() != null){
469
                // propagate readonly state from source component to popup
470
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
471
            }
472
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
473
        }
474
    }
475

    
476
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
477
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
478

    
479
        if(event.getSourceComponent() != null){
480
            return;
481
        }
482

    
483
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
484
            SpecimenTypeDesignationWorkingsetPopupEditor popup = getNavigationManager().showInPopup(SpecimenTypeDesignationWorkingsetPopupEditor.class, getView());
485
            popup.setParentEditorActionContext(event.getContext());
486
            TypeDesignationWorkingsetEditorIdSet identifierSet;
487
            UUID typifiedNameUuid;
488
            if(newRegistrationDTOWithExistingName != null){
489
                typifiedNameUuid = newRegistrationDTOWithExistingName.getTypifiedNameRef().getUuid();
490
            } else {
491
                RegistrationDTO registrationDTO = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
492
                EntityReference typifiedNameRef = registrationDTO.getTypifiedNameRef();
493
                if(typifiedNameRef != null){
494
                    // case for registrations without name, in which case the typifiedName is only defined via the typedesignations
495
                    typifiedNameUuid = typifiedNameRef.getUuid();
496
                } else {
497
                    // case of registrations with a name in the nomenclatural act.
498
                    typifiedNameUuid = registrationDTO.getNameRef().getUuid();
499
                }
500
            }
501
            identifierSet = new TypeDesignationWorkingsetEditorIdSet(
502
                    event.getRegistrationUuid(),
503
                    getView().getCitationUuid(),
504
                    typifiedNameUuid
505
                    );
506
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
507
            popup.loadInEditor(identifierSet);
508
            popup.withDeleteButton(true);
509
            if(event.getSourceComponent() != null){
510
                // propagate readonly state from source component to popup
511
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
512
            }
513
        } else {
514
            NameTypeDesignationPopupEditor popup = getNavigationManager().showInPopup(NameTypeDesignationPopupEditor.class, getView());
515
            popup.setParentEditorActionContext(event.getContext());
516
            popup.withDeleteButton(true);
517
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
518
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
519
            popup.setBeanInstantiator(new BeanInstantiator<NameTypeDesignation>() {
520

    
521
                @Override
522
                public NameTypeDesignation createNewBean() {
523

    
524
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
525
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
526
                    nameTypeDesignation.setCitation(newNameTypeDesignationTarget.getCitation());
527
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
528
                    return nameTypeDesignation;
529
                }
530
            });
531
            popup.loadInEditor(null);
532
            popup.getCitationCombobox().setEnabled(false);
533
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
534
            if(event.getSourceComponent() != null){
535
                // propagate readonly state from source component to popup
536
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
537
            }
538
        }
539
    }
540

    
541
    /**
542
     * Performs final actions after a TypeDesignationEditor which has been
543
     * opened to add a TypeDesignation to a Registration object which was
544
     * created for an previously published name. Prior adding a typedesignation,
545
     * the according Registration object is dangling, that has no association to
546
     * any entity denoting an nomenclatural act which has a reference to a
547
     * publication. This means that the registration object is not in the
548
     * working set.
549
     *
550
     *
551
     * @param event
552
     * @throws RegistrationValidationException
553
     */
554
    @EventBusListenerMethod
555
    public void onDoneWithTypeDesignationEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
556
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
557
            if(event.getReason().equals(Reason.SAVE)){
558
                refreshView(true);
559
            } else if(event.getReason().equals(Reason.CANCEL)){
560
                // noting to do
561
            }
562
            newRegistrationDTOWithExistingName = null;
563
        } else if(event.getPopup() instanceof NameTypeDesignationPopupEditor){
564
            if(event.getReason().equals(Reason.SAVE)){
565
                UUID uuid = ((NameTypeDesignationPopupEditor)event.getPopup()).getBean().getUuid();
566

    
567
                Session session = getRepo().getSessionFactory().openSession();
568
                Transaction txstate = session.beginTransaction();
569
                TypeDesignationBase<?> nameTypeDesignation = getRepo().getNameService().loadTypeDesignation(uuid, Arrays.asList(""));
570
                // only load the typeDesignations with the registration so that the typified name can  not be twice in the session
571
                // otherwise multiple representation problems might occur
572
                Registration registration = getRepo().getRegistrationService().load(newNameTypeDesignationTarget.getUuid(), Arrays.asList("typeDesignations"));
573
                registration.getTypeDesignations().add(nameTypeDesignation);
574
                session.merge(registration);
575
                txstate.commit();
576
                session.close();
577

    
578
                refreshView(true);
579
            } else if(event.getReason().equals(Reason.CANCEL)){
580
                // noting to do
581
            }
582
            newNameTypeDesignationTarget = null;
583
        }
584
        // ignore other editors
585
    }
586

    
587

    
588
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
589
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
590

    
591
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
592
            List<String> messages = new ArrayList<>();
593
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
594
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
595
            }
596
            getView().openDetailsPopup("Validation Problems", messages);
597
        }
598
    }
599

    
600
    @EventBusListenerMethod
601
    public void onEntityChangeEvent(EntityChangeEvent event){
602
        if(workingset == null){
603
            return;
604
        }
605
        if(Reference.class.isAssignableFrom(event.getEntityType())){
606
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
607
                refreshView(true);
608
            }
609
        } else
610
        if(Registration.class.isAssignableFrom(event.getEntityType())){
611
            if(workingset.getRegistrations().stream().anyMatch(reg -> reg.getUuid() == event.getEntityUuid())){
612
                refreshView(true);
613
            }
614
        } else
615
        if(TaxonName.class.isAssignableFrom(event.getEntityType())){
616
            if(event.getType().equals(EntityChangeEvent.Type.CREATED)){
617
                // new name! create a blocking registration
618
                Stack<EditorActionContext>context = ((AbstractPopupEditor)event.getSourceView()).getEditorActionContext();
619
                EditorActionContext rootContext = context.get(0);
620
                if(rootContext.getParentView().equals(getView())){
621
                    Registration blockingRegistration = createNewRegistrationForName(event.getEntityUuid());
622
                    TypedEntityReference<Registration> regReference = (TypedEntityReference<Registration>)rootContext.getParentEntity();
623
                    Registration registration = getRepo().getRegistrationService().load(regReference.getUuid(), Arrays.asList("$", "blockedBy"));
624
                    registration.getBlockedBy().add(blockingRegistration);
625
                    getRepo().getRegistrationService().saveOrUpdate(registration);
626
                    logger.debug("Blocking registration created");
627
                } else {
628
                    logger.debug("Nn blocking registration, since a new name for a new registration has been created");
629
                }
630
            }
631
            if(workingset.getRegistrationDTOs().stream().anyMatch(reg ->
632
                reg.getTypifiedNameRef() != null
633
                && reg.getTypifiedNameRef().getUuid().equals(event.getEntityUuid()))){
634
                    refreshView(true);
635
            }
636
        } else
637
        if(TypeDesignationBase.class.isAssignableFrom(event.getEntityType())){
638
            if(workingset.getRegistrationDTOs().stream().anyMatch(
639
                    reg -> reg.getTypeDesignations() != null && reg.getTypeDesignations().stream().anyMatch(
640
                            td -> td.getUuid() == event.getEntityUuid()
641
                            )
642
                        )
643
                    ){
644
                refreshView(true);
645
            }
646
        }
647
    }
648

    
649

    
650
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
651
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
652

    
653
        // FIXME check from own view!!!
654
        if(getView() == null){
655
            return;
656
        }
657

    
658
        UUID registrationUuid = event.getIdentifier();
659

    
660
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
661
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
662

    
663
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
664
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
665
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
666

    
667
            RegistrationMessagesPopup popup = getNavigationManager().showInPopup(RegistrationMessagesPopup.class, getView());
668
            popup.loadMessagesFor(regDto.getUuid());
669

    
670
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
671
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
672
        }
673

    
674

    
675
    }
676

    
677
}
(16-16/23)