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