001// --------------------------------------------------------------------------------
002// Copyright 2002-2025 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.core.server.command;
018
019import com.echothree.control.user.core.common.edit.CoreEditFactory;
020import com.echothree.control.user.core.common.edit.EntityNameAttributeEdit;
021import com.echothree.control.user.core.common.form.EditEntityNameAttributeForm;
022import com.echothree.control.user.core.common.result.CoreResultFactory;
023import com.echothree.control.user.core.common.spec.EntityNameAttributeSpec;
024import com.echothree.model.control.core.server.logic.EntityAttributeLogic;
025import com.echothree.model.control.core.server.logic.EntityInstanceLogic;
026import com.echothree.model.control.party.common.PartyTypes;
027import com.echothree.model.data.core.server.entity.EntityNameAttribute;
028import com.echothree.model.data.user.common.pk.UserVisitPK;
029import com.echothree.util.common.command.BaseResult;
030import com.echothree.util.common.command.EditMode;
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.server.control.BaseEditCommand;
035import com.echothree.util.server.control.CommandSecurityDefinition;
036import com.echothree.util.server.control.PartyTypeDefinition;
037import com.echothree.util.server.persistence.PersistenceUtils;
038import java.util.Arrays;
039import java.util.Collections;
040import java.util.List;
041import java.util.regex.Pattern;
042import javax.enterprise.context.RequestScoped;
043
044@RequestScoped
045public class EditEntityNameAttributeCommand
046        extends BaseEditCommand<EntityNameAttributeSpec, EntityNameAttributeEdit> {
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(), null)
056        ));
057
058        SPEC_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList(
059                new FieldDefinition("EntityRef", FieldType.ENTITY_REF, false, null, null),
060                new FieldDefinition("Uuid", FieldType.UUID, false, null, null),
061                new FieldDefinition("EntityAttributeName", FieldType.ENTITY_NAME, false, null, null),
062                new FieldDefinition("EntityAttributeUuid", FieldType.UUID, false, null, null)
063                ));
064        
065        EDIT_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList(
066                new FieldDefinition("NameAttribute", FieldType.ENTITY_NAME, true, null, null)
067                ));
068    }
069    
070    /** Creates a new instance of EditEntityNameAttributeCommand */
071    public EditEntityNameAttributeCommand() {
072        super(COMMAND_SECURITY_DEFINITION, SPEC_FIELD_DEFINITIONS, EDIT_FIELD_DEFINITIONS);
073    }
074    
075    @Override
076    protected BaseResult execute() {
077        var result = CoreResultFactory.getEditEntityNameAttributeResult();
078        var parameterCount = EntityInstanceLogic.getInstance().countPossibleEntitySpecs(spec);
079
080        if(parameterCount == 1) {
081            var entityInstance = EntityInstanceLogic.getInstance().getEntityInstance(this, spec);
082
083            if(!hasExecutionErrors()) {
084                var entityAttributeName = spec.getEntityAttributeName();
085                var entityAttributeUuid = spec.getEntityAttributeUuid();
086
087                parameterCount = (entityAttributeName == null ? 0 : 1) + (entityAttributeUuid == null ? 0 : 1);
088
089                if(parameterCount == 1) {
090                    var entityAttribute = entityAttributeName == null ?
091                            EntityAttributeLogic.getInstance().getEntityAttributeByUuid(this, entityAttributeUuid) :
092                            EntityAttributeLogic.getInstance().getEntityAttributeByName(this, entityInstance.getEntityType(), entityAttributeName);
093
094                    if(!hasExecutionErrors()) {
095                        if(entityInstance.getEntityType().equals(entityAttribute.getLastDetail().getEntityType())) {
096                            EntityNameAttribute entityNameAttribute = null;
097                            var basePK = PersistenceUtils.getInstance().getBasePKFromEntityInstance(entityInstance);
098
099                            if(editMode.equals(EditMode.LOCK) || editMode.equals(EditMode.ABANDON)) {
100                                entityNameAttribute = coreControl.getEntityNameAttribute(entityAttribute, entityInstance);
101
102                                if(entityNameAttribute != null) {
103                                    if(editMode.equals(EditMode.LOCK)) {
104                                        result.setEntityNameAttribute(coreControl.getEntityNameAttributeTransfer(getUserVisit(),
105                                                entityNameAttribute, entityInstance));
106
107                                        if(lockEntity(basePK)) {
108                                            var edit = CoreEditFactory.getEntityNameAttributeEdit();
109
110                                            result.setEdit(edit);
111                                            edit.setNameAttribute(entityNameAttribute.getNameAttribute());
112                                        } else {
113                                            addExecutionError(ExecutionErrors.EntityLockFailed.name());
114                                        }
115                                    } else { // EditMode.ABANDON
116                                        unlockEntity(basePK);
117                                        basePK = null;
118                                    }
119                                } else {
120                                    addExecutionError(ExecutionErrors.UnknownEntityNameAttribute.name(),
121                                            EntityInstanceLogic.getInstance().getEntityRefFromEntityInstance(entityInstance), entityAttributeName);
122                                }
123                            } else if(editMode.equals(EditMode.UPDATE)) {
124                                var entityAttributeString = coreControl.getEntityAttributeString(entityAttribute);
125                                var validationPattern = entityAttributeString == null ? null : entityAttributeString.getValidationPattern();
126                                var stringAttribute = edit.getNameAttribute();
127
128                                if(validationPattern != null) {
129                                    var pattern = Pattern.compile(validationPattern);
130                                    var matcher = pattern.matcher(stringAttribute);
131
132                                    if(!matcher.matches()) {
133                                        addExecutionError(ExecutionErrors.InvalidNameAttribute.name(), stringAttribute);
134                                    }
135                                }
136
137                                if(!hasExecutionErrors()) {
138                                    entityNameAttribute = coreControl.getEntityNameAttributeForUpdate(entityAttribute, entityInstance);
139
140                                    if(entityNameAttribute != null) {
141                                        if(lockEntityForUpdate(basePK)) {
142                                            try {
143                                                var entityNameAttributeValue = coreControl.getEntityNameAttributeValueForUpdate(entityNameAttribute);
144
145                                                entityNameAttributeValue.setNameAttribute(stringAttribute);
146
147                                                coreControl.updateEntityNameAttributeFromValue(entityNameAttributeValue, getPartyPK());
148                                            } finally {
149                                                unlockEntity(basePK);
150                                                basePK = null;
151                                            }
152                                        } else {
153                                            addExecutionError(ExecutionErrors.EntityLockStale.name());
154                                        }
155                                    } else {
156                                        addExecutionError(ExecutionErrors.UnknownEntityNameAttribute.name(),
157                                                EntityInstanceLogic.getInstance().getEntityRefFromEntityInstance(entityInstance), entityAttributeName);
158                                    }
159                                }
160                            }
161
162                            if(basePK != null) {
163                                result.setEntityLock(getEntityLockTransfer(basePK));
164                            }
165
166                            if(entityNameAttribute != null) {
167                                result.setEntityNameAttribute(coreControl.getEntityNameAttributeTransfer(getUserVisit(), entityNameAttribute, entityInstance));
168                            }
169                        } else {
170                            addExecutionError(ExecutionErrors.MismatchedEntityType.name());
171                        }
172                    }
173                } else {
174                    addExecutionError(ExecutionErrors.InvalidParameterCount.name());
175                }
176            }
177        } else {
178            addExecutionError(ExecutionErrors.InvalidParameterCount.name());
179        }
180
181        return result;
182    }
183    
184}