TemplateMoney.java

package org.freshmarker.money;

import ftl.Token.TokenType;
import org.freshmarker.core.ProcessContext;
import org.freshmarker.core.ProcessException;
import org.freshmarker.core.model.TemplateObject;
import org.freshmarker.core.model.primitive.TemplatePrimitive;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.spi.MoneyUtils;

public class TemplateMoney extends TemplatePrimitive<Money> {
    public TemplateMoney(Money value) {
        super(value);
    }

    @Override
    public TemplateObject operation(TokenType operator, TemplateObject operand, ProcessContext context) {
        TemplateMoney money = operand.evaluate(context, TemplateMoney.class);
        try {
            return switch (operator) {
                case PLUS -> new TemplateMoney(getValue().add(money.getValue()));
                case MINUS -> new TemplateMoney(getValue().subtract(money.getValue()));
                default -> super.operation(operator, operand, context);
            };
        } catch (RuntimeException e) {
            throw new ProcessException(e.getMessage(), e);
        }
    }

    @Override
    public boolean relation(TokenType operator, TemplateObject operand, ProcessContext context) {
        Money money = operand.evaluate(context, TemplateMoney.class).getValue();
        try {
            MoneyUtils.checkAmountParameter(money, getValue().getCurrency());
        } catch (RuntimeException e) {
            throw new ProcessException(e.getMessage(), e);
        }
        int compare = getValue().compareTo(money);
        return switch (operator) {
            case LT -> compare < 0;
            case GT -> compare > 0;
            case LTE -> compare <= 0;
            case GTE -> compare >= 0;
            default -> super.relation(operator, operand, context);
        };
    }
}