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.contact.server.command;
018
019import com.echothree.control.user.contact.common.form.CreateContactTelephoneForm;
020import com.echothree.control.user.contact.common.result.ContactResultFactory;
021import com.echothree.model.control.contact.common.ContactMechanismTypes;
022import com.echothree.model.control.contact.common.workflow.TelephoneStatusConstants;
023import com.echothree.model.control.contact.server.control.ContactControl;
024import com.echothree.model.control.core.server.control.EntityInstanceControl;
025import com.echothree.model.control.geo.server.control.GeoControl;
026import com.echothree.model.control.party.common.PartyTypes;
027import com.echothree.model.control.party.server.control.PartyControl;
028import com.echothree.model.control.security.common.SecurityRoleGroups;
029import com.echothree.model.control.security.common.SecurityRoles;
030import com.echothree.model.control.sequence.common.SequenceTypes;
031import com.echothree.model.control.sequence.server.logic.SequenceGeneratorLogic;
032import com.echothree.model.control.workflow.server.control.WorkflowControl;
033import com.echothree.model.data.user.common.pk.UserVisitPK;
034import com.echothree.util.common.command.BaseResult;
035import com.echothree.util.common.command.SecurityResult;
036import com.echothree.util.common.message.ExecutionErrors;
037import com.echothree.util.common.persistence.BasePK;
038import com.echothree.util.common.string.StringUtils;
039import com.echothree.util.common.validation.FieldDefinition;
040import com.echothree.util.common.validation.FieldType;
041import com.echothree.util.server.control.BaseSimpleCommand;
042import com.echothree.util.server.control.CommandSecurityDefinition;
043import com.echothree.util.server.control.PartyTypeDefinition;
044import com.echothree.util.server.control.SecurityRoleDefinition;
045import com.echothree.util.server.persistence.Session;
046import java.util.List;
047import java.util.Locale;
048import java.util.regex.Pattern;
049import javax.enterprise.context.Dependent;
050
051@Dependent
052public class CreateContactTelephoneCommand
053        extends BaseSimpleCommand<CreateContactTelephoneForm> {
054
055    private final static CommandSecurityDefinition COMMAND_SECURITY_DEFINITION;
056    private final static List<FieldDefinition> FORM_FIELD_DEFINITIONS;
057
058    static {
059        COMMAND_SECURITY_DEFINITION = new CommandSecurityDefinition(List.of(
060                new PartyTypeDefinition(PartyTypes.UTILITY.name(), null),
061                new PartyTypeDefinition(PartyTypes.CUSTOMER.name(), null),
062                new PartyTypeDefinition(PartyTypes.VENDOR.name(), null),
063                new PartyTypeDefinition(PartyTypes.EMPLOYEE.name(), List.of(
064                        new SecurityRoleDefinition(SecurityRoleGroups.ContactMechanism.name(), SecurityRoles.Create.name())
065                        ))
066                ));
067
068        FORM_FIELD_DEFINITIONS = List.of(
069                new FieldDefinition("PartyName", FieldType.ENTITY_NAME, false, null, null),
070                new FieldDefinition("CountryName", FieldType.ENTITY_NAME, true, null, null),
071                new FieldDefinition("AreaCode", FieldType.STRING, false, 1L, 5L),
072                new FieldDefinition("TelephoneNumber", FieldType.STRING, true, 1L, 25L),
073                new FieldDefinition("TelephoneExtension", FieldType.NUMBERS, false, 1L, 10L),
074                new FieldDefinition("AllowSolicitation", FieldType.BOOLEAN, true, null, null),
075                new FieldDefinition("Description", FieldType.STRING, false, 1L, 132L)
076                );
077    }
078    
079    /** Creates a new instance of CreateContactTelephoneCommand */
080    public CreateContactTelephoneCommand() {
081        super(COMMAND_SECURITY_DEFINITION, FORM_FIELD_DEFINITIONS, false);
082    }
083
084    @Override
085    protected SecurityResult security() {
086        var securityResult = super.security();
087
088        return securityResult != null ? securityResult : selfOnly(form);
089    }
090
091    @Override
092    protected BaseResult execute() {
093        var result = ContactResultFactory.getCreateContactTelephoneResult();
094        var partyControl = Session.getModelController(PartyControl.class);
095        var partyName = form.getPartyName();
096        var party = partyName == null ? getParty() : partyControl.getPartyByName(partyName);
097        
098        if(party != null) {
099            var geoControl = Session.getModelController(GeoControl.class);
100            var countryName = form.getCountryName();
101            var countryAlias = StringUtils.getInstance().cleanStringToName(countryName).toUpperCase(Locale.getDefault());
102            var countryGeoCode = geoControl.getCountryByAlias(countryAlias);
103            
104            if(countryGeoCode != null) {
105                var geoCodeCountry = geoControl.getGeoCodeCountry(countryGeoCode);
106                var areaCode = form.getAreaCode();
107                
108                if(!geoCodeCountry.getAreaCodeRequired() || areaCode != null) {
109                    var areaCodePattern = geoCodeCountry.getAreaCodePattern();
110                    var pattern = areaCodePattern == null? null: Pattern.compile(areaCodePattern);
111                    
112                    if(pattern == null || pattern.matcher(areaCode).matches()) {
113                        var telephoneNumberPattern = geoCodeCountry.getTelephoneNumberPattern();
114                        var telephoneNumber = form.getTelephoneNumber();
115                        
116                        pattern = telephoneNumberPattern == null? null: Pattern.compile(telephoneNumberPattern);
117                        
118                        if(pattern == null || pattern.matcher(telephoneNumber).matches()) {
119                            var contactControl = Session.getModelController(ContactControl.class);
120                            var entityInstanceControl = Session.getModelController(EntityInstanceControl.class);
121                            var workflowControl = Session.getModelController(WorkflowControl.class);
122                            BasePK createdBy = getPartyPK();
123                            var telephoneExtension = form.getTelephoneExtension();
124                            var allowSolicitation = Boolean.valueOf(form.getAllowSolicitation());
125                            var description = form.getDescription();
126                            var contactMechanismName = SequenceGeneratorLogic.getInstance().getNextSequenceValue(null, SequenceTypes.CONTACT_MECHANISM.name());
127
128                            var contactMechanismType = contactControl.getContactMechanismTypeByName(ContactMechanismTypes.TELECOM_ADDRESS.name());
129                            var contactMechanism = contactControl.createContactMechanism(contactMechanismName,
130                                    contactMechanismType, allowSolicitation, createdBy);
131                            
132                            contactControl.createContactTelephone(contactMechanism, countryGeoCode, areaCode, telephoneNumber,
133                                    telephoneExtension, createdBy);
134                            
135                            contactControl.createPartyContactMechanism(party, contactMechanism, description, false, 1, createdBy);
136
137                            var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(contactMechanism.getPrimaryKey());
138                            workflowControl.addEntityToWorkflowUsingNames(null, TelephoneStatusConstants.Workflow_TELEPHONE_STATUS,
139                                    TelephoneStatusConstants.WorkflowEntrance_NEW_TELEPHONE, entityInstance, null, null, createdBy);
140                            
141                            result.setContactMechanismName(contactMechanism.getLastDetail().getContactMechanismName());
142                            result.setEntityRef(contactMechanism.getPrimaryKey().getEntityRef());
143                        } else {
144                            addExecutionError(ExecutionErrors.InvalidTelephoneNumber.name(), telephoneNumber);
145                        }
146                    } else {
147                        addExecutionError(ExecutionErrors.InvalidAreaCode.name(), areaCode);
148                    }
149                } else {
150                    addExecutionError(ExecutionErrors.MissingAreaCode.name());
151                }
152            } else {
153                addExecutionError(ExecutionErrors.UnknownCountryName.name(), countryName);
154            }
155        } else {
156            addExecutionError(ExecutionErrors.UnknownPartyName.name(), partyName);
157        }
158        
159        return result;
160    }
161    
162}