VocabularyTermServiceImpl.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.service.impl;

import lombok.extern.slf4j.Slf4j;

import java.util.Locale;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.genesys.server.exception.InvalidApiUsageException;
import org.genesys.server.model.filters.VocabularyTermFilter;
import org.genesys.server.model.vocab.VocabularyTerm;
import org.genesys.server.model.vocab.VocabularyTermLang;
import org.genesys.server.persistence.VocabularyTermLangRepository;
import org.genesys.server.persistence.vocab.VocabularyTermRepository;
import org.genesys.server.service.TranslatorService;
import org.genesys.server.service.TranslatorService.FormattedText;
import org.genesys.server.service.TranslatorService.TextFormat;
import org.genesys.server.service.VocabularyTermService;
import org.genesys.server.service.VocabularyTermTranslationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

@Slf4j
@Service("vocabularyTermServiceImpl")
@Transactional(readOnly = true)
@Validated
public class VocabularyTermServiceImpl extends FilteredTranslatedCRUDServiceImpl<
	VocabularyTerm, VocabularyTermLang, VocabularyTermTranslationService.TranslatedVocabularyTerm, VocabularyTermFilter, VocabularyTermRepository>
	implements VocabularyTermService {

	@Autowired(required = false)
	private TranslatorService translatorService;

	@Component(value = "VocabularyTermTranslationSupport")
	protected static class VocabularyTermTranslationSupport
		extends BaseTranslationSupport<
		VocabularyTerm, VocabularyTermLang, VocabularyTermTranslationService.TranslatedVocabularyTerm, VocabularyTermFilter, VocabularyTermLangRepository>
		implements VocabularyTermTranslationService {

	}
	
	@Override
	@Transactional
	@PreAuthorize("hasRole('ADMINISTRATOR') or (#target.vocabulary != null and hasPermission(#target.vocabulary, 'write')) or (#target.descriptor != null and hasPermission(#target.descriptor, 'write'))")
	public VocabularyTerm updateFast(VocabularyTerm updated, VocabularyTerm target) {
		target.apply(updated);
		return repository.save(target);
	}

	@Override
	@Transactional
	@PreAuthorize("hasRole('ADMINISTRATOR') or (#source.vocabulary != null and hasPermission(#source.vocabulary, 'write')) or (#source.descriptor != null and hasPermission(#source.descriptor, 'write'))")
	public VocabularyTerm create(VocabularyTerm source) {
		VocabularyTerm term = new VocabularyTerm();
		term.apply(source);
		return repository.save(term);
	}

	@Override
	@Transactional
	@PreAuthorize("hasRole('ADMINISTRATOR') or (#source.vocabulary != null and hasPermission(#source.vocabulary, 'write')) or (#source.descriptor != null and hasPermission(#source.descriptor, 'write'))")
	public VocabularyTerm createFast(VocabularyTerm source) {
		return super.createFast(source);
	}

	@Override
	@Transactional
	@PreAuthorize("hasRole('ADMINISTRATOR') or (#target.vocabulary != null and hasPermission(#target.vocabulary, 'write')) or (#target.descriptor != null and hasPermission(#target.descriptor, 'write'))")
	public VocabularyTerm update(VocabularyTerm updated, VocabularyTerm target) {
		return _lazyLoad(updateFast(updated, target));
	}

	@Override
	@PreAuthorize("hasRole('ADMINISTRATOR') or (#original.vocabulary != null and hasPermission(#original.vocabulary, 'write')) or (#original.descriptor != null and hasPermission(#original.descriptor, 'write'))")
	public VocabularyTermLang machineTranslate(VocabularyTerm original, String targetLanguage) throws TranslatorService.TranslatorException {
		var mt = new VocabularyTermLang();
		mt.setMachineTranslated(true);
		mt.setLanguageTag(targetLanguage);
		mt.setEntity(original);

		if (translatorService == null) return mt;

		var builder = TranslatorService.TranslationStructuredRequest.builder()
			.targetLang(targetLanguage);

		if (! Objects.equals(Locale.ENGLISH.getLanguage(), targetLanguage) && ! Objects.equals(Locale.ENGLISH.getLanguage(), original.getOriginalLanguageTag())) {
			// Translations to other languages use the English version (either original or translated)
			var enTranslation = translationSupport.getLang(original, Locale.ENGLISH.getLanguage());
			if (enTranslation == null) {
				throw new InvalidApiUsageException("English text is not available.");
			}

			builder
				.sourceLang(enTranslation.getLanguageTag())
				.context(buildTranslationContext(VocabularyTerm.class, "title", enTranslation.getTitle(), Locale.ENGLISH))
				.texts(Map.of(
					"title", new FormattedText(TextFormat.markdown, enTranslation.getTitle()),
					"description", new FormattedText(TextFormat.markdown, enTranslation.getDescription())
				));

		} else {
			// Translations to English use the original texts
			var originLocale = Locale.forLanguageTag(original.getOriginalLanguageTag());
			builder
				.sourceLang(original.getOriginalLanguageTag())
				.context(buildTranslationContext(VocabularyTerm.class, "title", original.getTitle(), originLocale))
				.texts(Map.of(
					"title", new FormattedText(TextFormat.markdown, original.getTitle()),
					"description", new FormattedText(TextFormat.markdown, original.getDescription())
				));
		}

		var translations = translatorService.translate(builder.build());

		if (StringUtils.isNotBlank(original.getTitle())) {
			mt.setTitle(translations.getTexts().get("title"));
		}
		if (StringUtils.isNotBlank(original.getDescription())) {
			mt.setDescription(translations.getTexts().get("description"));
		}
		return mt;
	}
}