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.checksum;
018
019import com.echothree.util.common.message.ExecutionErrors;
020import com.echothree.util.server.message.ExecutionErrorAccumulator;
021import javax.enterprise.context.ApplicationScoped;
022
023@ApplicationScoped
024public class UpcAChecksumLogic
025        extends BaseChecksumLogic
026        implements ItemAliasChecksumInterface {
027
028    protected UpcAChecksumLogic() {
029        super();
030    }
031
032    @Override
033    public void checkChecksum(final ExecutionErrorAccumulator eea, final String alias) {
034        if(alias.length() == 12) {
035            var hasCharacterError = false;
036            var totalA = 0;
037            var totalB = 0;
038
039            for(var i = 0; i < 11; i++) {
040                var digit = getDigit(alias, i);
041
042                if(digit == -1) {
043                    hasCharacterError = true;
044                    break;
045                } else {
046                    if(i % 2 == 0) {
047                        totalA += digit;
048                    } else {
049                        totalB += digit;
050                    }
051                }
052            }
053
054            if(!hasCharacterError) {
055                var checkDigit = getDigit(alias, 11);
056
057                hasCharacterError = checkDigit == -1;
058
059                if(!hasCharacterError) {
060                    var intermediate = (10 - (totalA * 3 + totalB) % 10) % 10;
061
062                    if(intermediate != checkDigit) {
063                        eea.addExecutionError(ExecutionErrors.IncorrectUpcAChecksum.name(), alias);
064                    }
065                }
066            }
067
068            if(hasCharacterError) {
069                eea.addExecutionError(ExecutionErrors.IncorrectUpcACharacter.name(), alias);
070            }
071        } else {
072            eea.addExecutionError(ExecutionErrors.IncorrectUpcALength.name(), alias);
073        }
074    }
075
076}