Project

General

Profile

Download (30.8 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.idminter.RegistrationIdentifierMinter;
43
import eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager.TypeDesignationWorkingSetType;
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.permission.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
    /**
100
     *
101
     */
102
    private static final List<String> REGISTRATION_INIT_STRATEGY = Arrays.asList(
103
            "$",
104
            "blockedBy",
105
            "name.combinationAuthorship.teamMembers",
106
            "name.exCombinationAuthorship.teamMembers",
107
            "name.basionymAuthorship.teamMembers",
108
            "name.exBasionymAuthorship.teamMembers"
109
            );
110

    
111
    private static final long serialVersionUID = 1L;
112

    
113
    @Autowired
114
    private IRegistrationWorkingSetService regWorkingSetService;
115

    
116
    @Autowired
117
    private RegistrationIdentifierMinter minter;
118

    
119
    @Autowired
120
    private IRegistrationMessageService messageService;
121

    
122
    /**
123
     * @return the regWorkingSetService
124
     */
125
    public IRegistrationWorkingSetService getWorkingSetService() {
126
        return regWorkingSetService;
127
    }
128

    
129
    private RegistrationWorkingSet workingset;
130

    
131
    private TaxonName newTaxonNameForRegistration = null;
132

    
133
    private RegistrationDTO newRegistrationDTOWithExistingName;
134

    
135
    private RegistrationDTO newNameTypeDesignationTarget;
136

    
137

    
138
    /**
139
     *
140
     */
141
    public RegistrationWorkingsetPresenter() {
142
    }
143

    
144
    /**
145
     * Always create a new Store
146
     *
147
     * @return
148
     */
149
    protected CdmStore<Registration, IRegistrationService> getRegistrationStore(){
150
        return new CdmStore<Registration, IRegistrationService>(getRepo(), getRepo().getRegistrationService());
151
    }
152

    
153
    /**
154
     * Always create a new Store
155
     *
156
     * @return
157
     */
158
    protected CdmStore<TaxonName, INameService> getTaxonNameStore(){
159
        return new  CdmStore<TaxonName, INameService>(getRepo(), getRepo().getNameService());
160
    }
161

    
162

    
163
    /**
164
     * @param taxonNameId
165
     * @return
166
     */
167
    protected Registration createNewRegistrationForName(UUID taxonNameUuid) {
168
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
        // move into RegistrationWorkflowStateMachine
170
        TransactionStatus txStatus = getRepo().startTransaction();
171

    
172
        Identifier<String> identifiers = minter.mint();
173
        if(identifiers.getIdentifier() == null){
174
            throw new RuntimeException("RegistrationIdentifierMinter configuration incomplete.");
175
        }
176
        Registration reg = Registration.NewInstance(
177
                identifiers.getIdentifier(),
178
                identifiers.getLocalId(),
179
                taxonNameUuid != null ? getRepo().getNameService().find(taxonNameUuid) : null,
180
                null);
181
        Authentication authentication = currentSecurityContext().getAuthentication();
182
        reg.setSubmitter((User)authentication.getPrincipal());
183
        EntityChangeEvent event = getRegistrationStore().saveBean(reg, (AbstractView) getView());
184
        UserHelper.fromSession().createAuthorityForCurrentUser(Registration.class, event.getEntityUuid(), Operation.UPDATE, RegistrationStatus.PREPARATION.name());
185
        getRepo().commitTransaction(txStatus);
186
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
187
        return getRepo().getRegistrationService().load(event.getEntityUuid(), Arrays.asList(new String []{"blockedBy"}));
188
    }
189

    
190

    
191
    /**
192
     * @param doReload TODO
193
     *
194
     */
195
    protected void refreshView(boolean doReload) {
196
        if(workingset == null){
197
            return; // nothing to do
198
        }
199
        if(doReload){
200
            loadWorkingSet(workingset.getCitationUuid());
201
        }
202
        getView().setWorkingset(workingset);
203
    }
204

    
205

    
206
    /**
207
     * {@inheritDoc}
208
     */
209
    @Override
210
    public void handleViewEntered() {
211

    
212
        super.handleViewEntered();
213

    
214
        loadWorkingSet(getView().getCitationUuid());
215
        getView().setWorkingset(workingset);
216

    
217
        // PagingProviders and CacheGenerator for the existingNameCombobox
218
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
219
                getRepo().getNameService());
220
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
221
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
222
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
223

    
224
        // update the messages
225
        User user = UserHelper.fromSession().user();
226
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
227
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
228

    
229
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
230
            try {
231
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
232

    
233
                boolean activeMessages = messageCount > 0;
234
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName() != null && regDto.getSubmitterUserName().equals(UserHelper.fromSession().userName());
235
                boolean currentUserIsCurator = UserHelper.fromSession().userIsRegistrationCurator();
236
                messageButton.setEnabled(false);
237
                if(currentUserIsCurator){
238
                    if(currentUserIsSubmitter){
239
                        messageButton.setDescription("No point sending messages to your self.");
240
                    } else {
241
                        messageButton.setEnabled(true);
242
                        messageButton.setDescription("Open the messages dialog.");
243
                    }
244
                } else {
245
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
246
                }
247
                if(activeMessages){
248
                    messageButton.setEnabled(true);
249
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
250
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
251
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
252

    
253
                }
254
            } catch (ExternalServiceException e) {
255
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
256
            }
257
        }
258

    
259
    }
260

    
261

    
262
    /**
263
     * @param referenceID
264
     */
265
    protected void loadWorkingSet(UUID referenceUuid) {
266
        try {
267
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid);
268
        } catch (RegistrationValidationException error) {
269
            logger.error(error);
270
            Window errorDialog = new Window("Validation Error");
271
            errorDialog.setModal(true);
272
            VerticalLayout subContent = new VerticalLayout();
273
            subContent.setMargin(true);
274
            errorDialog.setContent(subContent);
275
            subContent.addComponent(new Label(error.getMessage()));
276
            UI.getCurrent().addWindow(errorDialog);
277
        }
278
        if(workingset == null || workingset.getCitationUuid() == null){
279
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
280
            workingset = new RegistrationWorkingSet(citation);
281
        }
282
    }
283

    
284

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

    
288
        if(!checkFromOwnView(event)){
289
            return;
290
        }
291

    
292
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView());
293
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
294
        popup.loadInEditor(null);
295
    }
296

    
297
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
298
    public void onReferenceEditorActionEdit(ReferenceEditorAction event) {
299

    
300
        if(!checkFromOwnView(event)){
301
            return;
302
        }
303
        ReferencePopupEditor popup = getNavigationManager().showInPopup(ReferencePopupEditor.class, getView());
304
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
305
        popup.withDeleteButton(true);
306
        popup.loadInEditor(event.getEntityUuid());
307
    }
308

    
309
    @EventBusListenerMethod
310
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
311
        if(event.getPopup() instanceof ReferencePopupEditor){
312
            if(event.getReason().equals(Reason.SAVE)){
313
                refreshView(true);
314
            }
315
        }
316
    }
317

    
318
    @EventBusListenerMethod
319
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
320
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
321
            if(event.getReason().equals(Reason.SAVE)){
322
                refreshView(true);
323
            }
324
        }
325
    }
326

    
327
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
328
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
329

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

    
334
        RegistrationPopupEditor popup = getNavigationManager().showInPopup(RegistrationPopupEditor.class, getView());
335
        popup.loadInEditor(event.getEntityUuid());
336
    }
337

    
338
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
339
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
340

    
341
        if(!checkFromOwnView(event)){
342
            return;
343
        }
344

    
345
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView());
346
        popup.setParentEditorActionContext(event.getContext());
347
        popup.withDeleteButton(true);
348
        configureTaxonNameEditor(popup);
349
        popup.loadInEditor(event.getEntityUuid());
350
        if(event.getSourceComponent() != null){
351
            popup.setReadOnly(event.getSourceComponent().isReadOnly());
352
        }
353

    
354
    }
355

    
356

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

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

    
364
        newTaxonNameForRegistration = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
365
        newTaxonNameForRegistration.setNomenclaturalReference(getRepo().getReferenceService().find(workingset.getCitationUuid()));
366
        EntityChangeEvent nameSaveEvent = getTaxonNameStore().saveBean(newTaxonNameForRegistration, (AbstractView) getView());
367
        newTaxonNameForRegistration = getRepo().getNameService().find(nameSaveEvent.getEntityUuid());
368
        TaxonNamePopupEditor popup = getNavigationManager().showInPopup(TaxonNamePopupEditor.class, getView());
369
        popup.setParentEditorActionContext(event.getContext());
370
        popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
371
        popup.withDeleteButton(true);
372
        configureTaxonNameEditor(popup);
373
        popup.loadInEditor(newTaxonNameForRegistration.getUuid());
374
    }
375

    
376
    /**
377
     * TODO consider putting this into a Configurer Bean per UIScope.
378
     * In the configurator bean this methods popup papamerter should be of the type
379
     * AbstractPopupEditor
380
     *
381
     * @param popup
382
     */
383
    protected void configureTaxonNameEditor(TaxonNamePopupEditorView popup) {
384
        popup.enableMode(TaxonNamePopupEditorMode.AUTOFILL_AUTHORSHIP_DATA);
385
        popup.enableMode(TaxonNamePopupEditorMode.NOMENCLATURALREFERENCE_SECTION_EDITING_ONLY);
386
        // popup.enableMode(TaxonNamePopupEditorMode.REQUIRE_NOMENCLATURALREFERENCE);
387
    }
388

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

    
425

    
426
    /**
427
     * Creates a new Registration for an exiting (previously published name).
428
     *
429
     * @param event
430
     * @throws RegistrationValidationException
431
     */
432
    @EventBusListenerMethod
433
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
434

    
435
        if(!event.isStart()){
436
            return;
437
        }
438

    
439
        getView().getAddExistingNameCombobox().commit();
440
        TaxonName typifiedName = getView().getAddExistingNameCombobox().getValue();
441
        if(typifiedName != null){
442
            Registration newRegistrationWithExistingName = createNewRegistrationForName(null);
443
            Reference citation = getRepo().getReferenceService().find(workingset.getCitationUuid());
444
            newRegistrationDTOWithExistingName = new RegistrationDTO(newRegistrationWithExistingName, typifiedName, citation);
445
            workingset.add(newRegistrationDTOWithExistingName);
446
            // tell the view to update the workingset
447
            getView().setWorkingset(workingset);
448
            getView().getAddExistingNameRegistrationButton().setEnabled(false);
449
            getView().getAddExistingNameRegistrationButton().setDescription("You first need to add a type designation to the previously created registration.");
450
        } else {
451
            logger.error("Seletced name is NULL");
452
        }
453

    
454
    }
455

    
456

    
457
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
458
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
459

    
460
        if(!checkFromOwnView(event)){
461
            return;
462
        }
463

    
464
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
465
            SpecimenTypeDesignationWorkingsetPopupEditor popup = getNavigationManager().showInPopup(SpecimenTypeDesignationWorkingsetPopupEditor.class, getView());
466
            popup.setParentEditorActionContext(event.getContext());
467
            popup.withDeleteButton(true);
468
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
469
            if(event.getSourceComponent() != null){
470
                // propagate readonly state from source component to popup
471
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
472
            }
473
        } else {
474
            NameTypeDesignationPopupEditor popup = getNavigationManager().showInPopup(NameTypeDesignationPopupEditor.class, getView());
475
            popup.setParentEditorActionContext(event.getContext());
476
            popup.withDeleteButton(true);
477
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
478

    
479
            popup.getCitationCombobox().setEnabled(false);
480
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
481

    
482
            if(event.getSourceComponent() != null){
483
                // propagate readonly state from source component to popup
484
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
485
            }
486
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
487
        }
488
    }
489

    
490
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
491
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
492

    
493
        if(event.getSourceComponent() != null){
494
            return;
495
        }
496

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

    
535
                @Override
536
                public NameTypeDesignation createNewBean() {
537

    
538
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
539
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
540
                    nameTypeDesignation.setCitation(newNameTypeDesignationTarget.getCitation());
541
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
542
                    return nameTypeDesignation;
543
                }
544
            });
545
            popup.loadInEditor(null);
546
            popup.getCitationCombobox().setEnabled(false);
547
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
548
            if(event.getSourceComponent() != null){
549
                // propagate readonly state from source component to popup
550
                popup.setReadOnly(event.getSourceComponent().isReadOnly());
551
            }
552
        }
553
    }
554

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

    
581
                Session session = getRepo().getSessionFactory().openSession();
582
                Transaction txstate = session.beginTransaction();
583
                TypeDesignationBase<?> nameTypeDesignation = getRepo().getNameService().loadTypeDesignation(uuid, Arrays.asList(""));
584
                // only load the typeDesignations with the registration so that the typified name can  not be twice in the session
585
                // otherwise multiple representation problems might occur
586
                Registration registration = getRepo().getRegistrationService().load(newNameTypeDesignationTarget.getUuid(), Arrays.asList("typeDesignations"));
587
                registration.getTypeDesignations().add(nameTypeDesignation);
588
                session.merge(registration);
589
                txstate.commit();
590
                session.close();
591

    
592
                refreshView(true);
593
            } else if(event.getReason().equals(Reason.CANCEL)){
594
                // noting to do
595
            }
596
            newNameTypeDesignationTarget = null;
597
        }
598
        // ignore other editors
599
    }
600

    
601

    
602
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
603
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
604

    
605
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
606
            List<String> messages = new ArrayList<>();
607
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
608
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
609
            }
610
            getView().openDetailsPopup("Validation Problems", messages);
611
        }
612
    }
613

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

    
663

    
664
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
665
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
666

    
667
        // FIXME check from own view!!!
668
        if(getView() == null){
669
            return;
670
        }
671

    
672
        UUID registrationUuid = event.getIdentifier();
673

    
674
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
675
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
676

    
677
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
678
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
679
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
680

    
681
            RegistrationMessagesPopup popup = getNavigationManager().showInPopup(RegistrationMessagesPopup.class, getView());
682
            popup.loadMessagesFor(regDto.getUuid());
683

    
684
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
685
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
686
        }
687

    
688

    
689
    }
690

    
691
}
(13-13/20)