TaxonomySpeciesApiServiceImpl.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.api.v2.facade.impl;

import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.gringlobal.api.model.TaxonomySpeciesDTO;
import org.gringlobal.api.model.TaxonomySpeciesInfo;
import org.gringlobal.api.v2.facade.TaxonomySpeciesApiService;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.QAccession;
import org.gringlobal.model.QTaxonomySpecies;
import org.gringlobal.model.TaxonomySpecies;
import org.gringlobal.service.TaxonomySpeciesCRUDService;
import org.gringlobal.service.filter.TaxonomySpeciesFilter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;

@Service
public class TaxonomySpeciesApiServiceImpl extends APIFilteredServiceFacadeImpl<TaxonomySpeciesCRUDService, TaxonomySpeciesDTO, TaxonomySpecies, TaxonomySpeciesFilter> implements TaxonomySpeciesApiService {

	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	protected @NotNull @Valid TaxonomySpecies convert(TaxonomySpeciesDTO source) {
		return mapper.map(source);
	}

	@Override
	protected @NotNull @Valid TaxonomySpeciesDTO convert(TaxonomySpecies source) {
		return mapper.map(source);
	}

	@Override
	@Transactional(readOnly = true)
	public List<TaxonomySpeciesInfo> autocomplete(String term) throws SearchException {
		term = term.trim();
		TaxonomySpeciesFilter filter = new TaxonomySpeciesFilter();
		Pageable pageable = PageRequest.of(0, 15, Sort.by("name"));
		if (!StringUtils.isBlank(term)) {
			// Find by name
			var qSpecies = QTaxonomySpecies.taxonomySpecies;
			var species = jpaQueryFactory
				.select(qSpecies)
				.from(qSpecies)
				.where(qSpecies.name.startsWithIgnoreCase(term))
				.orderBy(qSpecies.name.asc())
				.limit(15)
				.fetch();

			if (! CollectionUtils.isEmpty(species)) {
				return mapper.map(species, mapper::mapInfo);
			} else {
				filter._text(term + "*");
				return mapper.map(service.list(filter, pageable).getContent(), mapper::mapInfo);
			}

		} else {
			// Find most used taxonomy species based on accessions
			var qAccession = QAccession.accession;
			List<Long> speciesIds = jpaQueryFactory
				.select(qAccession.taxonomySpecies().id)
				.from(qAccession)
				.where(qAccession.taxonomySpecies().isNotNull())
				.groupBy(qAccession.taxonomySpecies().id)
				.orderBy(qAccession.taxonomySpecies().id.count().desc())
				.limit(15)
				.fetch();

			if (CollectionUtils.isEmpty(speciesIds)) {
				return mapper.map(service.list(filter, pageable).getContent(), mapper::mapInfo);
			}

			filter.id(new HashSet<>(speciesIds));
			var result = service.list(filter, pageable).getContent();
			// Preserve the order of the most-used in accessions
			result = result.stream().sorted(Comparator.comparingInt(a -> speciesIds.indexOf(a.getId()))).toList();
			return mapper.map(result, mapper::mapInfo);
		}
	}
}