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.model.control.contactlist.server.logic;
018
019import com.echothree.control.user.contactlist.common.spec.ContactListUniversalSpec;
020import com.echothree.model.control.contactlist.common.exception.UnknownContactListContactMechanismPurposeException;
021import com.echothree.model.control.contactlist.common.exception.UnknownContactListNameException;
022import com.echothree.model.control.contactlist.common.exception.UnknownDefaultContactListException;
023import com.echothree.model.control.contactlist.common.workflow.PartyContactListStatusConstants;
024import com.echothree.model.control.contactlist.server.control.ContactListControl;
025import com.echothree.model.control.core.common.ComponentVendors;
026import com.echothree.model.control.core.common.EntityTypes;
027import com.echothree.model.control.core.common.exception.InvalidParameterCountException;
028import com.echothree.model.control.core.server.control.EntityInstanceControl;
029import com.echothree.model.control.core.server.logic.EntityInstanceLogic;
030import com.echothree.model.control.customer.server.control.CustomerControl;
031import com.echothree.model.control.party.common.PartyTypes;
032import com.echothree.model.control.party.server.logic.PartyLogic;
033import com.echothree.model.control.workflow.server.control.WorkflowControl;
034import com.echothree.model.data.contact.server.entity.ContactMechanismPurpose;
035import com.echothree.model.data.contactlist.server.entity.ContactList;
036import com.echothree.model.data.contactlist.server.entity.ContactListContactMechanismPurpose;
037import com.echothree.model.data.contactlist.server.entity.CustomerTypeContactList;
038import com.echothree.model.data.contactlist.server.entity.CustomerTypeContactListGroup;
039import com.echothree.model.data.contactlist.server.entity.PartyContactList;
040import com.echothree.model.data.contactlist.server.entity.PartyTypeContactList;
041import com.echothree.model.data.contactlist.server.entity.PartyTypeContactListGroup;
042import com.echothree.model.data.party.server.entity.Party;
043import com.echothree.util.common.message.ExecutionErrors;
044import com.echothree.util.common.persistence.BasePK;
045import com.echothree.util.server.control.BaseLogic;
046import com.echothree.util.server.message.ExecutionErrorAccumulator;
047import com.echothree.util.server.persistence.EntityPermission;
048import java.util.HashSet;
049import java.util.Set;
050import javax.enterprise.context.ApplicationScoped;
051import javax.enterprise.inject.spi.CDI;
052import javax.inject.Inject;
053
054@ApplicationScoped
055public class ContactListLogic
056    extends BaseLogic {
057
058    protected ContactListLogic() {
059        super();
060    }
061
062    public static ContactListLogic getInstance() {
063        return CDI.current().select(ContactListLogic.class).get();
064    }
065
066    @Inject
067    ContactListControl contactListControl;
068
069    @Inject
070    CustomerControl customerControl;
071
072    @Inject
073    EntityInstanceControl entityInstanceControl;
074
075    @Inject
076    WorkflowControl workflowControl;
077
078    @Inject
079    ContactListChainLogic contactListChainLogic;
080
081    @Inject
082    PartyLogic partyLogic;
083    
084    public ContactList getContactListByName(final ExecutionErrorAccumulator eea, final String contactListName,
085            final EntityPermission entityPermission) {
086        var contactList = contactListControl.getContactListByName(contactListName, entityPermission);
087
088        if(contactList == null) {
089            handleExecutionError(UnknownContactListNameException.class, eea, ExecutionErrors.UnknownContactListName.name(), contactListName);
090        }
091
092        return contactList;
093    }
094
095    public ContactList getContactListByName(final ExecutionErrorAccumulator eea, final String contactListName) {
096        return getContactListByName(eea, contactListName, EntityPermission.READ_ONLY);
097    }
098
099    public ContactList getContactListByNameForUpdate(final ExecutionErrorAccumulator eea, final String contactListName) {
100        return getContactListByName(eea, contactListName, EntityPermission.READ_WRITE);
101    }
102
103    public ContactList getContactListByUniversalSpec(final ExecutionErrorAccumulator eea,
104            final ContactListUniversalSpec universalSpec, boolean allowDefault, final EntityPermission entityPermission) {
105        ContactList contactList = null;
106        var contactListName = universalSpec.getContactListName();
107        var parameterCount = (contactListName == null ? 0 : 1) + EntityInstanceLogic.getInstance().countPossibleEntitySpecs(universalSpec);
108
109        switch(parameterCount) {
110            case 0 -> {
111                if(allowDefault) {
112                    contactList = contactListControl.getDefaultContactList(entityPermission);
113
114                    if(contactList == null) {
115                        handleExecutionError(UnknownDefaultContactListException.class, eea, ExecutionErrors.UnknownDefaultContactList.name());
116                    }
117                } else {
118                    handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name());
119                }
120            }
121            case 1 -> {
122                if(contactListName == null) {
123                    var entityInstance = EntityInstanceLogic.getInstance().getEntityInstance(eea, universalSpec,
124                            ComponentVendors.ECHO_THREE.name(), EntityTypes.ContactList.name());
125
126                    if(eea == null || !eea.hasExecutionErrors()) {
127                        contactList = contactListControl.getContactListByEntityInstance(entityInstance, entityPermission);
128                    }
129                } else {
130                    contactList = getContactListByName(eea, contactListName, entityPermission);
131                }
132            }
133            default ->
134                    handleExecutionError(InvalidParameterCountException.class, eea, ExecutionErrors.InvalidParameterCount.name());
135        }
136
137        return contactList;
138    }
139
140    public ContactList getContactListByUniversalSpec(final ExecutionErrorAccumulator eea,
141            final ContactListUniversalSpec universalSpec, boolean allowDefault) {
142        return getContactListByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_ONLY);
143    }
144
145    public ContactList getContactListByUniversalSpecForUpdate(final ExecutionErrorAccumulator eea,
146            final ContactListUniversalSpec universalSpec, boolean allowDefault) {
147        return getContactListByUniversalSpec(eea, universalSpec, allowDefault, EntityPermission.READ_WRITE);
148    }
149
150    public ContactListContactMechanismPurpose getContactListContactMechanismPurpose(final ExecutionErrorAccumulator eea, final ContactList contactList,
151            final ContactMechanismPurpose contactMechanismPurpose) {
152        var contactListContactMechanismPurpose = contactListControl.getContactListContactMechanismPurpose(contactList, contactMechanismPurpose);
153        
154        if(contactListContactMechanismPurpose == null) {
155            handleExecutionError(UnknownContactListContactMechanismPurposeException.class, eea, ExecutionErrors.UnknownContactListContactMechanismPurpose.name(),
156                    contactList.getLastDetail().getContactListName(), contactMechanismPurpose.getContactMechanismPurposeName());
157        }
158        
159        return contactListContactMechanismPurpose;
160    }
161    
162    public boolean isPartyOnContactList(final Party party, final ContactList contactList) {
163        return contactListControl.getPartyContactList(party, contactList) != null;
164    }
165    
166    public void addContactListToParty(final ExecutionErrorAccumulator eea, final Party party, final ContactList contactList,
167            final ContactListContactMechanismPurpose preferredContactListContactMechanismPurpose, final BasePK createdBy) {
168        var partyContactList = contactListControl.createPartyContactList(party, contactList, preferredContactListContactMechanismPurpose, createdBy);
169        var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(partyContactList.getPrimaryKey());
170        var workflowEntrance = contactList.getLastDetail().getDefaultPartyContactListStatus();
171        var workflowEntranceName = workflowEntrance.getLastDetail().getWorkflowEntranceName();
172        
173        workflowControl.addEntityToWorkflow(workflowEntrance, entityInstance, null, null, createdBy);
174        
175        if(workflowEntranceName.equals(PartyContactListStatusConstants.WorkflowEntrance_NEW_AWAITING_VERIFICATION)) {
176            contactListChainLogic.createContactListConfirmationChainInstance(eea, party, partyContactList, createdBy);
177        } else if(workflowEntranceName.equals(PartyContactListStatusConstants.WorkflowEntrance_NEW_ACTIVE)) {
178            contactListChainLogic.createContactListSubscribeChainInstance(eea, party, partyContactList, createdBy);
179        }
180    }
181    
182    public void removeContactListFromParty(final ExecutionErrorAccumulator eea, final PartyContactList partyContactList, final BasePK deletedBy) {
183        var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(partyContactList.getPrimaryKey());
184        var workflowEntityStatus = workflowControl.getWorkflowEntityStatusByEntityInstanceForUpdateUsingNames(PartyContactListStatusConstants.Workflow_PARTY_CONTACT_LIST_STATUS, entityInstance);
185        var workflowStepName = workflowEntityStatus.getWorkflowStep().getLastDetail().getWorkflowStepName();
186        
187        if(workflowStepName.equals(PartyContactListStatusConstants.WorkflowStep_ACTIVE)) {
188            contactListChainLogic.createContactListUnsubscribeChainInstance(eea, partyContactList.getLastDetail().getParty(), partyContactList, deletedBy);
189        }
190        
191        contactListControl.deletePartyContactList(partyContactList, deletedBy);
192        workflowControl.deleteWorkflowEntityStatus(workflowEntityStatus, deletedBy);
193    }
194    
195    public void setupInitialContactLists(final ExecutionErrorAccumulator eea, final Party party, final BasePK createdBy) {
196        var partyType = party.getLastDetail().getPartyType();
197        Set<ContactList> contactLists = new HashSet<>();
198
199        contactListControl.getPartyTypeContactListsByPartyType(partyType)
200                .stream()
201                .filter(PartyTypeContactList::getAddWhenCreated)
202                .map(PartyTypeContactList::getContactList)
203                .forEach(contactLists::add);
204
205        contactListControl.getPartyTypeContactListGroupsByPartyType(partyType)
206                .stream()
207                .filter(PartyTypeContactListGroup::getAddWhenCreated)
208                .forEach((partyTypeContactListGroup) ->
209                        contactLists.addAll(contactListControl.getContactListsByContactListGroup(partyTypeContactListGroup.getContactListGroup()))
210                );
211
212        if(partyLogic.isPartyType(party, PartyTypes.CUSTOMER.name())) {
213            var customerType = customerControl.getCustomer(party).getCustomerType();
214
215            contactListControl.getCustomerTypeContactListsByCustomerType(customerType)
216                    .stream()
217                    .filter(CustomerTypeContactList::getAddWhenCreated)
218                    .map(CustomerTypeContactList::getContactList)
219                    .forEach(contactLists::add);
220
221            contactListControl.getCustomerTypeContactListGroupsByCustomerType(customerType)
222                    .stream()
223                    .filter(CustomerTypeContactListGroup::getAddWhenCreated)
224                    .forEach((customerTypeContactListGroup) ->
225                            contactLists.addAll(contactListControl.getContactListsByContactListGroup(customerTypeContactListGroup.getContactListGroup()))
226                    );
227        }
228
229        if(!hasExecutionErrors(eea)) {
230            contactLists.forEach((contactList) -> {
231                addContactListToParty(eea, party, contactList, null, createdBy);
232            });
233        }
234    }
235    
236}