001// --------------------------------------------------------------------------------
002// Copyright 2002-2025 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.term.server.command;
018
019import com.echothree.control.user.term.common.edit.PartyCreditLimitEdit;
020import com.echothree.control.user.term.common.edit.TermEditFactory;
021import com.echothree.control.user.term.common.form.EditPartyCreditLimitForm;
022import com.echothree.control.user.term.common.result.TermResultFactory;
023import com.echothree.control.user.term.common.spec.PartyCreditLimitSpec;
024import com.echothree.model.control.accounting.server.control.AccountingControl;
025import com.echothree.model.control.party.common.PartyTypes;
026import com.echothree.model.control.party.server.control.PartyControl;
027import com.echothree.model.control.party.server.logic.PartyChainLogic;
028import com.echothree.model.control.term.server.control.TermControl;
029import com.echothree.model.data.user.common.pk.UserVisitPK;
030import com.echothree.util.common.message.ExecutionErrors;
031import com.echothree.util.common.validation.FieldDefinition;
032import com.echothree.util.common.validation.FieldType;
033import com.echothree.util.common.command.BaseResult;
034import com.echothree.util.common.command.EditMode;
035import com.echothree.util.common.form.BaseForm;
036import com.echothree.util.server.control.BaseEditCommand;
037import com.echothree.util.server.persistence.Session;
038import com.echothree.util.server.string.AmountUtils;
039import com.echothree.util.server.validation.Validator;
040import java.util.Arrays;
041import java.util.Collections;
042import java.util.List;
043import javax.enterprise.context.RequestScoped;
044
045@RequestScoped
046public class EditPartyCreditLimitCommand
047        extends BaseEditCommand<PartyCreditLimitSpec, PartyCreditLimitEdit> {
048    
049    private final static List<FieldDefinition> SPEC_FIELD_DEFINITIONS;
050    private final static List<FieldDefinition> EDIT_FIELD_DEFINITIONS;
051    
052    static {
053        SPEC_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList(
054                new FieldDefinition("PartyName", FieldType.ENTITY_NAME, true, null, null),
055                new FieldDefinition("CurrencyIsoName", FieldType.ENTITY_NAME, true, null, null)
056                ));
057        
058        EDIT_FIELD_DEFINITIONS = Collections.unmodifiableList(Arrays.asList(
059                new FieldDefinition("CreditLimit", FieldType.UNSIGNED_PRICE_LINE, false, null, null),
060                new FieldDefinition("PotentialCreditLimit", FieldType.UNSIGNED_PRICE_LINE, false, null, null)
061                ));
062    }
063    
064    /** Creates a new instance of EditPartyCreditLimitCommand */
065    public EditPartyCreditLimitCommand() {
066        super(null, SPEC_FIELD_DEFINITIONS, EDIT_FIELD_DEFINITIONS);
067    }
068    
069    @Override
070    protected void setupValidatorForEdit(Validator validator, BaseForm specForm) {
071        var accountingControl = Session.getModelController(AccountingControl.class);
072        var currencyIsoName = spec.getCurrencyIsoName();
073        validator.setCurrency(accountingControl.getCurrencyByIsoName(currencyIsoName));
074    }
075    
076    @Override
077    protected BaseResult execute() {
078        var partyControl = Session.getModelController(PartyControl.class);
079        var result = TermResultFactory.getEditPartyCreditLimitResult();
080        var partyName = spec.getPartyName();
081        var party = partyControl.getPartyByName(partyName);
082        
083        if(party != null) {
084            var accountingControl = Session.getModelController(AccountingControl.class);
085            var currencyIsoName = spec.getCurrencyIsoName();
086            var currency = accountingControl.getCurrencyByIsoName(currencyIsoName);
087            
088            if(currency != null) {
089                var termControl = Session.getModelController(TermControl.class);
090                
091                if(editMode.equals(EditMode.LOCK)) {
092                    var partyCreditLimit = termControl.getPartyCreditLimit(party, currency);
093                    
094                    if(partyCreditLimit != null) {
095                        result.setPartyCreditLimit(termControl.getPartyCreditLimitTransfer(getUserVisit(), partyCreditLimit));
096                        
097                        if(lockEntity(party)) {
098                            var edit = TermEditFactory.getPartyCreditLimitEdit();
099                            
100                            result.setEdit(edit);
101                            edit.setCreditLimit(AmountUtils.getInstance().formatPriceLine(currency, partyCreditLimit.getCreditLimit()));
102                            edit.setPotentialCreditLimit(AmountUtils.getInstance().formatPriceLine(currency, partyCreditLimit.getPotentialCreditLimit()));
103                        } else {
104                            addExecutionError(ExecutionErrors.EntityLockFailed.name());
105                        }
106                        
107                        result.setEntityLock(getEntityLockTransfer(party));
108                    } else {
109                        addExecutionError(ExecutionErrors.UnknownPartyCreditLimit.name());
110                    }
111                } else if(editMode.equals(EditMode.UPDATE)) {
112                    var partyCreditLimitValue = termControl.getPartyCreditLimitValueForUpdate(party, currency);
113                    
114                    if(partyCreditLimitValue != null) {
115                        if(lockEntityForUpdate(party)) {
116                            var strCreditLimit = edit.getCreditLimit();
117                            var creditLimit = strCreditLimit == null? null: Long.valueOf(strCreditLimit);
118                            var strPotentialCreditLimit = edit.getPotentialCreditLimit();
119                            var potentialCreditLimit = strPotentialCreditLimit == null? null: Long.valueOf(strPotentialCreditLimit);
120                            
121                            try {
122                                partyCreditLimitValue.setCreditLimit(creditLimit);
123                                partyCreditLimitValue.setPotentialCreditLimit(potentialCreditLimit);
124                                
125                                if(partyCreditLimitValue.hasBeenModified()) {
126                                    var partyTypeName = party.getLastDetail().getPartyType().getPartyTypeName();
127                                    var updatedBy = getPartyPK();
128                                    
129                                    termControl.updatePartyCreditLimitFromValue(partyCreditLimitValue, updatedBy);
130                                    
131                                    if(partyTypeName.equals(PartyTypes.CUSTOMER.name())) {
132                                        // ExecutionErrorAccumulator is passed in as null so that an Exception will be thrown if there is an error.
133                                        PartyChainLogic.getInstance().createPartyCreditLimitChangedChainInstance(null, party, updatedBy);
134                                    }
135                                }
136                            } finally {
137                                unlockEntity(party);
138                            }
139                        } else {
140                            addExecutionError(ExecutionErrors.EntityLockStale.name());
141                        }
142                    } else {
143                        addExecutionError(ExecutionErrors.UnknownPartyCreditLimit.name());
144                    }
145                }
146            } else {
147                addExecutionError(ExecutionErrors.UnknownCurrencyIsoName.name(), currencyIsoName);
148            }
149        } else {
150            addExecutionError(ExecutionErrors.UnknownPartyName.name(), partyName);
151        }
152        
153        return result;
154    }
155    
156}