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.invoice.server.logic;
018
019import com.echothree.model.control.accounting.common.AccountingConstants;
020import com.echothree.model.control.accounting.server.logic.GlAccountLogic;
021import com.echothree.model.control.core.server.control.EntityInstanceControl;
022import com.echothree.model.control.invoice.common.InvoiceTypes;
023import com.echothree.model.control.invoice.common.choice.PurchaseInvoiceStatusChoicesBean;
024import com.echothree.model.control.invoice.common.workflow.PurchaseInvoiceStatusConstants;
025import com.echothree.model.control.invoice.server.control.InvoiceControl;
026import com.echothree.model.control.vendor.server.control.VendorControl;
027import com.echothree.model.control.workflow.server.control.WorkflowControl;
028import com.echothree.model.data.accounting.server.entity.Currency;
029import com.echothree.model.data.accounting.server.entity.GlAccount;
030import com.echothree.model.data.contact.server.entity.PartyContactMechanism;
031import com.echothree.model.data.invoice.server.entity.Invoice;
032import com.echothree.model.data.invoice.server.entity.InvoiceLine;
033import com.echothree.model.data.invoice.server.entity.InvoiceLineType;
034import com.echothree.model.data.party.common.pk.PartyPK;
035import com.echothree.model.data.party.server.entity.Language;
036import com.echothree.model.data.party.server.entity.Party;
037import com.echothree.model.data.shipment.server.entity.FreeOnBoard;
038import com.echothree.model.data.term.server.entity.Term;
039import com.echothree.model.data.vendor.server.entity.Vendor;
040import com.echothree.util.common.message.ExecutionErrors;
041import com.echothree.util.common.persistence.BasePK;
042import com.echothree.util.server.message.ExecutionErrorAccumulator;
043import com.echothree.util.server.persistence.Session;
044import javax.enterprise.context.ApplicationScoped;
045import javax.enterprise.inject.spi.CDI;
046import javax.inject.Inject;
047
048@ApplicationScoped
049public class PurchaseInvoiceLogic {
050
051    @Inject
052    EntityInstanceControl entityInstanceControl;
053
054    @Inject
055    InvoiceControl invoiceControl;
056
057    @Inject
058    VendorControl vendorControl;
059
060    @Inject
061    WorkflowControl workflowControl;
062
063    @Inject
064    GlAccountLogic glAccountLogic;
065
066    @Inject
067    InvoiceLogic invoiceLogic;
068
069    protected PurchaseInvoiceLogic() {
070        super();
071    }
072
073    public static PurchaseInvoiceLogic getInstance() {
074        return CDI.current().select(PurchaseInvoiceLogic.class).get();
075    }
076    
077    public Invoice getInvoiceByName(String invoiceName) {
078        return invoiceControl.getInvoiceByNameUsingNames(InvoiceTypes.PURCHASE_INVOICE.name(), invoiceName);
079    }
080    
081    protected void validateReference(final ExecutionErrorAccumulator eea, final Party billFrom, final String reference, final Vendor vendor) {
082        if(vendor.getRequireReference() && reference == null) {
083            eea.addExecutionError(ExecutionErrors.PurchaseInvoiceReferenceRequired.name());
084        } else if(reference != null) {
085            if(!vendor.getAllowReferenceDuplicates() && invoiceControl.countInvoicesByInvoiceFromAndReference(billFrom, reference) != 0) {
086                eea.addExecutionError(ExecutionErrors.PurchaseInvoiceDuplicateReference.name());
087            } else {
088                var referenceValidationPattern = vendor.getReferenceValidationPattern();
089                
090                if(referenceValidationPattern != null && !reference.matches(referenceValidationPattern)) {
091                    eea.addExecutionError(ExecutionErrors.InvalidPurchaseInvoiceReference.name());
092                }
093            }
094        }
095    }
096
097    protected GlAccount getApGlAccount(final ExecutionErrorAccumulator eea, final Vendor vendor) {
098        var vendorApGlAccount = vendor.getApGlAccount();
099        var vendorTypeDefaultApGlAccount = vendor.getVendorType().getLastDetail().getDefaultApGlAccount();
100        var glAccounts = new GlAccount[]{vendorApGlAccount, vendorTypeDefaultApGlAccount};
101
102        return glAccountLogic.getDefaultGlAccountByCategory(eea, new GlAccount[]{
103                    vendor.getApGlAccount(),
104                    vendor.getVendorType().getLastDetail().getDefaultApGlAccount()
105                }, AccountingConstants.GlAccountCategory_ACCOUNTS_PAYABLE, ExecutionErrors.UnknownDefaultApGlAccount.name());
106    }
107    
108    public Invoice createInvoice(final Session session, final ExecutionErrorAccumulator eea, final Party billFrom,
109            final PartyContactMechanism billFromPartyContactMechanism, final Party billTo, final PartyContactMechanism billToPartyContactMechanism,
110            final Currency currency, final Term term, final FreeOnBoard freeOnBoard, final String reference,
111            final String description, final Long invoicedTime, final Long dueTime,
112            final Long paidTime, final String workflowEntranceName, final BasePK createdBy) {
113        Invoice invoice = null;
114        var vendor = vendorControl.getVendor(billFrom);
115        var glAccount = getApGlAccount(eea, vendor);
116        
117        validateReference(eea, billFrom, reference, vendor);
118        
119        if(eea == null || !eea.hasExecutionErrors()) {
120            invoice = invoiceLogic.createInvoice(session, eea, InvoiceTypes.PURCHASE_INVOICE.name(), billFrom,
121                    billFromPartyContactMechanism, billTo, billToPartyContactMechanism, currency, glAccount, term,
122                    freeOnBoard, reference, description, invoicedTime, dueTime, paidTime, createdBy);
123
124            if(!eea.hasExecutionErrors() && workflowEntranceName != null) {
125                var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(invoice.getPrimaryKey());
126
127                workflowControl.addEntityToWorkflowUsingNames(null, PurchaseInvoiceStatusConstants.Workflow_PURCHASE_INVOICE_STATUS, workflowEntranceName,
128                        entityInstance, null, null, createdBy);
129            }
130        }
131        
132        return invoice;
133    }
134    
135    public InvoiceLine createInvoiceLine(final ExecutionErrorAccumulator eea, final Invoice invoice, final Integer invoiceLineSequence, final InvoiceLine parentInvoiceLine,
136            final Long amount, final InvoiceLineType invoiceLineType, final GlAccount glAccount, final String description, final BasePK createdBy) {
137        InvoiceLine invoiceLine = null;
138        var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(invoice.getPrimaryKey());
139        var workflowEntityStatus = workflowControl.getWorkflowEntityStatusByEntityInstanceUsingNames(PurchaseInvoiceStatusConstants.Workflow_PURCHASE_INVOICE_STATUS, entityInstance);
140        var workflowStepName = workflowEntityStatus.getWorkflowStep().getLastDetail().getWorkflowStepName();
141
142        if(workflowStepName.equals(PurchaseInvoiceStatusConstants.WorkflowStep_ENTRY)) {
143            invoiceLine = invoiceLogic.createInvoiceLine(eea, invoice, invoiceLineSequence, parentInvoiceLine, amount, invoiceLineType, glAccount, description, createdBy);
144        } else {
145            eea.addExecutionError(ExecutionErrors.InvalidPurchaseInvoiceStatus.name(), invoice.getLastDetail().getInvoiceName(), workflowStepName);
146        }
147        
148        return invoiceLine;
149    }
150    
151    public PurchaseInvoiceStatusChoicesBean getPurchaseInvoiceStatusChoices(final String defaultInvoiceStatusChoice, final Language language, final boolean allowNullChoice,
152            final Invoice invoice, final PartyPK partyPK) {
153        var purchaseInvoiceStatusChoicesBean = new PurchaseInvoiceStatusChoicesBean();
154        
155        if(invoice == null) {
156            workflowControl.getWorkflowEntranceChoices(purchaseInvoiceStatusChoicesBean, defaultInvoiceStatusChoice, language, allowNullChoice,
157                    workflowControl.getWorkflowByName(PurchaseInvoiceStatusConstants.Workflow_PURCHASE_INVOICE_STATUS), partyPK);
158        } else {
159            var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(invoice.getPrimaryKey());
160            var workflowEntityStatus = workflowControl.getWorkflowEntityStatusByEntityInstanceUsingNames(PurchaseInvoiceStatusConstants.Workflow_PURCHASE_INVOICE_STATUS, entityInstance);
161            
162            workflowControl.getWorkflowDestinationChoices(purchaseInvoiceStatusChoicesBean, defaultInvoiceStatusChoice, language, allowNullChoice, workflowEntityStatus.getWorkflowStep(), partyPK);
163        }
164        
165        return purchaseInvoiceStatusChoicesBean;
166    }
167    
168    public void setPurchaseInvoiceStatus(final ExecutionErrorAccumulator eea, final Invoice invoice, final String invoiceStatusChoice, final PartyPK modifiedBy) {
169        var entityInstance = entityInstanceControl.getEntityInstanceByBasePK(invoice.getPrimaryKey());
170        var workflowEntityStatus = workflowControl.getWorkflowEntityStatusByEntityInstanceForUpdateUsingNames(PurchaseInvoiceStatusConstants.Workflow_PURCHASE_INVOICE_STATUS,
171                entityInstance);
172        var workflowDestination = invoiceStatusChoice == null? null: workflowControl.getWorkflowDestinationByName(workflowEntityStatus.getWorkflowStep(), invoiceStatusChoice);
173        
174        if(workflowDestination != null || invoiceStatusChoice == null) {
175            workflowControl.transitionEntityInWorkflow(eea, workflowEntityStatus, workflowDestination, null, modifiedBy);
176        } else {
177            eea.addExecutionError(ExecutionErrors.UnknownPurchaseInvoiceStatusChoice.name(), invoiceStatusChoice);
178        }
179    }
180    
181}