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.item.server.logic;
018
019import com.echothree.model.control.core.server.control.EntityInstanceControl;
020import com.echothree.model.control.item.common.exception.DuplicateItemNameException;
021import com.echothree.model.control.item.common.exception.UnknownItemNameException;
022import com.echothree.model.control.item.common.exception.UnknownItemNameOrAliasException;
023import com.echothree.model.control.item.common.exception.UnknownItemStatusChoiceException;
024import com.echothree.model.control.item.common.exception.UnknownItemTypeNameException;
025import com.echothree.model.control.item.common.exception.UnknownItemUseTypeNameException;
026import com.echothree.model.control.item.common.workflow.ItemStatusConstants;
027import com.echothree.model.control.item.server.control.ItemControl;
028import com.echothree.model.control.sequence.common.SequenceTypes;
029import com.echothree.model.control.sequence.common.exception.MissingDefaultSequenceException;
030import com.echothree.model.control.sequence.server.logic.SequenceGeneratorLogic;
031import com.echothree.model.control.workflow.server.control.WorkflowControl;
032import com.echothree.model.control.workflow.server.logic.WorkflowDestinationLogic;
033import com.echothree.model.control.workflow.server.logic.WorkflowLogic;
034import com.echothree.model.data.accounting.server.entity.ItemAccountingCategory;
035import com.echothree.model.data.cancellationpolicy.server.entity.CancellationPolicy;
036import com.echothree.model.data.item.server.entity.Item;
037import com.echothree.model.data.item.server.entity.ItemCategory;
038import com.echothree.model.data.item.server.entity.ItemDeliveryType;
039import com.echothree.model.data.item.server.entity.ItemInventoryType;
040import com.echothree.model.data.item.server.entity.ItemPriceType;
041import com.echothree.model.data.item.server.entity.ItemType;
042import com.echothree.model.data.item.server.entity.ItemUseType;
043import com.echothree.model.data.party.common.pk.PartyPK;
044import com.echothree.model.data.party.server.entity.Party;
045import com.echothree.model.data.returnpolicy.server.entity.ReturnPolicy;
046import com.echothree.model.data.sequence.server.entity.Sequence;
047import com.echothree.model.data.style.server.entity.StylePath;
048import com.echothree.model.data.uom.server.entity.UnitOfMeasureKind;
049import com.echothree.model.data.vendor.server.entity.ItemPurchasingCategory;
050import com.echothree.util.common.message.ExecutionErrors;
051import com.echothree.util.common.persistence.BasePK;
052import com.echothree.util.server.control.BaseLogic;
053import com.echothree.util.server.message.ExecutionErrorAccumulator;
054import com.echothree.util.server.persistence.Session;
055import javax.enterprise.context.ApplicationScoped;
056import javax.enterprise.inject.spi.CDI;
057import javax.inject.Inject;
058
059@ApplicationScoped
060public class ItemLogic
061        extends BaseLogic {
062
063    @Inject
064    EntityInstanceControl entityInstanceControl;
065
066    @Inject
067    ItemControl itemControl;
068
069    @Inject
070    WorkflowControl workflowControl;
071
072    @Inject
073    ItemCategoryLogic itemCategoryLogic;
074
075    @Inject
076    SequenceGeneratorLogic sequenceGeneratorLogic;
077
078    @Inject
079    WorkflowDestinationLogic workflowDestinationLogic;
080
081    @Inject
082    WorkflowLogic workflowLogic;
083
084    protected ItemLogic() {
085        super();
086    }
087
088    public static ItemLogic getInstance() {
089        return CDI.current().select(ItemLogic.class).get();
090    }
091    
092    public ItemType getItemTypeByName(final ExecutionErrorAccumulator eea, final String itemTypeName) {
093        var itemType = itemControl.getItemTypeByName(itemTypeName);
094
095        if(itemType == null) {
096            handleExecutionError(UnknownItemTypeNameException.class, eea, ExecutionErrors.UnknownItemTypeName.name(), itemTypeName);
097        }
098
099        return itemType;
100    }
101
102    public ItemUseType getItemUseTypeByName(final ExecutionErrorAccumulator eea, final String itemUseTypeName) {
103        var itemUseType = itemControl.getItemUseTypeByName(itemUseTypeName);
104
105        if(itemUseType == null) {
106            handleExecutionError(UnknownItemUseTypeNameException.class, eea, ExecutionErrors.UnknownItemUseTypeName.name(), itemUseTypeName);
107        }
108
109        return itemUseType;
110    }
111
112    public Item getItemByName(final ExecutionErrorAccumulator eea, final String itemName) {
113        var item = itemControl.getItemByName(itemName);
114
115        if(item == null) {
116            handleExecutionError(UnknownItemNameException.class, eea, ExecutionErrors.UnknownItemName.name(), itemName);
117        }
118
119        return item;
120    }
121
122    public Item getItemByNameThenAlias(final ExecutionErrorAccumulator eea, final String itemNameOrAlias) {
123        var item = itemControl.getItemByNameThenAlias(itemNameOrAlias);
124
125        if(item == null) {
126            handleExecutionError(UnknownItemNameOrAliasException.class, eea, ExecutionErrors.UnknownItemNameOrAlias.name(), itemNameOrAlias);
127        }
128
129        return item;
130    }
131
132    public Item createItem(final ExecutionErrorAccumulator eea, String itemName, final ItemType itemType, final ItemUseType itemUseType,
133            ItemCategory itemCategory, final ItemAccountingCategory itemAccountingCategory, final ItemPurchasingCategory itemPurchasingCategory,
134            final Party companyParty, final ItemDeliveryType itemDeliveryType, final ItemInventoryType itemInventoryType,
135            final Boolean inventorySerialized, final Sequence serialNumberSequence, final Boolean shippingChargeExempt,
136            final Long shippingStartTime, final Long shippingEndTime, final Long salesOrderStartTime, final Long salesOrderEndTime,
137            final Long purchaseOrderStartTime, final Long purchaseOrderEndTime, final Boolean allowClubDiscounts, final Boolean allowCouponDiscounts,
138            final Boolean allowAssociatePayments, final UnitOfMeasureKind unitOfMeasureKind, final ItemPriceType itemPriceType,
139            final CancellationPolicy cancellationPolicy, final ReturnPolicy returnPolicy, final StylePath stylePath, final BasePK createdBy) {
140        Item item = null;
141        
142        if(itemCategory == null) {
143            itemCategory = itemCategoryLogic.getDefaultItemCategory(eea);
144        }
145        
146        if(itemName == null && !hasExecutionErrors(eea)) {
147            itemName = getItemName(eea, itemCategory);
148        }
149        
150        if(itemControl.getItemByNameThenAlias(itemName) != null) {
151            handleExecutionError(DuplicateItemNameException.class, eea, ExecutionErrors.DuplicateItemName.name(),
152                    itemName);
153        }
154        
155        if(!hasExecutionErrors(eea)) {
156            item = itemControl.createItem(itemName, itemType, itemUseType, itemCategory, itemAccountingCategory,
157                    itemPurchasingCategory, companyParty, itemDeliveryType, itemInventoryType, inventorySerialized,
158                    serialNumberSequence, shippingChargeExempt, shippingStartTime, shippingEndTime, salesOrderStartTime,
159                    salesOrderEndTime, purchaseOrderStartTime, purchaseOrderEndTime, allowClubDiscounts, allowCouponDiscounts,
160                    allowAssociatePayments, unitOfMeasureKind, itemPriceType, cancellationPolicy, returnPolicy, stylePath,
161                    createdBy);
162        }
163            
164        return item;
165    }
166
167    private String getItemName(final ExecutionErrorAccumulator eea, final ItemCategory itemCategory) {
168        String itemName = null;
169        var itemSequence = itemCategory.getLastDetail().getItemSequence();
170        
171        if(itemSequence == null) {
172            itemSequence = sequenceGeneratorLogic.getDefaultSequence(eea, SequenceTypes.ITEM.name());
173        }
174        
175        if(!hasExecutionErrors(eea)) {
176            itemName = sequenceGeneratorLogic.getNextSequenceValue(eea, itemSequence);
177        } else {
178            handleExecutionError(MissingDefaultSequenceException.class, eea, ExecutionErrors.MissingDefaultSequence.name(),
179                    SequenceTypes.ITEM.name());
180        }
181        
182        return itemName;
183    }
184
185    public void setItemStatus(final Session session, final ExecutionErrorAccumulator eea, final Item item, final String itemStatusChoice, final PartyPK modifiedBy) {
186        var workflow = workflowLogic.getWorkflowByName(eea, ItemStatusConstants.Workflow_ITEM_STATUS);
187        var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(item.getPrimaryKey());
188        var workflowEntityStatus = workflowControl.getWorkflowEntityStatusByEntityInstanceForUpdate(workflow, entityInstance);
189        var workflowDestination = itemStatusChoice == null ? null : workflowControl.getWorkflowDestinationByName(workflowEntityStatus.getWorkflowStep(), itemStatusChoice);
190
191        if(workflowDestination != null || itemStatusChoice == null) {
192            var currentWorkflowStepName = workflowEntityStatus.getWorkflowStep().getLastDetail().getWorkflowStepName();
193            var map = workflowDestinationLogic.getWorkflowDestinationsAsMap(workflowDestination);
194            var handled = false;
195            Long triggerTime = null;
196            
197            if(currentWorkflowStepName.equals(ItemStatusConstants.WorkflowStep_ITEM_STATUS_ACTIVE)) {
198                if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_DISCONTINUED)) {
199                    // TODO
200                    handled = true;
201                } else if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_CANCEL_IF_NOT_IN_STOCK)) {
202                    // TODO
203                    handled = true;
204                }
205            } else if(currentWorkflowStepName.equals(ItemStatusConstants.WorkflowStep_ITEM_STATUS_DISCONTINUED)) {
206                if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_ACTIVE)) {
207                    // TODO
208                    handled = true;
209                } else if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_CANCEL_IF_NOT_IN_STOCK)) {
210                    // TODO
211                    handled = true;
212                }
213            } else if(currentWorkflowStepName.equals(ItemStatusConstants.WorkflowStep_ITEM_STATUS_CANCEL_IF_NOT_IN_STOCK)) {
214                if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_ACTIVE)) {
215                    // TODO
216                    handled = true;
217                } else if(workflowDestinationLogic.workflowDestinationMapContainsStep(map, ItemStatusConstants.Workflow_ITEM_STATUS, ItemStatusConstants.WorkflowStep_ITEM_STATUS_DISCONTINUED)) {
218                    // TODO
219                    handled = true;
220                }
221            }
222            
223            if(eea == null || !eea.hasExecutionErrors()) {
224                if(handled) {
225                    workflowControl.transitionEntityInWorkflow(eea, workflowEntityStatus, workflowDestination, triggerTime, modifiedBy);
226                } else {
227                    // TODO: An error of some sort.
228                }
229            }
230        } else {
231            handleExecutionError(UnknownItemStatusChoiceException.class, eea, ExecutionErrors.UnknownItemStatusChoice.name(), itemStatusChoice);
232        }
233    }
234    
235}