001// --------------------------------------------------------------------------------
002// Copyright 2002-2026 Echo Three, LLC
003//
004// Licensed under the Apache License, Version 2.0 (the "License");
005// you may not use this file except in compliance with the License.
006// You may obtain a copy of the License at
007//
008//     http://www.apache.org/licenses/LICENSE-2.0
009//
010// Unless required by applicable law or agreed to in writing, software
011// distributed under the License is distributed on an "AS IS" BASIS,
012// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013// See the License for the specific language governing permissions and
014// limitations under the License.
015// --------------------------------------------------------------------------------
016
017package com.echothree.control.user.letter.server.command;
018
019import com.echothree.control.user.letter.common.edit.LetterEdit;
020import com.echothree.control.user.letter.common.edit.LetterEditFactory;
021import com.echothree.control.user.letter.common.form.EditLetterForm;
022import com.echothree.control.user.letter.common.result.LetterResultFactory;
023import com.echothree.control.user.letter.common.spec.LetterSpec;
024import com.echothree.model.control.chain.server.control.ChainControl;
025import com.echothree.model.control.contactlist.server.control.ContactListControl;
026import com.echothree.model.control.letter.server.control.LetterControl;
027import com.echothree.model.control.party.common.PartyTypes;
028import com.echothree.model.control.security.common.SecurityRoleGroups;
029import com.echothree.model.control.security.common.SecurityRoles;
030import com.echothree.model.data.user.common.pk.UserVisitPK;
031import com.echothree.util.common.message.ExecutionErrors;
032import com.echothree.util.common.validation.FieldDefinition;
033import com.echothree.util.common.validation.FieldType;
034import com.echothree.util.common.command.BaseResult;
035import com.echothree.util.common.command.EditMode;
036import com.echothree.util.server.control.BaseEditCommand;
037import com.echothree.util.server.control.CommandSecurityDefinition;
038import com.echothree.util.server.control.PartyTypeDefinition;
039import com.echothree.util.server.control.SecurityRoleDefinition;
040import com.echothree.util.server.persistence.Session;
041import java.util.List;
042import javax.enterprise.context.Dependent;
043
044@Dependent
045public class EditLetterCommand
046        extends BaseEditCommand<LetterSpec, LetterEdit> {
047    
048    private final static CommandSecurityDefinition COMMAND_SECURITY_DEFINITION;
049    private final static List<FieldDefinition> SPEC_FIELD_DEFINITIONS;
050    private final static List<FieldDefinition> EDIT_FIELD_DEFINITIONS;
051    
052    static {
053        COMMAND_SECURITY_DEFINITION = new CommandSecurityDefinition(List.of(
054                new PartyTypeDefinition(PartyTypes.UTILITY.name(), null),
055                new PartyTypeDefinition(PartyTypes.EMPLOYEE.name(), List.of(
056                    new SecurityRoleDefinition(SecurityRoleGroups.Letter.name(), SecurityRoles.Edit.name())
057                    ))
058                ));
059        
060        SPEC_FIELD_DEFINITIONS = List.of(
061                new FieldDefinition("ChainKindName", FieldType.ENTITY_NAME, true, null, null),
062                new FieldDefinition("ChainTypeName", FieldType.ENTITY_NAME, true, null, null),
063                new FieldDefinition("LetterName", FieldType.ENTITY_NAME, true, null, null)
064                );
065        
066        EDIT_FIELD_DEFINITIONS = List.of(
067                new FieldDefinition("LetterName", FieldType.ENTITY_NAME, true, null, null),
068                new FieldDefinition("LetterSourceName", FieldType.ENTITY_NAME, true, null, null),
069                new FieldDefinition("ContactListName", FieldType.ENTITY_NAME, false, null, null),
070                new FieldDefinition("IsDefault", FieldType.BOOLEAN, true, null, null),
071                new FieldDefinition("SortOrder", FieldType.SIGNED_INTEGER, true, null, null),
072                new FieldDefinition("Description", FieldType.STRING, false, 1L, 132L)
073                );
074    }
075    
076    /** Creates a new instance of EditLetterCommand */
077    public EditLetterCommand() {
078        super(COMMAND_SECURITY_DEFINITION, SPEC_FIELD_DEFINITIONS, EDIT_FIELD_DEFINITIONS);
079    }
080    
081    @Override
082    protected BaseResult execute() {
083        var chainControl = Session.getModelController(ChainControl.class);
084        var result = LetterResultFactory.getEditLetterResult();
085        var chainKindName = spec.getChainKindName();
086        var chainKind = chainControl.getChainKindByName(chainKindName);
087        
088        if(chainKind != null) {
089            var chainTypeName = spec.getChainTypeName();
090            var chainType = chainControl.getChainTypeByName(chainKind, chainTypeName);
091            
092            if(chainType != null) {
093                var letterControl = Session.getModelController(LetterControl.class);
094                
095                if(editMode.equals(EditMode.LOCK)) {
096                    var letterName = spec.getLetterName();
097                    var letter = letterControl.getLetterByName(chainType, letterName);
098                    
099                    if(letter != null) {
100                        result.setLetter(letterControl.getLetterTransfer(getUserVisit(), letter));
101                        
102                        if(lockEntity(letter)) {
103                            var letterDescription = letterControl.getLetterDescription(letter, getPreferredLanguage());
104                            var edit = LetterEditFactory.getLetterEdit();
105                            var letterDetail = letter.getLastDetail();
106                            var contactList = letterDetail.getContactList();
107                            
108                            result.setEdit(edit);
109                            edit.setLetterName(letterDetail.getLetterName());
110                            edit.setLetterSourceName(letterDetail.getLetterSource().getLastDetail().getLetterSourceName());
111                            edit.setContactListName(contactList == null? null: contactList.getLastDetail().getContactListName());
112                            edit.setIsDefault(letterDetail.getIsDefault().toString());
113                            edit.setSortOrder(letterDetail.getSortOrder().toString());
114                            
115                            if(letterDescription != null)
116                                edit.setDescription(letterDescription.getDescription());
117                        } else {
118                            addExecutionError(ExecutionErrors.EntityLockFailed.name());
119                        }
120                        
121                        result.setEntityLock(getEntityLockTransfer(letter));
122                    } else {
123                        addExecutionError(ExecutionErrors.UnknownLetterName.name(), letterName);
124                    }
125                } else if(editMode.equals(EditMode.UPDATE)) {
126                    var letterName = spec.getLetterName();
127                    var letter = letterControl.getLetterByNameForUpdate(chainType, letterName);
128                    
129                    if(letter != null) {
130                        letterName = edit.getLetterName();
131                        var duplicateLetter = letterControl.getLetterByName(chainType, letterName);
132                        
133                        if(duplicateLetter == null || letter.equals(duplicateLetter)) {
134                            var letterSourceName = edit.getLetterSourceName();
135                            var letterSource = letterControl.getLetterSourceByName(letterSourceName);
136                            
137                            if(letterSource != null) {
138                                var contactListControl = Session.getModelController(ContactListControl.class);
139                                var contactListName = edit.getContactListName();
140                                var contactList = contactListName == null? null: contactListControl.getContactListByName(contactListName);
141                                
142                                if(contactListName == null || contactList != null) {
143                                    if(lockEntityForUpdate(letter)) {
144                                        try {
145                                            var partyPK = getPartyPK();
146                                            var letterDetailValue = letterControl.getLetterDetailValueForUpdate(letter);
147                                            var letterDescription = letterControl.getLetterDescriptionForUpdate(letter, getPreferredLanguage());
148                                            var description = edit.getDescription();
149                                            
150                                            letterDetailValue.setLetterName(edit.getLetterName());
151                                            letterDetailValue.setLetterSourcePK(letterSource.getPrimaryKey());
152                                            letterDetailValue.setContactListPK(contactList == null? null: contactList.getPrimaryKey());
153                                            letterDetailValue.setIsDefault(Boolean.valueOf(edit.getIsDefault()));
154                                            letterDetailValue.setSortOrder(Integer.valueOf(edit.getSortOrder()));
155                                            
156                                            letterControl.updateLetterFromValue(letterDetailValue, partyPK);
157                                            
158                                            if(letterDescription == null && description != null) {
159                                                letterControl.createLetterDescription(letter, getPreferredLanguage(), description, partyPK);
160                                            } else if(letterDescription != null && description == null) {
161                                                letterControl.deleteLetterDescription(letterDescription, partyPK);
162                                            } else if(letterDescription != null && description != null) {
163                                                var letterDescriptionValue = letterControl.getLetterDescriptionValue(letterDescription);
164                                                
165                                                letterDescriptionValue.setDescription(description);
166                                                letterControl.updateLetterDescriptionFromValue(letterDescriptionValue, partyPK);
167                                            }
168                                        } finally {
169                                            unlockEntity(letter);
170                                        }
171                                    } else {
172                                        addExecutionError(ExecutionErrors.EntityLockStale.name());
173                                    }
174                                } else {
175                                    addExecutionError(ExecutionErrors.UnknownContactListName.name(), contactListName);
176                                }
177                            } else {
178                                addExecutionError(ExecutionErrors.UnknownLetterSourceName.name(), letterSourceName);
179                            }
180                        } else {
181                            addExecutionError(ExecutionErrors.DuplicateLetterName.name(), letterName);
182                        }
183                    } else {
184                        addExecutionError(ExecutionErrors.UnknownLetterName.name(), letterName);
185                    }
186                    
187                    if(hasExecutionErrors()) {
188                        result.setLetter(letterControl.getLetterTransfer(getUserVisit(), letter));
189                        result.setEntityLock(getEntityLockTransfer(letter));
190                    }
191                }
192            } else {
193                addExecutionError(ExecutionErrors.UnknownChainTypeName.name(), chainTypeName);
194            }
195        } else {
196            addExecutionError(ExecutionErrors.UnknownChainKindName.name(), chainKindName);
197        }
198        
199        return result;
200    }
201    
202}