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.purchase.server.command;
018
019import com.echothree.control.user.purchase.common.form.CreatePurchaseInvoiceForm;
020import com.echothree.control.user.purchase.common.result.PurchaseResultFactory;
021import com.echothree.model.control.accounting.server.control.AccountingControl;
022import com.echothree.model.control.contact.server.control.ContactControl;
023import com.echothree.model.control.invoice.common.workflow.PurchaseInvoiceStatusConstants;
024import com.echothree.model.control.invoice.server.logic.PurchaseInvoiceLogic;
025import com.echothree.model.control.party.common.PartyTypes;
026import com.echothree.model.control.party.server.control.PartyControl;
027import com.echothree.model.control.security.common.SecurityRoleGroups;
028import com.echothree.model.control.security.common.SecurityRoles;
029import com.echothree.model.control.shipment.server.logic.FreeOnBoardLogic;
030import com.echothree.model.control.term.server.logic.TermLogic;
031import com.echothree.model.control.vendor.server.control.VendorControl;
032import com.echothree.model.data.invoice.server.entity.Invoice;
033import com.echothree.model.data.party.server.entity.Party;
034import com.echothree.model.data.user.common.pk.UserVisitPK;
035import com.echothree.util.common.command.BaseResult;
036import com.echothree.util.common.message.ExecutionErrors;
037import com.echothree.util.common.validation.FieldDefinition;
038import com.echothree.util.common.validation.FieldType;
039import com.echothree.util.server.control.BaseSimpleCommand;
040import com.echothree.util.server.control.CommandSecurityDefinition;
041import com.echothree.util.server.control.PartyTypeDefinition;
042import com.echothree.util.server.control.SecurityRoleDefinition;
043import com.echothree.util.server.persistence.Session;
044import java.util.List;
045import javax.enterprise.context.Dependent;
046
047@Dependent
048public class CreatePurchaseInvoiceCommand
049        extends BaseSimpleCommand<CreatePurchaseInvoiceForm> {
050    
051    private final static CommandSecurityDefinition COMMAND_SECURITY_DEFINITION;
052    private final static List<FieldDefinition> FORM_FIELD_DEFINITIONS;
053    
054    static {
055        COMMAND_SECURITY_DEFINITION = new CommandSecurityDefinition(List.of(
056                new PartyTypeDefinition(PartyTypes.UTILITY.name(), null),
057                new PartyTypeDefinition(PartyTypes.EMPLOYEE.name(), List.of(
058                    new SecurityRoleDefinition(SecurityRoleGroups.PurchaseInvoice.name(), SecurityRoles.Create.name())
059                    ))
060                ));
061        
062        FORM_FIELD_DEFINITIONS = List.of(
063                new FieldDefinition("CompanyName", FieldType.ENTITY_NAME, false, null, null),
064                new FieldDefinition("BillFromPartyName", FieldType.ENTITY_NAME, false, null, null),
065                new FieldDefinition("BillFromContactMechanismName", FieldType.ENTITY_NAME, false, null, null),
066                new FieldDefinition("VendorName", FieldType.ENTITY_NAME, false, null, null),
067                new FieldDefinition("BillToPartyName", FieldType.ENTITY_NAME, false, null, null),
068                new FieldDefinition("BillToContactMechanismName", FieldType.ENTITY_NAME, false, null, null),
069                new FieldDefinition("CurrencyIsoName", FieldType.ENTITY_NAME, false, null, null),
070                new FieldDefinition("InvoicedTime", FieldType.DATE_TIME, false, null, null),
071                new FieldDefinition("DueTime", FieldType.DATE_TIME, false, null, null),
072                new FieldDefinition("PaidTime", FieldType.DATE_TIME, false, null, null),
073                new FieldDefinition("TermName", FieldType.ENTITY_NAME, false, null, null),
074                new FieldDefinition("FreeOnBoardName", FieldType.ENTITY_NAME, false, null, null),
075                new FieldDefinition("Reference", FieldType.STRING, false, 1L, 40L),
076                new FieldDefinition("Description", FieldType.STRING, false, 1L, 132L)
077                );
078    }
079    
080    /** Creates a new instance of CreatePurchaseInvoiceCommand */
081    public CreatePurchaseInvoiceCommand() {
082        super(COMMAND_SECURITY_DEFINITION, FORM_FIELD_DEFINITIONS, false);
083    }
084    
085    @Override
086    protected BaseResult execute() {
087        var result = PurchaseResultFactory.getCreatePurchaseInvoiceResult();
088        Invoice invoice = null;
089        var accountingControl = Session.getModelController(AccountingControl.class);
090        var currencyIsoName = form.getCurrencyIsoName();
091        var currency = currencyIsoName == null ? null : accountingControl.getCurrencyByIsoName(currencyIsoName);
092
093        if(currencyIsoName == null || currency != null) {
094            var termName = form.getTermName();
095            var freeOnBoardName = form.getFreeOnBoardName();
096            var term = termName == null ? null : TermLogic.getInstance().getTermByName(this, termName);
097            var freeOnBoard = freeOnBoardName == null ? null : FreeOnBoardLogic.getInstance().getFreeOnBoardByName(this, freeOnBoardName);
098
099            if(!hasExecutionErrors()) {
100                var vendorControl = Session.getModelController(VendorControl.class);
101                var vendorName = form.getVendorName();
102                var billFromPartyName = form.getBillFromPartyName();
103                var parameterCount = (vendorName == null ? 0 : 1) + (billFromPartyName == null ? 0 : 1);
104
105                if(parameterCount == 1) {
106                    var partyControl = Session.getModelController(PartyControl.class);
107                    Party billFrom = null;
108                    
109                    if(vendorName == null) {
110                        billFrom = partyControl.getPartyByName(billFromPartyName);
111                        
112                        if(billFrom != null) {
113                            if(!billFrom.getLastDetail().getPartyType().getPartyTypeName().equals(PartyTypes.VENDOR.name())) {
114                                addExecutionError(ExecutionErrors.InvalidBillFromPartyType.name());
115                            }
116                        } else {
117                            addExecutionError(ExecutionErrors.UnknownBillFromPartyName.name(), billFromPartyName);
118                        }
119                    } else {
120                        var vendor = vendorControl.getVendorByName(vendorName);
121                        
122                        if(vendor != null) {
123                            billFrom = vendor.getParty();
124                        } else {
125                            addExecutionError(ExecutionErrors.UnknownVendorName.name(), vendorName);
126                        }
127                    }
128                    
129                    if(!hasExecutionErrors()) {
130                        var contactControl = Session.getModelController(ContactControl.class);
131                        var billFromContactMechanismName = form.getBillFromContactMechanismName();
132                        var billFromContactMechanism = billFromContactMechanismName == null? null: contactControl.getPartyContactMechanismByContactMechanismName(this, billFrom, billFromContactMechanismName);
133                        
134                        if(billFromContactMechanismName == null || billFromContactMechanism != null) {
135                            var companyName = form.getCompanyName();
136                            var billToPartyName = form.getBillToPartyName();
137
138                            parameterCount = (companyName == null ? 0 : 1) + (billToPartyName == null ? 0 : 1);
139
140                            if(parameterCount < 2) {
141                                Party billTo = null;
142
143                                if(companyName != null) {
144                                    var partyCompany = partyControl.getPartyCompanyByName(companyName);
145
146                                    if(partyCompany != null) {
147                                        billTo = partyCompany.getParty();
148                                    } else {
149                                        addExecutionError(ExecutionErrors.UnknownCompanyName.name(), companyName);
150                                    }
151                                } else if(billToPartyName != null) {
152                                    billTo = partyControl.getPartyByName(billToPartyName);
153
154                                    if(billTo != null) {
155                                        if(!billTo.getLastDetail().getPartyType().getPartyTypeName().equals(PartyTypes.COMPANY.name())) {
156                                            addExecutionError(ExecutionErrors.InvalidBillToPartyType.name());
157                                        }
158                                    } else {
159                                        addExecutionError(ExecutionErrors.UnknownBillToPartyName.name(), billToPartyName);
160                                    }
161                                } else {
162                                    billTo = getUserSession().getPartyRelationship().getFromParty();
163                                }
164
165                                if(!hasExecutionErrors()) {
166                                    var billToContactMechanismName = form.getBillToContactMechanismName();
167                                    var billToContactMechanism = billToContactMechanismName == null ? null : contactControl.getPartyContactMechanismByContactMechanismName(this, billTo, billToContactMechanismName);
168                                    
169                                    if(billToContactMechanismName == null || billToContactMechanism != null) {
170                                        var strInvoicedTime = form.getInvoicedTime();
171                                        var invoicedTime = strInvoicedTime == null ? null : Long.valueOf(strInvoicedTime);
172                                        var strDueTime = form.getDueTime();
173                                        var dueTime = strDueTime == null ? null : Long.valueOf(strDueTime);
174                                        var strPaidTime = form.getPaidTime();
175                                        var paidTime = strPaidTime == null ? null : Long.valueOf(strPaidTime);
176                                        var reference = form.getReference();
177                                        var description = form.getDescription();
178
179                                        invoice = PurchaseInvoiceLogic.getInstance().createInvoice(session, this, billFrom, billFromContactMechanism, billTo,
180                                                billToContactMechanism, currency, term, freeOnBoard, reference, description, invoicedTime, dueTime, paidTime,
181                                                PurchaseInvoiceStatusConstants.WorkflowEntrance_NEW_ENTRY, getPartyPK());
182                                    }
183                                }
184                            } else {
185                                addExecutionError(ExecutionErrors.InvalidParameterCount.name());
186                            }
187                        }
188                    }
189                } else {
190                    addExecutionError(ExecutionErrors.InvalidParameterCount.name());
191                }
192            }
193        } else {
194            addExecutionError(ExecutionErrors.UnknownCurrencyIsoName.name(), currencyIsoName);
195        }
196        
197        if(invoice != null) {
198            result.setEntityRef(invoice.getPrimaryKey().getEntityRef());
199            result.setInvoiceName(invoice.getLastDetail().getInvoiceName());
200        }
201        
202        return result;
203    }
204    
205}