TransportUnitSynchronizerImpl.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.transport.impl;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.ameba.annotation.Measured;
import org.ameba.annotation.TxService;
import org.openwms.common.transport.api.messages.TransportUnitMO;
import org.openwms.wms.api.TimeProvider;
import org.openwms.wms.location.Location;
import org.openwms.wms.location.LocationPK;
import org.openwms.wms.location.LocationService;
import org.openwms.wms.transport.TransportUnit;
import org.openwms.wms.transport.TransportUnitService;
import org.openwms.wms.transport.TransportUnitSynchronizer;
import org.openwms.wms.transport.events.TransportUnitEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.retry.annotation.Retryable;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.ServiceLoader;

import static org.openwms.wms.transport.events.TransportUnitEvent.TransportUnitEventType.REQUEST;

/**
 * A TransportUnitSynchronizerImpl is a transactional Spring managed service to synchronize {@link TransportUnit} changes on the golden
 * source.
 *
 * @author Heiko Scherrer
 */
@Validated
@TxService
class TransportUnitSynchronizerImpl implements TransportUnitSynchronizer {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransportUnitSynchronizerImpl.class);
    private final TimeProvider timeProvider = ServiceLoader.load(TimeProvider.class).iterator().next();
    private final TransportUnitRepository repository;
    private final TransportUnitService transportUnitService;
    private final LocationService locationService;
    private final ApplicationEventPublisher publisher;

    TransportUnitSynchronizerImpl(TransportUnitRepository repository, TransportUnitService transportUnitService, LocationService locationService, ApplicationEventPublisher publisher) {
        this.repository = repository;
        this.transportUnitService = transportUnitService;
        this.locationService = locationService;
        this.publisher = publisher;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Retryable
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Measured
    public @NotNull TransportUnit synchronize(@NotNull TransportUnit transportUnit) {
        TransportUnit result;
        var optTU = transportUnitService.findOneBy(transportUnit.getTransportUnitBK().getValue());
        if (optTU.isPresent()) {
            var existing = optTU.get();
            var location = locationService.findByForeignPKey(transportUnit.getActualLocation().getForeignPKey());
            existing.setForeignPKey(transportUnit.getForeignPKey());
            existing.synchronizeActualLocationChange(location, transportUnit.getActualLocationDate());
            var currentNoTU = numberOfTransportUnits(location);
            if (!location.hasFreeSpaceAvailable(currentNoTU)) {
                LOGGER.warn("By configuration not allowed to move the TransportUnit [{}] to the Location [{}]. But doing anyway, because has been moved on golden source, the current number of TransportUnits [{}] exceeds the allowed number [{}]",
                        transportUnit.getTransportUnitBK(), location.getErpCode(), currentNoTU, location.getNoMaxTransportUnits()
                );
            }
            existing.setState(transportUnit.getState());
            existing.setHeight(transportUnit.getHeight());
            existing.setWidth(transportUnit.getWidth());
            existing.setLength(transportUnit.getLength());
            existing.setTarget(transportUnit.getTarget());
            existing.acknowledge();
            result = transportUnitService.save(existing);
            // Do not send event
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("TransportUnit with Barcode [{}] updated during synchronization", transportUnit.getTransportUnitBK());
            }
        } else {
            transportUnit.acknowledge();
            result = transportUnitService.create(transportUnit);
            // Do not send event
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("TransportUnit with Barcode [{}] created during synchronization", transportUnit.getTransportUnitBK());
            }
        }
        return result;
    }

    private int numberOfTransportUnits(Location location) {
        return repository.countByActualLocation(location);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void move(@NotBlank String foreignPKey, @NotBlank String actualLocationId, @NotNull LocalDateTime actualLocationDate) {
        var existing = repository.findByForeignPKey(foreignPKey);
        if (existing.isPresent()) {
            trackInventoryChange(existing.get().getActualLocation());
            existing.get().synchronizeActualLocationChange(
                    trackInventoryChange(locationService.findByBK(LocationPK.fromString(actualLocationId))),
                    actualLocationDate
            );
            repository.save(existing.get());
            // Do not send event, TU has been moved on golden source
        } else {
            requestInstance(foreignPKey);
        }
    }

    private Location trackInventoryChange(Location location) {
        if (location.getNoMaxTransportUnits() == 1) {
            location.setLastInventoryDate(timeProvider.nowAsZonedDateTime());
            location = locationService.save(location);
        }
        return location;
    }

    private void requestInstance(@NotEmpty String foreignPKey) {
        LOGGER.warn("TransportUnit with foreignPKey [{}] does not exist in Inventory Service, request a fresh instance!", foreignPKey);
        publisher.publishEvent(TransportUnitEvent.of(TransportUnit.newBuilder().foreignPKey(foreignPKey).build(), REQUEST));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void update(@NotNull TransportUnitMO mo) {
        LOGGER.debug("Update a TransportUnit to [{}]", mo);
        var existingOpt = repository.findByForeignPKey(mo.getpKey());
        if (existingOpt.isPresent()) {
            var existing = existingOpt.get();
            if (mo.hasTargetLocation()) {
                var targetLocation = locationService.findByBK(LocationPK.fromString(mo.getTargetLocation().id()));
                existing.setTarget(targetLocation.getErpCode());
            } else {
                existing.setTarget(null);
            }
            repository.save(existing);
            // Do not send event
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Measured
    public void changeState(@NotBlank String foreignPKey, @NotBlank String state) {
        LOGGER.debug("Change the state of the TransportUnit with foreignPKey [{}] to [{}]", foreignPKey, state);
        var existing = repository.findByForeignPKey(foreignPKey);
        if (existing.isPresent()) {
            existing.get().setState(state);
            repository.save(existing.get());
            // No event required!
        } else {
            requestInstance(foreignPKey);
        }
    }
}