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