UomMapper.java

/*
 * Copyright 2005-2025 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openwms.wms.inventory.impl;

import org.mapstruct.Mapper;
import org.openwms.wms.CycleAvoidingMappingContext;
import org.openwms.wms.inventory.DimensionMapper;
import org.openwms.wms.inventory.ProductMapper;
import org.openwms.wms.inventory.UomRelation;
import org.openwms.wms.inventory.api.UomRelationVO;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

/**
 * A UomMapper.
 *
 * @author Heiko Scherrer
 */
@Mapper
public abstract class UomMapper {

    private ProductMapper productMapper;
    private DimensionMapper dimensionMapper;
    private UomRelationRepository repository;

    @Autowired
    public void setProductMapper(ProductMapper productMapper) {
        this.productMapper = productMapper;
    }

    @Autowired
    public void setDimensionMapper(DimensionMapper dimensionMapper) {
        this.dimensionMapper = dimensionMapper;
    }

    @Autowired
    public void setRepository(UomRelationRepository repository) {
        this.repository = repository;
    }

    public UomRelationVO convertTo(UomRelation source) {
        if (source == null) {
            return null;
        }
        UomRelationVO vo = new UomRelationVO(
                source.getLabel(),
                source.getUnit(),
                dimensionMapper.convert(source.getDimension()),
                source.getDetails());
        vo.setProduct(productMapper.convert(source.getProduct(), new CycleAvoidingMappingContext()));
        return vo;
    }

    public UomRelation convertFrom(UomRelationVO source, UomRelation destination) {
        if (source == null) {
            return destination;
        }
        if (source.getProduct() != null && source.getQuantity() != null) {
            Optional<UomRelation> optionalUomRelation = repository.findByProduct_SkuAndUnit(source.getProduct().getSku(), source.getQuantity());
            if (optionalUomRelation.isPresent()) {
                return optionalUomRelation.get();
            }
        }
        UomRelation other = new UomRelation(source.getLabel(), source.getQuantity());
        if (source.getDimension() != null) {
            other.setDimension(dimensionMapper.convertVO(source.getDimension()));
        }
        if (source.getDetails() != null) {
            other.setDetails(source.getDetails());
        }
        return other;
    }
}