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",
106
            "name.exCombinationAuthorship",
107
            "name.basionymAuthorship",
108
            "name.exBasionymAuthorship"
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
     * @param doReload TODO
192
     *
193
     */
194
    protected void refreshView(boolean doReload) {
195
        if(workingset == null){
196
            return; // nothing to do
197
        }
198
        if(doReload){
199
            loadWorkingSet(workingset.getCitationUuid());
200
        }
201
        applyWorkingset();
202
    }
203

    
204
    /**
205
     * {@inheritDoc}
206
     */
207
    @Override
208
    public void handleViewEntered() {
209
        super.handleViewEntered();
210
        loadWorkingSet(getView().getCitationUuid());
211
        applyWorkingset();
212

    
213
    }
214

    
215
    private void applyWorkingset(){
216
         getView().setWorkingset(workingset);
217
        // PagingProviders and CacheGenerator for the existingNameCombobox
218
        activateComboboxes();
219
        // update the messages
220
        updateMessages();
221
    }
222

    
223
    /**
224
     *
225
     */
226
    protected void activateComboboxes() {
227
        CdmFilterablePagingProvider<TaxonName, TaxonName> pagingProvider = new CdmFilterablePagingProvider<TaxonName, TaxonName>(
228
                getRepo().getNameService());
229
        CdmTitleCacheCaptionGenerator<TaxonName> titleCacheGenerator = new CdmTitleCacheCaptionGenerator<TaxonName>();
230
        getView().getAddExistingNameCombobox().setCaptionGenerator(titleCacheGenerator);
231
        getView().getAddExistingNameCombobox().loadFrom(pagingProvider, pagingProvider, pagingProvider.getPageSize());
232
    }
233

    
234
    /**
235
     *
236
     */
237
    protected void updateMessages() {
238
        User user = UserHelper.fromSession().user();
239
        for (UUID registrationUuid : getView().getRegistrationItemMap().keySet()) {
240
            Button messageButton = getView().getRegistrationItemMap().get(registrationUuid).regItemButtons.getMessagesButton();
241

    
242
            RegistrationDTO regDto = workingset.getRegistrationDTO(registrationUuid).get();
243
            try {
244
                int messageCount = messageService.countActiveMessagesFor(regDto.registration(), user);
245

    
246
                boolean activeMessages = messageCount > 0;
247
                boolean currentUserIsSubmitter = regDto.getSubmitterUserName() != null && regDto.getSubmitterUserName().equals(UserHelper.fromSession().userName());
248
                boolean currentUserIsCurator = UserHelper.fromSession().userIsRegistrationCurator();
249
                messageButton.setEnabled(false);
250
                if(currentUserIsCurator){
251
                    if(currentUserIsSubmitter){
252
                        messageButton.setDescription("No point sending messages to your self.");
253
                    } else {
254
                        messageButton.setEnabled(true);
255
                        messageButton.setDescription("Open the messages dialog.");
256
                    }
257
                } else {
258
                    messageButton.setDescription("Sorry, only a curator can start a conversation.");
259
                }
260
                if(activeMessages){
261
                    messageButton.setEnabled(true);
262
                    messageButton.addStyleName(EditValoTheme.BUTTON_HIGHLITE);
263
                    String who = currentUserIsSubmitter ? "curator" : "submitter";
264
                    messageButton.setDescription("The " + who + " is looking forward to your reply.");
265

    
266
                }
267
            } catch (ExternalServiceException e) {
268
                messageButton.setComponentError(new SystemError(e.getMessage(), e));
269
            }
270
        }
271
    }
272

    
273

    
274
    /**
275
     * @param referenceID
276
     */
277
    protected void loadWorkingSet(UUID referenceUuid) {
278
        try {
279
            workingset = getWorkingSetService().loadWorkingSetByReferenceUuid(referenceUuid, true);
280
        } catch (RegistrationValidationException error) {
281
            logger.error(error);
282
            Window errorDialog = new Window("Validation Error");
283
            errorDialog.setModal(true);
284
            VerticalLayout subContent = new VerticalLayout();
285
            subContent.setMargin(true);
286
            errorDialog.setContent(subContent);
287
            subContent.addComponent(new Label(error.getMessage()));
288
            UI.getCurrent().addWindow(errorDialog);
289
        }
290
        if(workingset == null || workingset.getCitationUuid() == null){
291
            Reference citation = getRepo().getReferenceService().find(referenceUuid);
292
            workingset = new RegistrationWorkingSet(citation);
293
        }
294
    }
295

    
296

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

    
300
        if(!checkFromOwnView(event)){
301
            return;
302
        }
303

    
304
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
305
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
306
        popup.loadInEditor(null);
307
    }
308

    
309
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
310
    public void onReferenceEditorActionEdit(ReferenceEditorAction event) {
311

    
312
        if(!checkFromOwnView(event)){
313
            return;
314
        }
315
        ReferencePopupEditor popup = openPopupEditor(ReferencePopupEditor.class, event);
316
        popup.withReferenceTypes(RegistrationUIDefaults.PRINTPUB_REFERENCE_TYPES);
317
        popup.withDeleteButton(true);
318
        popup.loadInEditor(event.getEntityUuid());
319
    }
320

    
321
    @EventBusListenerMethod
322
    public void onDoneWithReferencePopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
323
        if(event.getPopup() instanceof ReferencePopupEditor){
324
            if(event.getReason().equals(Reason.SAVE)){
325
                refreshView(true);
326
            }
327
        }
328
    }
329

    
330
    @EventBusListenerMethod
331
    public void onDoneWithSpecimenTypeDesignationWorkingsetPopupEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
332
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
333
            if(event.getReason().equals(Reason.SAVE)){
334
                refreshView(true);
335
            }
336
        }
337
    }
338

    
339
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
340
    public void onRegistrationEditorAction(RegistrationEditorAction event) {
341

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

    
346
        RegistrationPopupEditor popup = openPopupEditor(RegistrationPopupEditor.class, event);
347
        popup.loadInEditor(event.getEntityUuid());
348
    }
349

    
350
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
351
    public void onTaxonNameEditorActionEdit(TaxonNameEditorAction event) {
352

    
353
        if(!checkFromOwnView(event)){
354
            return;
355
        }
356

    
357
        TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
358
        popup.setParentEditorActionContext(event.getContext());
359
        popup.withDeleteButton(true);
360
        configureTaxonNameEditor(popup);
361
        popup.loadInEditor(event.getEntityUuid());
362
        if(event.hasSource() && event.getSource().isReadOnly()){
363
            // avoid resetting readonly to false
364
            popup.setReadOnly(true);
365
        }
366

    
367
    }
368

    
369

    
370
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
371
    public void onTaxonNameEditorActionAdd(TaxonNameEditorAction event) {
372

    
373
        if(!checkFromOwnView(event)){
374
            return;
375
        }
376

    
377
        newTaxonNameForRegistration = TaxonNameFactory.NewNameInstance(RegistrationUIDefaults.NOMENCLATURAL_CODE, Rank.SPECIES());
378
        newTaxonNameForRegistration.setNomenclaturalReference(getRepo().getReferenceService().find(workingset.getCitationUuid()));
379
        EntityChangeEvent nameSaveEvent = getTaxonNameStore().saveBean(newTaxonNameForRegistration, (AbstractView) getView());
380
        newTaxonNameForRegistration = getRepo().getNameService().find(nameSaveEvent.getEntityUuid());
381
        TaxonNamePopupEditor popup = openPopupEditor(TaxonNamePopupEditor.class, event);
382
        popup.setParentEditorActionContext(event.getContext());
383
        popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE,CRUD.DELETE));
384
        popup.withDeleteButton(true);
385
        configureTaxonNameEditor(popup);
386
        popup.loadInEditor(newTaxonNameForRegistration.getUuid());
387
    }
388

    
389
    /**
390
     * TODO consider putting this into a Configurer Bean per UIScope.
391
     * In the configurator bean this methods popup papamerter should be of the type
392
     * AbstractPopupEditor
393
     *
394
     * @param popup
395
     */
396
    protected void configureTaxonNameEditor(TaxonNamePopupEditorView popup) {
397
        popup.enableMode(TaxonNamePopupEditorMode.AUTOFILL_AUTHORSHIP_DATA);
398
        popup.enableMode(TaxonNamePopupEditorMode.NOMENCLATURALREFERENCE_SECTION_EDITING_ONLY);
399
        popup.enableMode(TaxonNamePopupEditorMode.VALIDATE_AGAINST_HIGHER_NAME_PART);
400
        // popup.enableMode(TaxonNamePopupEditorMode.REQUIRE_NOMENCLATURALREFERENCE);
401
    }
402

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

    
439

    
440
    /**
441
     * Creates a new Registration for an exiting (previously published name).
442
     *
443
     * @param event
444
     * @throws RegistrationValidationException
445
     */
446
    @EventBusListenerMethod
447
    public void onRegistrationWorkflowEventActionStart(RegistrationWorkingsetAction event) throws RegistrationValidationException {
448

    
449
        if(!event.isStart()){
450
            return;
451
        }
452

    
453
        getView().getAddExistingNameCombobox().commit();
454
        TaxonName typifiedName = getView().getAddExistingNameCombobox().getValue();
455
        if(typifiedName != null){
456
            Registration newRegistrationWithExistingName = createNewRegistrationForName(null);
457
            Reference citation = getRepo().getReferenceService().find(workingset.getCitationUuid());
458
            newRegistrationDTOWithExistingName = new RegistrationDTO(newRegistrationWithExistingName, typifiedName, citation);
459
            workingset.add(newRegistrationDTOWithExistingName);
460
            // tell the view to update the workingset
461
            getView().setWorkingset(workingset);
462
            getView().getAddExistingNameRegistrationButton().setEnabled(false);
463
            getView().getAddExistingNameRegistrationButton().setDescription("You first need to add a type designation to the previously created registration.");
464
        } else {
465
            logger.error("Seletced name is NULL");
466
        }
467

    
468
    }
469

    
470

    
471
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Edit.class)
472
    public void onTypeDesignationsEditorActionEdit(TypeDesignationWorkingsetEditorAction event) {
473

    
474
        if(!checkFromOwnView(event)){
475
            return;
476
        }
477

    
478
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET ){
479
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
480
            popup.setParentEditorActionContext(event.getContext());
481
            popup.withDeleteButton(true);
482
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
483
            if(event.hasSource()){
484
                // propagate readonly state from source button to popup
485
                popup.setReadOnly(event.getSource().isReadOnly());
486
            }
487
        } else {
488
            NameTypeDesignationPopupEditor popup = openPopupEditor(NameTypeDesignationPopupEditor.class, event);
489
            popup.setParentEditorActionContext(event.getContext());
490
            popup.withDeleteButton(true);
491
            popup.loadInEditor(new TypeDesignationWorkingsetEditorIdSet(event.getRegistrationUuid(), event.getBaseEntityRef()));
492

    
493
            popup.getCitationCombobox().setEnabled(false);
494
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
495

    
496
            if(event.hasSource()){
497
                // propagate readonly state from source button to popup
498
                popup.setReadOnly(event.getSource().isReadOnly());
499
            }
500
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
501
        }
502
    }
503

    
504
    @EventBusListenerMethod(filter = EditorActionTypeFilter.Add.class)
505
    public void onTypeDesignationWorkingsetAdd(TypeDesignationWorkingsetEditorAction event) {
506

    
507
        if(!event.hasSource()){
508
            return;
509
        }
510

    
511
        if(event.getWorkingSetType() == TypeDesignationWorkingSetType.SPECIMEN_TYPE_DESIGNATION_WORKINGSET){
512
            SpecimenTypeDesignationWorkingsetPopupEditor popup = openPopupEditor(SpecimenTypeDesignationWorkingsetPopupEditor.class, event);
513
            popup.setParentEditorActionContext(event.getContext());
514
            TypeDesignationWorkingsetEditorIdSet identifierSet;
515
            UUID typifiedNameUuid;
516
            if(newRegistrationDTOWithExistingName != null){
517
                typifiedNameUuid = newRegistrationDTOWithExistingName.getTypifiedNameRef().getUuid();
518
            } else {
519
                RegistrationDTO registrationDTO = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
520
                EntityReference typifiedNameRef = registrationDTO.getTypifiedNameRef();
521
                if(typifiedNameRef != null){
522
                    // case for registrations without name, in which case the typifiedName is only defined via the typedesignations
523
                    typifiedNameUuid = typifiedNameRef.getUuid();
524
                } else {
525
                    // case of registrations with a name in the nomenclatural act.
526
                    typifiedNameUuid = registrationDTO.getNameRef().getUuid();
527
                }
528
            }
529
            identifierSet = new TypeDesignationWorkingsetEditorIdSet(
530
                    event.getRegistrationUuid(),
531
                    getView().getCitationUuid(),
532
                    typifiedNameUuid
533
                    );
534
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
535
            popup.loadInEditor(identifierSet);
536
            popup.withDeleteButton(true);
537
            if(event.hasSource()){
538
                // propagate readonly state from source component to popup
539
                popup.setReadOnly(event.getSource().isReadOnly());
540
            }
541
        } else {
542
            NameTypeDesignationPopupEditor popup = openPopupEditor(NameTypeDesignationPopupEditor.class, event);
543
            popup.setParentEditorActionContext(event.getContext());
544
            popup.withDeleteButton(true);
545
            popup.grantToCurrentUser(EnumSet.of(CRUD.UPDATE, CRUD.DELETE));
546
            newNameTypeDesignationTarget = workingset.getRegistrationDTO(event.getRegistrationUuid()).get();
547
            popup.setBeanInstantiator(new BeanInstantiator<NameTypeDesignation>() {
548

    
549
                @Override
550
                public NameTypeDesignation createNewBean() {
551

    
552
                    TaxonName typifiedName = getRepo().getNameService().load(event.getTypifiedNameUuid(), Arrays.asList(new String[]{"typeDesignations", "homotypicalGroup"}));
553
                    NameTypeDesignation nameTypeDesignation  = NameTypeDesignation.NewInstance();
554
                    nameTypeDesignation.setCitation(newNameTypeDesignationTarget.getCitation());
555
                    nameTypeDesignation.getTypifiedNames().add(typifiedName);
556
                    return nameTypeDesignation;
557
                }
558
            });
559
            popup.loadInEditor(null);
560
            popup.getCitationCombobox().setEnabled(false);
561
            popup.getTypifiedNamesComboboxSelect().setEnabled(false);
562
            if(event.hasSource()){
563
                // propagate readonly state from source component to popup
564
                popup.setReadOnly(event.getSource().isReadOnly());
565
            }
566
        }
567
    }
568

    
569
    /**
570
     * Performs final actions after a TypeDesignationEditor which has been
571
     * opened to add a TypeDesignation to a Registration object which was
572
     * created for an previously published name. Prior adding a typedesignation,
573
     * the according Registration object is dangling, that has no association to
574
     * any entity denoting an nomenclatural act which has a reference to a
575
     * publication. This means that the registration object is not in the
576
     * working set.
577
     *
578
     *
579
     * @param event
580
     * @throws RegistrationValidationException
581
     */
582
    @EventBusListenerMethod
583
    public void onDoneWithTypeDesignationEditor(DoneWithPopupEvent event) throws RegistrationValidationException{
584
        if(event.getPopup() instanceof SpecimenTypeDesignationWorkingsetPopupEditor){
585
            if(event.getReason().equals(Reason.SAVE)){
586
                refreshView(true);
587
            } else if(event.getReason().equals(Reason.CANCEL)){
588
                // noting to do
589
            }
590
            newRegistrationDTOWithExistingName = null;
591
        } else if(event.getPopup() instanceof NameTypeDesignationPopupEditor){
592
            if(event.getReason().equals(Reason.SAVE)){
593
                UUID uuid = ((NameTypeDesignationPopupEditor)event.getPopup()).getBean().getUuid();
594

    
595
                Session session = getRepo().getSessionFactory().openSession();
596
                Transaction txstate = session.beginTransaction();
597
                TypeDesignationBase<?> nameTypeDesignation = getRepo().getNameService().loadTypeDesignation(uuid, Arrays.asList(""));
598
                // only load the typeDesignations with the registration so that the typified name can  not be twice in the session
599
                // otherwise multiple representation problems might occur
600
                Registration registration = getRepo().getRegistrationService().load(newNameTypeDesignationTarget.getUuid(), Arrays.asList("typeDesignations"));
601
                registration.getTypeDesignations().add(nameTypeDesignation);
602
                session.merge(registration);
603
                txstate.commit();
604
                session.close();
605

    
606
                refreshView(true);
607
            } else if(event.getReason().equals(Reason.CANCEL)){
608
                // noting to do
609
            }
610
            newNameTypeDesignationTarget = null;
611
        }
612
        // ignore other editors
613
    }
614

    
615

    
616
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationWorkingSet.class)
617
    public void onShowDetailsEventForRegistrationWorkingSet(ShowDetailsEvent<RegistrationWorkingSet,?> event) {
618

    
619
        if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
620
            List<String> messages = new ArrayList<>();
621
            for(RegistrationDTO dto : workingset.getRegistrationDTOs()){
622
                dto.getValidationProblems().forEach(m -> messages.add(dto.getSummary() + ": " + m));
623
            }
624
            getView().openDetailsPopup("Validation Problems", messages);
625
        }
626
    }
627

    
628
    @EventBusListenerMethod
629
    public void onEntityChangeEvent(EntityChangeEvent event){
630

    
631
        if(workingset == null){
632
            return;
633
        }
634
        if(Reference.class.isAssignableFrom(event.getEntityType())){
635
            if(workingset.getCitationUuid().equals(event.getEntityUuid())){
636
                refreshView(true);
637
            }
638
        } else
639
        if(Registration.class.isAssignableFrom(event.getEntityType())){
640
            if(workingset.getRegistrations().stream().anyMatch(reg -> reg.getUuid() == event.getEntityUuid())){
641
                refreshView(true);
642
            }
643
        } else
644
        if(TaxonName.class.isAssignableFrom(event.getEntityType()) && isFromOwnView(event)){
645
            if(event.getType().equals(EntityChangeEvent.Type.CREATED)){
646
                // new name! create a blocking registration
647
                Stack<EditorActionContext>context = ((AbstractPopupEditor)event.getSourceView()).getEditorActionContext();
648
                EditorActionContext rootContext = context.get(0);
649
                if(rootContext.getParentView().equals(getView())){
650
                    Registration blockingRegistration = createNewRegistrationForName(event.getEntityUuid());
651
                    TypedEntityReference<Registration> regReference = (TypedEntityReference<Registration>)rootContext.getParentEntity();
652
                    Registration registration = getRepo().getRegistrationService().load(regReference.getUuid(), REGISTRATION_INIT_STRATEGY);
653
                    registration.getBlockedBy().add(blockingRegistration);
654
                    getRepo().getRegistrationService().saveOrUpdate(registration);
655
                    logger.debug("Blocking registration created");
656
                } else {
657
                    logger.debug("Non blocking registration, since a new name for a new registration has been created");
658
                }
659
            }
660
            if(workingset.getRegistrationDTOs().stream().anyMatch(reg ->
661
                reg.getTypifiedNameRef() != null
662
                && reg.getTypifiedNameRef().getUuid().equals(event.getEntityUuid()))){
663
                    refreshView(true);
664
            }
665
        } else
666
        if(TypeDesignationBase.class.isAssignableFrom(event.getEntityType())){
667
            if(workingset.getRegistrationDTOs().stream().anyMatch(
668
                    reg -> reg.getTypeDesignations() != null && reg.getTypeDesignations().stream().anyMatch(
669
                            td -> td.getUuid() == event.getEntityUuid()
670
                            )
671
                        )
672
                    ){
673
                refreshView(true);
674
            }
675
        }
676
    }
677

    
678

    
679
    @EventBusListenerMethod(filter = ShowDetailsEventEntityTypeFilter.RegistrationDTO.class)
680
    public void onShowDetailsEventForRegistrationDTO(ShowDetailsEvent<RegistrationDTO, UUID> event) {
681

    
682
        // FIXME check from own view!!!
683
        if(getView() == null){
684
            return;
685
        }
686

    
687
        UUID registrationUuid = event.getIdentifier();
688

    
689
        RegistrationDTO regDto = getWorkingSetService().loadDtoByUuid(registrationUuid);
690
        if(event.getProperty().equals(RegistrationItem.BLOCKED_BY)){
691

    
692
            Set<RegistrationDTO> blockingRegs = getWorkingSetService().loadBlockingRegistrations(registrationUuid);
693
            getView().setBlockingRegistrations(registrationUuid, blockingRegs);
694
        } else if(event.getProperty().equals(RegistrationItem.MESSAGES)){
695

    
696
            RegistrationMessagesPopup popup = openPopupEditor(RegistrationMessagesPopup.class, null);
697
            popup.loadMessagesFor(regDto.getUuid());
698

    
699
        } else if(event.getProperty().equals(RegistrationItem.VALIDATION_PROBLEMS)){
700
            getView().openDetailsPopup("Validation Problems", regDto.getValidationProblems());
701
        }
702

    
703

    
704
    }
705

    
706
}
(13-13/20)