Project

General

Profile

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

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

    
99
    private static final long serialVersionUID = 1L;
100

    
101
    @Autowired
102
    private IRegistrationWorkingSetService regWorkingSetService;
103

    
104
    @Autowired
105
    private RegistrationIdentifierMinter minter;
106

    
107
    @Autowired
108
    private IRegistrationMessageService messageService;
109

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

    
117
    private RegistrationWorkingSet workingset;
118

    
119
    private TaxonName newTaxonNameForRegistration = null;
120

    
121
    private RegistrationDTO newRegistrationDTOWithExistingName;
122

    
123
    private RegistrationDTO newNameTypeDesignationTarget;
124

    
125

    
126
    /**
127
     *
128
     */
129
    public RegistrationWorkingsetPresenter() {
130
    }
131

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

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

    
150

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

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

    
178

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

    
193

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

    
200
        super.handleViewEntered();
201

    
202
        loadWorkingSet(getView().getCitationUuid());
203
        getView().setWorkingset(workingset);
204

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

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

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

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

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

    
247
    }
248

    
249

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

    
272

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

    
276
        if(!checkFromOwnView(event)){
277
            return;
278
        }
279

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

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

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

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

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

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

    
318
        if(!checkFromOwnView(event)){
319
            return;
320
        }
321

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

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

    
329
        if(!checkFromOwnView(event)){
330
            return;
331
        }
332

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

    
342
    }
343

    
344

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

    
348
        if(!checkFromOwnView(event)){
349
            return;
350
        }
351

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

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

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

    
413

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

    
423
        if(!event.isStart()){
424
            return;
425
        }
426

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

    
442
    }
443

    
444

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

    
448
        if(!checkFromOwnView(event)){
449
            return;
450
        }
451

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

    
467
            popup.getCitationCombobox().setEnabled(false);
468
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
469

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

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

    
481
        if(event.getSourceComponent() != null){
482
            return;
483
        }
484

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

    
523
                @Override
524
                public NameTypeDesignation createNewBean() {
525

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

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

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

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

    
589

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

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

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

    
651

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

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

    
660
        UUID registrationUuid = event.getIdentifier();
661

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

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

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

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

    
676

    
677
    }
678

    
679
}
(13-13/20)