TranslatedCRUDController.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;

import com.querydsl.core.types.OrderSpecifier;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.apache.commons.lang3.ArrayUtils;
import org.genesys.blocks.model.BasicModel;
import org.genesys.blocks.model.filters.EmptyModelFilter;
import org.genesys.server.api.ApiBaseController;
import org.genesys.server.api.FilteredPage;
import org.genesys.server.api.Pagination;
import org.genesys.server.api.v2.facade.APIFilteredTranslatedServiceFacade;
import org.genesys.server.api.v2.model.LangModelDTO;
import org.genesys.server.api.v2.model.Translated;
import org.genesys.server.exception.SearchException;
import org.genesys.server.model.impl.LangModel;
import org.genesys.server.service.ShortFilterService;
import org.genesys.server.service.ShortFilterService.FilterInfo;
import org.genesys.server.service.TranslatorService.TranslatorException;
import org.genesys.server.service.worker.ShortFilterProcessor;
import org.genesys.spring.validation.javax.SupportedLanguage;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public abstract class TranslatedCRUDController<DTO, TDTO extends Translated<DTO, LDTO>, LDTO extends LangModelDTO, E extends BasicModel, L extends LangModel<L, E>,
	SF extends APIFilteredTranslatedServiceFacade<DTO, TDTO, LDTO, E, L, F>, F extends EmptyModelFilter<F, E>>
	extends ApiBaseController {

	public static final String ENDPOINT_ID = "/{id:\\d+}";

	@SuppressWarnings("unchecked")
	private final Class<F> filterType = ((Class<F>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[6]);

	@Autowired
	private ShortFilterService shortFilterService;

	@Autowired
	private ShortFilterProcessor shortFilterProcessor;

	@Autowired
	protected SF translatedApiService;

	/**
	 * Get normalized filter from filterCode or filter body. Filter by code takes precedence over filter object.
	 * 
	 * @param filterCode filter code takes precedence and loads an existing filter
	 * @param filter filter
	 * @return normalized filter info
	 */
	protected final FilterInfo<F> processFilter(String filterCode, F filter, Class<F> filterType) throws IOException {
		return shortFilterProcessor.processFilter(filterCode, filter, filterType);
	}

	/**
	 * Get normalized filter from filterCode or filter body. Filter by code takes precedence over filter object.
	 * 
	 * @param filterCode filter code takes precedence and loads an existing filter
	 * @param filter filter
	 * @param filterType filter type
	 * @return normalized filter info
	 */
	protected final F normalizeFilter(F filter, Class<F> filterType) throws IOException {
		return shortFilterService.normalizeFilter(filter, filterType);
	}


	@GetMapping(value = ENDPOINT_ID, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "get", description = "Get translated record by ID", summary = "Get")
	public TDTO get(@PathVariable("id") @Parameter(description = "Entity ID") final long id) {
		return translatedApiService.loadTranslated(id);
	}

	/**
	 * Remove the entity.
	 *
	 * @param id the id
	 * @return the removed record
	 */
	@DeleteMapping(value = ENDPOINT_ID, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "remove", description = "Delete existing record by ID", summary = "Delete")
	public DTO remove(@PathVariable("id") @Parameter(description = "Entity ID") final long id) {
		return translatedApiService.remove(translatedApiService.get(id));
	}

	/**
	 * Register a new entity.
	 *
	 * @param entity the site
	 * @return the recorded record
	 */
	@PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "create", description = "Create a record with translation", summary = "Add")
	public DTO create(@RequestBody @Valid @NotNull final DTO entity) {
		return translatedApiService.create(entity);
	}

	// NOTE: Genesys stores original texts in entity E
	// /**
	//  * Register a new entity.
	//  *
	//  * @param entity the site
	//  * @return the recorded record
	//  */
	// @PostMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	// @Operation(operationId = "create", description = "Create a record with translation", summary = "Add")
	// public TDTO create(@RequestBody @Valid @NotNull final TDTO entity) {
	// 	return translatedApiService.loadTranslated(translatedApiService.createTranslated(entity).getEntity().getId());
	// }

	/**
	 * Update the entity.
	 *
	 * @param entity entity with updates
	 * @return the updated record
	 */
	@PutMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "update", description = "Update an existing record", summary = "Update")
	public DTO update(@RequestBody @Valid @NotNull final DTO entity) {
		return translatedApiService.update(entity);
	}

	/**
	 * Get filtered list of entities.
	 *
	 * @param page the page
	 * @param filter the filter
	 * @return the page
	 * @throws SearchException
	 */
	@PostMapping(value = FilteredCRUDController.ENDPOINT_LIST, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter", summary = "List by filter")
	public FilteredPage<TDTO, F> list(@ParameterObject final Pagination page, @RequestBody(required = false) final F filter) throws SearchException, IOException {

		var cleanFilter = normalizeFilter(filter, filterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(cleanFilter, translatedApiService.listFiltered(cleanFilter, pageable));
	}

	/**
	 * Get filtered list of entities by filterCode or filter.
	 *
	 * @param page the page
	 * @param filterCode short filter code
	 * @param filter the filter
	 * @return the page
	 * @throws IOException
	 * @throws SearchException 
	 */
	@PostMapping(value = FilteredCRUDController.ENDPOINT_FILTER, produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(description = "Retrieve list of records matching the filter or filter code", summary = "List by filter code or filter")
	public FilteredPage<TDTO, F> filter(@RequestParam(name = "f", required = false) String filterCode, @ParameterObject Pagination page,
			@RequestBody(required = false) F filter) throws IOException, SearchException {

		var filterInfo = processFilter(filterCode, filter, filterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(filterInfo.filterCode, filterInfo.filter, translatedApiService.listFiltered(filterInfo.filter, pageable));
	}

	/**
	 * Default order specifier for this entity.
	 *
	 * @return the order specifier
	 */
	protected OrderSpecifier<?>[] defaultSort() {
		return null;
	}

	/**
	 * Gets the langs.
	 *
	 * @param entityId the source descriptor id
	 * @return the langs
	 */
	@GetMapping(value = "/{id:\\d+}/langs", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId="getTranslations", description = "Get translations for all languages by entity id", summary = "List of translations")
	public List<LDTO> listTranslations(@PathVariable("id") @Parameter(description = "Entity ID") final long entityId) {
		return translatedApiService.listTranslations(entityId);
	}

	/**
	 * Generate a machine translation
	 *
	 * @param entityId the record id
	 * @return Target language
	 * @throws TranslatorException 
	 */
	@GetMapping(value = "/{id:\\d+}/translate/{lang}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "machineTranslate", description = "Generate machine translation by entity id and language", summary = "Machine translate")
	public LDTO machineTranslate(@PathVariable("id") final long entityId, @PathVariable("lang") @Parameter(description = "Language tag") @SupportedLanguage final String languageTag) throws TranslatorException {
		return translatedApiService.machineTranslate(entityId, languageTag);
	}

	/**
	 * Removes the source descriptor lang.
	 *
	 * @param entityId the source descriptor id
	 * @return the source descriptor lang
	 */
	@PutMapping(value = "/{id:\\d+}/lang", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "upsertTranslation", description = "Insert or update translation by entity id and language", summary = "Update translation")
	public LDTO upsertTranslation(@PathVariable("id") @Parameter(description = "Entity ID") final long entityId, @RequestBody @NotNull LDTO input) {
		return translatedApiService.upsertTranslation(translatedApiService.get(entityId), input);
	}

	/**
	 * Removes the source descriptor lang.
	 *
	 * @param entityId the source descriptor id
	 * @return the source descriptor lang
	 */
	@DeleteMapping(value = "/{id:\\d+}/lang/{lang}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "removeTranslation", description = "Delete translation by entity id and language", summary = "Delete translation")
	public LDTO removeTranslation(@PathVariable("id") final long entityId, @PathVariable("lang") @Parameter(description = "Language tag") final String languageTag) {
		return translatedApiService.removeTranslation(translatedApiService.get(entityId), languageTag);
	}

	/**
	 * Remove many.
	 *
	 * @param deletes the entities to remove
	 * @return the {@link MultiOp} response
	 */
	@DeleteMapping(value = "/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "removeMany", description = "Delete existing records", summary = "Delete many")
	public MultiOp<DTO> removeMany(@RequestBody @Valid @NotNull final List<DTO> deletes) {
		return MultiOp.multiOp(deletes, translatedApiService::remove, translatedApiService::remove);
	}
}