DescriptorController.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.genesys.server.api.v2.impl;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.model.RepositoryImage;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.FilteredPage;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v2.FilteredCRUDController;
import org.genesys.server.api.v2.TranslatedCRUDController;
import org.genesys.server.api.v2.facade.DescriptorApiService;
import org.genesys.server.api.v2.facade.DescriptorLangApiService;
import org.genesys.server.api.v2.facade.impl.DescriptorApiServiceImpl;
import org.genesys.server.api.v2.model.impl.DescriptorDTO;
import org.genesys.server.api.v2.model.impl.DescriptorLangDTO;
import org.genesys.server.api.v2.model.impl.TranslatedDescriptorDTO;
import org.genesys.server.component.aspect.DownloadEndpoint;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.server.exception.NotFoundElement;
import org.genesys.server.exception.SearchException;
import org.genesys.server.model.filters.DescriptorFilter;
import org.genesys.server.model.traits.Descriptor;
import org.genesys.server.model.traits.DescriptorLang;
import org.genesys.server.service.ShortFilterService;
import org.genesys.server.service.TranslatorService;
import org.genesys.server.service.filter.DescriptorLangFilter;
import org.genesys.server.service.worker.ShortFilterProcessor;
import org.genesys.server.service.worker.dupe.DuplicateFinder;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController("descriptorApi2")
@RequestMapping(DescriptorController.CONTROLLER_URL)
@Tag(name = "Descriptor")
public class DescriptorController extends TranslatedCRUDController<DescriptorDTO, TranslatedDescriptorDTO,
	DescriptorLangDTO, Descriptor, DescriptorLang, DescriptorApiService, DescriptorFilter> {

	/** The Constant CONTROLLER_URL. */
	public static final String CONTROLLER_URL = ApiBaseController.APIv2_BASE + "/descriptor";
	public static final String IMAGE_URL = "/{uuid:\\w{8}\\-\\w{4}.+}/image";

	/** The short filter service. */
	@Autowired
	private ShortFilterProcessor shortFilterProcessor;

	/**
	 * Gets the descriptor.
	 *
	 * @param uuid the uuid
	 * @return the descriptor
	 */
	@RequestMapping(value = "/{uuid:\\w{8}\\-\\w{4}.+}", method = RequestMethod.GET)
	public TranslatedDescriptorDTO getDescriptor(@PathVariable("uuid") final UUID uuid) {
		return translatedApiService.loadTranslatedDescriptor(uuid);
	}

	/**
	 * Delete descriptor.
	 *
	 * @param uuid the uuid
	 * @param version the version
	 * @return the descriptor
	 * @throws IOException
	 * @throws InvalidRepositoryPathException
	 * @throws NotFoundElement
	 */
	@DeleteMapping(value = "/{uuid:\\w{8}\\-\\w{4}.+},{version}")
	public DescriptorDTO deleteDescriptor(@PathVariable("uuid") final UUID uuid, @PathVariable("version") final int version) throws NotFoundElement, InvalidRepositoryPathException, IOException {
		try {
			return translatedApiService.removeDescriptor(translatedApiService.loadDescriptor(uuid, version));
		} catch (DataIntegrityViolationException e) {
			throw new InvalidApiUsageException("Cannot delete a referenced descriptor");
		}
	}

	/**
	 * Loads descriptor by uuid and version and tries to publish it.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return published Descriptor (admin-only)
	 */
	@RequestMapping(value = "/approve", method = RequestMethod.POST)
	public DescriptorDTO approveDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final DescriptorDTO descriptor = translatedApiService.loadDescriptor(uuid, version);
		return translatedApiService.approveDescriptor(descriptor);
	}

	/**
	 * Loads descriptor by uuid and version and send to review.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return descriptor in review state
	 */
	@RequestMapping(value = "/for-review", method = RequestMethod.POST)
	public DescriptorDTO reviewDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final DescriptorDTO descriptor = translatedApiService.loadDescriptor(uuid, version);
		return translatedApiService.reviewDescriptor(descriptor);
	}

	/**
	 * Loads descriptor by uuid and version and unpublish it.
	 *
	 * @param uuid descriptor UUID
	 * @param version record version
	 * @return unpublished descriptor
	 */
	@RequestMapping(value = "/reject", method = RequestMethod.POST)
	public DescriptorDTO rejectDescriptor(@RequestParam(value = "uuid", required = true) final UUID uuid, @RequestParam(value = "version", required = true) final int version) {
		final DescriptorDTO descriptor = translatedApiService.loadDescriptor(uuid, version);
		return translatedApiService.rejectDescriptor(descriptor);
	}

	/**
	 * List categories.
	 *
	 * @return the category[]
	 */
	@GetMapping(value = "/categories")
	public org.genesys.server.model.traits.Descriptor.Category[] listCategories() {
		return org.genesys.server.model.traits.Descriptor.Category.values();
	}

	/**
	 * Make a new version of a descriptor.
	 *
	 * @param major make a new major version
	 * @param source the descriptor to copy
	 * @return the descriptor
	 */
	@RequestMapping(value = "/copy", method = RequestMethod.POST)
	public DescriptorDTO copyDescriptor(@RequestParam(name = "major", defaultValue = "true", required = false) final boolean major, @RequestBody final DescriptorDTO source) {
		return translatedApiService.nextVersion(source, major);
	}

	/**
	 * Update descriptor.
	 *
	 * @param source the source
	 * @return the descriptor
	 */
	@RequestMapping(value = "/force-update", method = RequestMethod.POST)
	public DescriptorDTO forceUpdateDescriptor(@RequestBody final DescriptorDTO source) {
		return translatedApiService.forceUpdateDescriptor(source);
	}

	/**
	 * Update descriptor.
	 *
	 * @param source the source
	 * @return the list
	 */
	@RequestMapping(value = "/upsert", method = RequestMethod.POST)
	@PreAuthorize("hasRole('ADMINISTRATOR')")
	public List<DescriptorDTO> updateDescriptors(@RequestBody final List<DescriptorDTO> source) {
		return translatedApiService.upsertDescriptors(source);
	}

	@DownloadEndpoint
	@PostMapping(value = "/export", produces = { "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" })
	public void exportDescriptors(@RequestParam(name = "f", required = false) String filterCode,
		@RequestBody(required = false) DescriptorFilter filter, HttpServletResponse response) throws IOException {

		var filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);

		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.addHeader("Content-Disposition", String.format("attachment; filename=\"genesys-descriptors-" + filterInfo.filterCode + ".xlsx\""));
		response.flushBuffer();

		// Write XLSX to the stream.
		final OutputStream outputStream = response.getOutputStream();

		try {
			translatedApiService.exportDescriptors(filterInfo.filter, outputStream);
			response.flushBuffer();
		} catch (EOFException e) {
			LOG.warn("Download was aborted", e);
			throw e;
		}
	}

	/**
	 * List descriptors.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list")
	public FilteredPage<DescriptorDTO, DescriptorFilter> listDescriptors(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
		@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		ShortFilterService.FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * List descriptors details.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list/details")
	public FilteredPage<TranslatedDescriptorDTO, DescriptorFilter> listDescriptorsDetails(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
		@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		ShortFilterService.FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listDescriptorsDetails(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * List descriptors accessible to user
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list-accessible")
	public FilteredPage<DescriptorDTO, DescriptorFilter> listAccessibleDescriptors(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
		@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		ShortFilterService.FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listAccessibleDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * My descriptors.
	 *
	 * @param page the page
	 * @param filter the descriptor filter
	 * @return the page
	 * @throws IOException
	 */
	@PostMapping(value = "/list-mine")
	public FilteredPage<DescriptorDTO, DescriptorFilter> myDescriptors(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject final Pagination page,
		@RequestBody(required = false) DescriptorFilter filter) throws IOException, SearchException {

		ShortFilterService.FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listDescriptorsForCurrentUser(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.DESC, "lastModifiedDate")));
	}

	/**
	 * Filter descriptors by filter code.
	 *
	 * @param page the page
	 * @param filterCode the filter code
	 * @return the filtered page
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @deprecated Use {@link #listDescriptors(int, int, org.springframework.data.domain.Sort.Direction, String[], DescriptorFilter)}
	 */
	@Deprecated
	@PostMapping(value = "/list/{filterCode}")
	public FilteredPage<DescriptorDTO, DescriptorFilter> listDescriptorsByShort(@ParameterObject final Pagination page, @PathVariable("filterCode") final String filterCode) throws IOException, SearchException {
		final DescriptorFilter filter = shortFilterProcessor.filterByCode(filterCode, DescriptorFilter.class);
		ShortFilterService.FilterInfo<DescriptorFilter> filterInfo = shortFilterProcessor.processFilter(filterCode, filter, DescriptorFilter.class);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listDescriptors(filterInfo.filter, page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, Sort.Direction.ASC, "id")));
	}

	/**
	 * Search matching descriptors.
	 *
	 * @param source the source
	 * @return matching descriptors
	 */
	@RequestMapping(value = "/search-matching", method = RequestMethod.POST)
	public List<DescriptorDTO> searchMatchingDescriptor(@RequestBody final DescriptorDTO source) {
		return translatedApiService.searchMatchingDescriptor(source).stream().filter(d -> d != null).collect(Collectors.toList());
	}

	/**
	 * Get additional information about descriptor that is not provided in the
	 * {@link #getDescriptor(UUID)} call.
	 *
	 * @param uuid descriptor UUID
	 * @return the descriptor details
	 */
	@RequestMapping(value = "/{uuid:\\w{8}\\-\\w{4}.+}/details", method = RequestMethod.GET)
	public DescriptorApiService.DescriptorDetails getDescriptorDetails(@PathVariable("uuid") final UUID uuid) {
		return translatedApiService.getDescriptorDetails(uuid);
	}

	@PostMapping(value = IMAGE_URL)
	public DescriptorDTO updateImage(@PathVariable("uuid") final UUID descriptorUuid, @RequestPart(name = "image", required = true) final MultipartFile image,
		@RequestPart(name = "metadata", required = false) final RepositoryImage metadata) throws InvalidRepositoryPathException,
		InvalidRepositoryFileDataException, IOException, NotFoundElement, NoSuchRepositoryFileException {

		return translatedApiService.updateImage(translatedApiService.loadDescriptor(descriptorUuid), image, metadata);
	}

	@DeleteMapping(value = IMAGE_URL)
	public DescriptorDTO removeImage(@PathVariable("uuid") final UUID descriptorUuid) throws NoSuchRepositoryFileException, IOException, NotFoundElement, InvalidRepositoryPathException {
		return translatedApiService.removeImage(translatedApiService.loadDescriptor(descriptorUuid));
	}

	@PostMapping(value = "/find-similar", produces = MediaType.APPLICATION_JSON_VALUE)
	public List<DuplicateFinder.Hit<DescriptorDTO>> findSimilar(@RequestBody DescriptorApiServiceImpl.SimilarRequest similarRequest) {
		return translatedApiService.findSimilar(similarRequest);
	}

	/**
	 * Gets machine translation of the Descriptor
	 *
	 * @param uuid the Descriptor uuid
	 * @param languageTag target language tag
	 * @return DescriptorLangDTO
	 * @throws org.genesys.server.service.TranslatorService.TranslatorException
	 */
	@GetMapping(value = "/{uuid:\\w{8}\\-\\w{4}.+}/translate/{languageTag}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "machineTranslateByUUID", summary = "Machine translate", description = "Generate machine translation of the descriptor by uuid")
	public DescriptorLangDTO machineTranslate(
		@PathVariable @Parameter(description = "Descriptor UUID") final UUID uuid,
		@PathVariable @Parameter(description = "Target language tag") final String languageTag
	) throws TranslatorService.TranslatorException {
		return translatedApiService.machineTranslate(uuid, languageTag);
	}

	@RestController("descriptorLangApi2")
	@RequestMapping(DescriptorController.DescriptorLangController.API_URL)
	@PreAuthorize("isAuthenticated()")
	@Tag(name = "Descriptor")
	public static class DescriptorLangController extends FilteredCRUDController<DescriptorLangDTO, DescriptorLang, DescriptorLangApiService, DescriptorLangFilter> {
		/** The Constant API_URL. */
		public static final String API_URL = DescriptorController.CONTROLLER_URL + "/lang";
	}
}