InventoryViabilityApiServiceImpl.java

/*
 * Copyright 2024 Global Crop Diversity Trust
 *
 * 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.gringlobal.api.v2.facade.impl;

import java.io.OutputStreamWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.api.model.InventoryViabilityDTO;
import org.gringlobal.api.model.InventoryViabilityDetailsDTO;
import org.gringlobal.api.model.OrderRequestDTO;
import org.gringlobal.api.v2.facade.InventoryViabilityApiService;
import org.gringlobal.api.v2.impl.InventoryViabilityController.ViabilityOrderRequest;
import org.gringlobal.model.Inventory;
import org.gringlobal.model.InventoryViability;
import org.gringlobal.model.InventoryViabilityRule;
import org.gringlobal.persistence.InventoryRepository;
import org.gringlobal.persistence.InventoryViabilityRuleRepository;
import org.gringlobal.service.CRUDService;
import org.gringlobal.service.InventoryViabilityService;
import org.gringlobal.service.filter.InventoryViabilityFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

@Service
public class InventoryViabilityApiServiceImpl extends APIFilteredServiceFacadeImpl<InventoryViabilityService, InventoryViabilityDTO, InventoryViability, InventoryViabilityFilter> implements InventoryViabilityApiService {

	@Autowired
	private InventoryRepository inventoryRepository;
	@Autowired
	private InventoryViabilityRuleRepository inventoryViabilityRuleRepository;

	@Override
	protected InventoryViability convert(InventoryViabilityDTO source) {
		return mapper.map(source);
	}

	@Override
	protected InventoryViabilityDTO convert(InventoryViability source) {
		return mapper.map(source);
	}

	@Override
	@Transactional
	public OrderRequestDTO orderViabilityTest(@Valid ViabilityOrderRequest viabilityOrderRequest) {
		List<Inventory> inventories = inventoryRepository.findAllById(viabilityOrderRequest.inventories.keySet());
		if (inventories.size() != viabilityOrderRequest.inventories.size()) {
			throw new InvalidApiUsageException("Specified inventory does not exist");
		}
		var viabilityRuleIds = Set.copyOf(viabilityOrderRequest.inventories.values());
		List<InventoryViabilityRule> viabilityRules = inventoryViabilityRuleRepository.findAllById(viabilityRuleIds);
		if (viabilityRules.size() != viabilityRuleIds.size()) {
			throw new InvalidApiUsageException("Specified vability rule does not exist");
		}

		var inventoryLookup = inventories.stream().collect(Collectors.toMap(Inventory::getId, Function.identity()));
		var ruleLookup = viabilityRules.stream().collect(Collectors.toMap(InventoryViabilityRule::getId, Function.identity()));

		Map<Inventory, InventoryViabilityRule> inventoriesAndRules = viabilityOrderRequest.inventories.entrySet().stream()
				// map
				.collect(Collectors.toMap((entry) -> inventoryLookup.get(entry.getKey()), (entry) -> ruleLookup.get(entry.getValue())));

		return mapper.map(service.orderViabilityTest(viabilityOrderRequest.site, inventoriesAndRules, viabilityOrderRequest.cooperator));
	}

	@Override
	public InventoryViabilityDetailsDTO calculateResult(final long id, List<Integer> selectedReplicationNumbers) {
		return mapper.map(service.calculateResult(service.get(id), selectedReplicationNumbers));
	}

	@Override
	@Transactional(readOnly = true)
	public InventoryViabilityDetailsDTO loadDetails(long id) {
		return mapper.map(service.loadDetails(service.get(id)));
	}

	@Override
	public ResponseEntity<StreamingResponseBody> generateLabels(CRUDService.LabelConfig labelConfig, List<Long> ids) {
		return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(out -> {
			var w = new OutputStreamWriter(out, "UTF8");
			service.generateLabels(labelConfig, ids, w);
			w.flush();
		});
	}

	@Override
	public ResponseEntity<StreamingResponseBody> generateLabels(Map<Long, CRUDService.LabelConfig> labelConfig) {
		return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(out -> {
			var w = new OutputStreamWriter(out, "UTF8");
			service.generateLabels(labelConfig, w);
			w.flush();
		});
	}

}