TaxonomySpecies.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.model;

import static org.gringlobal.model.community.CommunityCodeValues.CODE_VALUE_LENGTH;

import java.time.Instant;
import java.util.List;
import java.util.Objects;
import javax.persistence.*;

import org.genesys.blocks.model.Copyable;

import org.gringlobal.compatibility.LookupDisplay;
import org.gringlobal.component.elastic.ElasticLoader;
import org.gringlobal.custom.elasticsearch.SearchField;
import org.gringlobal.custom.validation.javax.CodeValueField;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.apache.commons.lang3.StringUtils;

/**
 * Auto-generated by:
 * org.apache.openjpa.jdbc.meta.ReverseMappingTool$AnnotatedCodeGenerator
 */
@Entity
@Cacheable
@Table(name = "taxonomy_species")
@Document(indexName = "taxonomyspecies")
@JsonIdentityInfo(scope = TaxonomySpecies.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Getter
@Setter
@ToString(doNotUseGetters = true, callSuper = false, exclude = { "currentTaxonomySpecies", "curator1Cooperator", "curator2Cooperator", "priority1Site", "priority2Site", "taxonomyGenus", "verifierCooperator", "taxonomyCrops" })
@NoArgsConstructor
@LookupDisplay(template = "case when exists (select id from TaxonomySpecies ts2 where ts2.name = t.name and ts2.id != t.id) then concat(t.name, concat(' ', coalesce(t.nameAuthority, ''))) else t.name end") // JPQL root uses alias 't'
public class TaxonomySpecies extends CooperatorOwnedModel implements Copyable<TaxonomySpecies>, ElasticLoader {

	private static final long serialVersionUID = -5958397094175847499L;

	public static final String PREFIX_SUBSPECIES = "subsp. ";
	public static final String PREFIX_NOTHOSUBSPECIES = "nothosubsp. ";
	public static final String PREFIX_VARIETY = "var. ";
	public static final String PREFIX_SUBVARIETY = "subvar. ";
	public static final String PREFIX_FORMA = "f.";

	/** Taxonomy Species ID. */
	@Id
	@JsonProperty
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "taxonomy_species_id", columnDefinition = "int")
	private Long id;

	// Keep this field here!
	/** GRIN Taxonomy Species ID: The id of this name in USDA GRIN Taxonomy. */
	@Column(name = "grin_species_id")
	private Long grinId;


	/** Taxon: The binomial or trinomial representation of the taxon name. */
	@Basic
	@Column(nullable = false, length = 100) // In DTO this is not requried and we calculate it automatically when null.
	@SearchField
	private String name;

	/** Taxon Authority: The author for the lowest ranking part of the taxon name. */
	@Basic
	@Column(name = "name_authority", length = 100)
	private String nameAuthority;

	/** Alternate Name: An alternative group name for this taxon under the International Code of Nomenclature for Cultivated Plants. */
	@Basic
	@Column(name = "alternate_name", length = 2000)
	private String alternateName;

	/** Hybrid Parentage: The hybrid parentage of the taxon. */
	@Basic
	@Column(name = "hybrid_parentage", length = 500)
	private String hybridParentage;

	/** TaxonomyGenus: Reference to the extended genus described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.EAGER, cascade = {})
	@JoinColumn(name = "taxonomy_genus_id", nullable = false)
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "ownedBy" })
	private TaxonomyGenus taxonomyGenus;

	/** Species: The specific epithet of the taxonomic species name. */
	@Basic
	@Column(name = "species_name", nullable = false, length = 30)
	private String speciesName;

	/** Species Authority: The author of the species name. */
	@Basic
	@Column(name = "species_authority", length = 100)
	private String speciesAuthority;

	/** Is Interspecific Hybrid?: A code to indicate an interspecific hybrid within the genus. */
	@Basic
	@Column(name = "is_specific_hybrid", nullable = false, length = 1)
	private String isSpecificHybrid = "N";

	/** Subspecies: The subspecific epithet for the taxon. */
	@Basic
	@Column(name = "subspecies_name", length = 30)
	private String subspeciesName;

	/** Subspecies Authority: The author of the subspecies name. */
	@Basic
	@Column(name = "subspecies_authority", length = 100)
	private String subspeciesAuthority;

	/** Is Subspecific Hybrid?: Y/N code indicates an intersubspecific hybrid within the species. */
	@Basic
	@Column(name = "is_subspecific_hybrid", nullable = false, length = 1)
	private String isSubspecificHybrid = "N";

	/** Variety: The varietal epithet for the taxon. */
	@Basic
	@Column(name = "variety_name", length = 30)
	private String varietyName;

	/** Variety Authority: The author of the varietal name. */
	@Basic
	@Column(name = "variety_authority", length = 100)
	private String varietyAuthority;

	/** Is Intervarietal Hybrid?: Y/N code indicates an intervarietal hybrid within the species. */
	@Basic
	@Column(name = "is_varietal_hybrid", nullable = false, length = 1)
	private String isVarietalHybrid = "N";

	/** Subvariety: The subvarietal epithet for the taxon. */
	@Basic
	@Column(name = "subvariety_name", length = 30)
	private String subvarietyName;

	/** Subvarietal Authority: The author of the subvarietal epithet. */
	@Basic
	@Column(name = "subvariety_authority", length = 100)
	private String subvarietyAuthority;

	/** Is Subvarietal Hybrid?: Y/N code indicates an intersubvarietal hybrid within the species. */
	@Basic
	@Column(name = "is_subvarietal_hybrid", nullable = false, length = 1)
	private String isSubvarietalHybrid = "N";

	/** Forma Rank: The rank indicator for the forma epithet. */
	@Basic
	@Column(name = "forma_rank_type", length = 30)
	private String formaRankType;

	/** Forma: The forma or other unranked epithet for the taxon. */
	@Basic
	@Column(name = "forma_name", length = 30)
	private String formaName;

	/** Forma Authority: The author string for the forma or other epithet. */
	@Basic
	@Column(name = "forma_authority", length = 100)
	private String formaAuthority;

	/** Is Forma Hybrid?: Y/N code indicates an interforma hybrid within the species. */
	@Basic
	@Column(name = "is_forma_hybrid", nullable = false, length = 1)
	private String isFormaHybrid = "N";

	/** Life Form: The normal life form of the species. Uses ACCESSION_LIFE_FORM vocabulary. */
	@Basic
	@Column(name = "life_form_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "ACCESSION_LIFE_FORM", strict = false)
	private String lifeFormCode;

	/** Nomen Number: The taxonomic species number. No decimals; whole numbers only. */
	@Basic
	@Column(name = "nomen_number")
	private Integer nomenNumber;

	/** Is Name Pending?: Y/N flag indicating the status of the name is in question. */
	@Basic
	@Column(name = "is_name_pending", nullable = false, length = 1)
	private String isNamePending = "N";

	/** Cooperator: Reference to the name-verifying cooperator described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "verifier_cooperator_id")
	@Field(type = FieldType.Object)
	private Cooperator verifierCooperator;

	/** Name Verification Date: Date when the name was verified. */
	@Basic
	@Column(name = "name_verified_date")
	private Instant nameVerifiedDate;

	/** Common Fertilization: The type of fertilization that is common in this species. Uses TAXONOMY_FERTILIZATION_METHOD vocabulary. */
	@Basic
	@Column(name = "common_fertilization_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "TAXONOMY_FERTILIZATION_METHOD", strict = false)
	private String commonFertilizationCode;

	/** Restriction: Restrictions on the taxon that may affect distributions of accessions. Uses TAXONOMY_RESTRICTION vocabulary. */
	@Basic
	@Column(name = "restriction_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "TAXONOMY_RESTRICTION", strict = false)
	private String restrictionCode;

	/** Synonym Code: A code to indicate the type of synonym. Uses TAXONOMY_SPECIES_QUALIFIER vocabulary. */
	@Basic
	@Column(name = "synonym_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "TAXONOMY_SPECIES_QUALIFIER", strict = false)
	private String synonymCode;

	// Keep this field here
	/** TaxonomySpecies: Reference to the current taxon described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "current_taxonomy_species_id")
	@JsonIdentityInfo(scope = TaxonomySpecies.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
	@JsonIdentityReference(alwaysAsId = true)
	@Field(index = false, type = FieldType.Long)
	private TaxonomySpecies currentTaxonomySpecies;

	/** Cooperator: Reference to the first curator described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "curator1_cooperator_id")
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy", "note", "geography", "secondaryGeography", "webCooperator" })
	@JsonIdentityReference(alwaysAsId = false)
	private Cooperator curator1Cooperator;

	/** Cooperator: Reference to the second curator described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "curator2_cooperator_id")
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy", "note", "geography", "secondaryGeography", "webCooperator" })
	@JsonIdentityReference(alwaysAsId = false)
	private Cooperator curator2Cooperator;

	/** Site: Reference to the first priority maintenance site described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "priority1_site_id")
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy" })
	private Site priority1Site;

	/** Site: Reference to the second priority maintenance site described by this taxonomy species. */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "priority2_site_id")
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy" })
	private Site priority2Site;

	/** Site Note: General remarks about the taxonomic species or infraspecies provided by the maintenance institute. */
	@Basic
	@Column(name = "site_note")
	@Lob
	private String siteNote;

	/** Protologue: The original literature reference for the species. */
	@Basic
	@Column(length = 500)
	private String protologue;

	/** Protologue Link: Link to protologue description on the web. */
	@Basic
	@Column(name = "protologue_virtual_path")
	private String protologueVirtualPath;

	/** Is Web Visible?: Whether this taxonomy species is visible on the web. */
	@Basic
	@Column(name = "is_web_visible", nullable = false, length = 1)
	private String isWebVisible = "N";

	/** Note: Generic comments about the taxonomic species. */
	@Basic
	@Column
	@Lob
	private String note;

	/** TaxonomyCropMap: The crop maps for this taxonomy species. */
	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "taxonomySpecies")
	@JsonIgnore
	private List<TaxonomyCropMap> taxonomyCrops;

	@PrePersist
	@PreUpdate
	private void updateName() {
		if (StringUtils.isBlank(this.name)) { // Update name if not specified
			this.name = this.taxonomyGenus.getName();
			this.name += (Objects.equals(this.isSpecificHybrid, "Y") ? " x " : " ") + this.speciesName;

			var subTaxon = getSubTaxon();
			if (subTaxon != null) {
				this.name += " " + subTaxon;
			}

			this.name = this.name.strip().replaceAll("\\s+", " "); // strip and replace whitespaces with single whitespace
		}

		if (StringUtils.isBlank(this.nameAuthority)) { // Update nameAuthority if not specified
			this.nameAuthority = this.speciesAuthority;

			if (StringUtils.isNotBlank(this.subspeciesName)) {
				this.nameAuthority = this.subspeciesAuthority;
			}
			if (StringUtils.isNotBlank(this.varietyName)) {
				this.nameAuthority = this.varietyAuthority;
			}
			if (StringUtils.isNotBlank(this.subvarietyName)) {
				this.nameAuthority = this.subvarietyAuthority;
			}
			if (StringUtils.isNotBlank(this.formaName)) {
				this.nameAuthority = this.formaAuthority;
			}
		}
	}

	@Transient
	@JsonIgnore
	public String getSubTaxon() {
		StringBuilder sb = new StringBuilder(50);
		if (StringUtils.isNotBlank(this.subspeciesName)) {
			if ("Y".equals(isSubspecificHybrid)) {
				sb.append(" ").append(PREFIX_NOTHOSUBSPECIES).append(subspeciesName);
			} else {
				sb.append(" ").append(PREFIX_SUBSPECIES).append(this.subspeciesName);
			}
		}

		if (StringUtils.isNotBlank(this.varietyName)) {
			sb.append(" ").append(PREFIX_VARIETY).append(this.varietyName);
		}

		if (StringUtils.isNotBlank(this.subvarietyName)) {
			sb.append(" ").append(PREFIX_SUBVARIETY).append(this.subvarietyName);
		}

		if (StringUtils.isNotBlank(this.formaName)) {
			sb.append(" ").append(this.formaRankType).append(" ").append(this.formaName);
		}

		return StringUtils.trimToNull(sb.toString());
	}

	/**
	 * Get specific epithet including Ă— for hybrids. Example: "Ă—acuminata"
	 *
	 * @return
	 */
	@Transient
	public String getSpecificEpithet() {
		return (Objects.equals(this.isSpecificHybrid, "Y") ? "x " : "") + this.speciesName;
	}

	public TaxonomySpecies(final Long id) {
		this.id = id;
	}

	/**
	 * Find and return the {@code name} of the first {@link Crop} this species is linked
	 * with.
	 *
	 * @return first {@code crop.name} or {@code null} if not linked to crop.
	 */
	@JsonIgnore
	public String reportCropName() {
		if (this.taxonomyCrops != null) {
			if (this.taxonomyCrops.size() > 0) {
				var first = this.taxonomyCrops.get(0);
				if (first.getCrop() != null) {
					return first.getCrop().getName(); // not null
				}
			}
		}
		return null;
	}

	@Override
	public void lazyLoad() {
		super.lazyLoad();
		lazyLoad(this.getTaxonomyGenus());
		lazyLoad(this.getVerifierCooperator());
		lazyLoad(this.getPriority1Site());
		lazyLoad(this.getPriority2Site());
		lazyLoad(this.getCurator1Cooperator());
		lazyLoad(this.getCurator2Cooperator());
	}

	@Override
	public void prepareForIndexing() {
		this.lazyLoad();
	}

	@Override
	public boolean canEqual(Object other) {
		return other instanceof TaxonomySpecies;
	}
}