]> git.basschouten.com Git - openhab-addons.git/blob
a0518c8811d2d674460d1c48f519cb981dbceba4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.transform.vat.internal;
14
15 import static org.openhab.transform.vat.internal.VATTransformationConstants.*;
16
17 import java.math.BigDecimal;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.library.types.QuantityType;
22 import org.openhab.core.transform.TransformationException;
23 import org.openhab.core.transform.TransformationService;
24 import org.osgi.service.component.annotations.Component;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * This {@link TransformationService} adds VAT to the input according to configured country.
30  *
31  * @author Jacob Laursen - Initial contribution
32  */
33 @NonNullByDefault
34 @Component(service = { TransformationService.class }, property = { "openhab.transform=VAT" })
35 public class VATTransformationService implements TransformationService {
36
37     private final Logger logger = LoggerFactory.getLogger(VATTransformationService.class);
38
39     @Override
40     public @Nullable String transform(String valueString, String sourceString) throws TransformationException {
41         QuantityType<?> source;
42         try {
43             source = new QuantityType<>(sourceString);
44         } catch (IllegalArgumentException e) {
45             logger.warn("Input value '{}' could not be converted to a valid number", sourceString);
46             throw new TransformationException("VAT Transformation can only be used with numeric inputs", e);
47         }
48         BigDecimal value;
49         try {
50             value = new BigDecimal(valueString);
51         } catch (NumberFormatException e) {
52             String rate = RATES.get(valueString);
53             if (rate == null) {
54                 logger.warn("Input value '{}' could not be converted to a valid number or country code", valueString);
55                 throw new TransformationException("VAT Transformation can only be used with numeric inputs", e);
56             }
57             value = new BigDecimal(rate);
58         }
59
60         return addVAT(source, value).toString();
61     }
62
63     private QuantityType<?> addVAT(QuantityType<?> source, BigDecimal percentage) {
64         return source.multiply(percentage.divide(new BigDecimal("100")).add(BigDecimal.ONE));
65     }
66 }