Accession.java

/*
 * Copyright 2019 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.gringlobal.model;

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

import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.model.Copyable;
import org.genesys.blocks.model.JsonViews;
import org.gringlobal.compatibility.LookupDisplay;
import org.gringlobal.compatibility.SysTableFieldInfo;
import org.gringlobal.compatibility.SysTableInfo;
import org.gringlobal.component.GGCE;
import org.gringlobal.component.elastic.AppContextHelper;
import org.gringlobal.component.elastic.ElasticLoader;
import org.gringlobal.component.elastic.ElasticTrigger;
import org.gringlobal.custom.elasticsearch.BoostedFields;
import org.gringlobal.custom.elasticsearch.IgnoreField;
import org.gringlobal.custom.elasticsearch.SearchField;
import org.gringlobal.custom.validation.javax.SimpleString;
import org.gringlobal.custom.validation.javax.CodeValueField;
import org.gringlobal.custom.validation.javax.OneLine;
import org.gringlobal.model.community.CommunityCodeValues;
import org.gringlobal.model.community.IWebVisible;
import org.hibernate.annotations.Formula;
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.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@Entity
@Table(name = "accession")
@Document(indexName = "accession")
@BoostedFields({ "accessionNumber", "accessionNumberPart2", "taxonomySpecies.name", "names.plantName", "accessionSources.geography.countryCode" })
@JsonIdentityInfo(scope = Accession.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@SysTableInfo(area = "Accession")
@Getter
@Setter
@NoArgsConstructor
public class Accession extends CooperatorOwnedModel implements IWebVisible, Copyable<Accession>, ElasticLoader, ElasticTrigger {
	private static final long serialVersionUID = 480310287159463049L;

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

	/** Site responsible for accession passport data */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "site_id", nullable = false)
	@Field(type = FieldType.Object)
	private Site site;

	/** Accession number (unique) */
	@SearchField
	@Size(max = 128)
//	@JsonProperty(access = JsonProperty.Access.READ_ONLY) // Allow JSON input, but will be recalculated
	@Column(name = "accession_number", length = 128)
	@SysTableFieldInfo(readonly = true)
	@LookupDisplay
	private String accessionNumber;

	/** Status of accession in the MLS */
	@Size(max = CODE_VALUE_LENGTH)
	@Column(name = "mls_status", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = ACCESSION_MLS_STATUS, indexed = true)
	private String mlsStatus;

	/** Accession number prefix */
	@Basic
	@OneLine
	@NotNull
	@SimpleString
	// Handled by @SimpleString -- @Pattern(regexp = "(^$)|(^\\S+(?:\\s\\S+)*$)") // Blank string or a trimmed string that may contain single white space characters
	@Column(name = "accession_number_part1", nullable = false, length = 50)
	private String accessionNumberPart1;
	
	/** Accession sequential number (within prefix) */
	@Basic
	@Column(name = "accession_number_part2")
	private Long accessionNumberPart2;
	
	/** Accession number suffix */
	@Basic
	@OneLine
	@SimpleString
	@Column(name = "accession_number_part3", length = 50)
	private String accessionNumberPart3;

	/** Site of primary backup */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "backup_location1_site_id")
	private Site backupLocation1Site;
	
	/** Site of secondary backup */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "backup_location2_site_id")
	private Site backupLocation2Site;
	
	/** DOI assigned to the accession */
	@Basic
	@Column(length = 20)
	@OneLine
	@Pattern(regexp = "^10\\.[0-9]+(\\.[0-9]+)*/.+")
	private String doi;
	
	/** Level of germplasm improvement (e.g. landrace, advanced cultivar, etc.) */
	@Basic
	@Column(name = "improvement_status_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "IMPROVEMENT_LEVEL", indexed = true)
	private String improvementStatusCode;

	/** Date when the accession was acquired */
	@Basic
	@Column(name = "initial_received_date")
	private Date initialReceivedDate;

	/** Date format */
	@Basic
	@Column(name = "initial_received_date_code", length = CODE_VALUE_LENGTH)
	@CodeValueField("DATE_FORMAT")
	private String initialReceivedDateCode;
	
	/** Type of germplasm when initially received */
	@Basic
	@Column(name = "initial_received_form_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = CommunityCodeValues.GERMPLASM_FORM, indexed = true)
	private String initialReceivedFormCode;
	
	/** Is accession backed up? */
	@Basic
	@Column(name = "is_backed_up", nullable = false, length = 1)
	private String isBackedUp = "N";
	
	/** Is accession part of the core collection. Please ignore. */
	@Basic
	@Column(name = "is_core", nullable = false, length = 1)
	private String isCore = "N";

	/** May accession data be shared beyond the genebank? */
	@Basic
	@Column(name = "is_web_visible", nullable = false, length = 1)
	private String isWebVisible = "N";

	/** Life form */
	@Basic
	@Column(name = "life_form_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "ACCESSION_LIFE_FORM", indexed = true)
	private String lifeFormCode;

	@Basic
	@Column
	@Lob
	private String note;

	@Basic
	@Column(name = "reproductive_uniformity_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(value = "REPRODUCTIVE_UNIFORMITY", indexed = true)
	private String reproductiveUniformityCode;

	@Basic
	@Column(name = "status_code", nullable = false, length = CODE_VALUE_LENGTH)
	@CodeValueField(value = CommunityCodeValues.ACCESSION_STATUS, indexed = true)
	private String statusCode = CommunityCodeValues.ACCESSION_STATUS_INACTIVE.value;

	/** Type of curation applied to the accession */
	@Basic
	@Column(name = "curation_type_code", nullable = true, length = CODE_VALUE_LENGTH)
	@CodeValueField(value = CommunityCodeValues.ACCESSION_CURATION_TYPE, indexed = true)
	private String curationTypeCode;

	/** The genebank collection this accession is part of. Examples are Banana collection, Invitro collection, Field collection, etc. */
	@Basic
	@Column(name = "collection_code", nullable = false, length = CODE_VALUE_LENGTH)
	@CodeValueField(value = CommunityCodeValues.ACCESSION_COLLECTION, indexed = true)
	private String collectionCode = ACCESSION_COLLECTION_DEFAULT.value;

	/** Species */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "taxonomy_species_id", nullable = false)
	@Field(type = FieldType.Object)
	@JsonIgnoreProperties({ "currentTaxonomySpecies", "ownedBy", "verifierCooperator", "curator1Cooperator", "curator2Cooperator" })
	private TaxonomySpecies taxonomySpecies;

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	private List<Inventory> inventories;

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	@IgnoreField(false) // this includes the field in JSON serialization for ES
	@Field(type = FieldType.Nested)
	@JsonIgnoreProperties({ "ownedBy", "accession" })
	private List<AccessionSource> accessionSources;

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	private List<AccessionAction> accessionActions;

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	private List<AccessionIpr> accessionIprs;

	@OneToOne(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession", optional = true)
	@JsonIgnore
	private AccessionPedigree accessionPedigree;


	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	private List<AccessionQuarantine> accessionQuarantines;

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "accession")
	@JsonIgnore
	private List<Citation> citations;
	
	@Transient
	@JsonView({ JsonViews.Update.class })
	@IgnoreField(false) // this includes the field in JSON serialization for ES
	@Field(type = FieldType.Nested)
	@JsonIgnoreProperties({ "ownedBy", "inventory" })
	private List<AccessionInvName> names;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "exploration_id")
	private Exploration exploration;

	@Formula("(SELECT name.plant_name FROM inventory i INNER JOIN accession_inv_name name ON name.inventory_id = i.inventory_id " +
			"WHERE i.accession_id = accession_id AND i.form_type_code = '**' ORDER BY name.plant_name_rank OFFSET 0 ROWS FETCH FIRST 1 ROWS ONLY)")
	private String preferredName;

	@Override
	protected void prePersist() {
		super.prePersist();

		this.accessionNumberPart1 = StringUtils.trimToEmpty(this.accessionNumberPart1);
		this.accessionNumberPart3 = StringUtils.trimToNull(this.accessionNumberPart3);
		this.accessionNumber = GGCE.accessionNumber(this);
	}

	@PreUpdate
	protected void preUpdate() {
		this.accessionNumberPart1 = StringUtils.trimToEmpty(this.accessionNumberPart1);
		this.accessionNumberPart3 = StringUtils.trimToNull(this.accessionNumberPart3);
		this.accessionNumber = GGCE.accessionNumber(this);
	}

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

	public List<AccessionSource> getAccessionSources() {
		return accessionSources;
	}

	public void setAccessionSources(List<AccessionSource> accessionSources) {
		this.accessionSources = accessionSources;
	}
	
	@SearchField
	public String getAccessionNumber() {
		return accessionNumber;
	}
	
	@Transient
	public List<AccessionInvName> getNames() {
		return names;
	}

	/**
	 * Finds the first {@link AccessionSource} that is marked as `isOrigin` <b>AND</b> `isWebVisible` for this
	 * accession. This operation is available only within a {@code @Transactional}
	 * scope, like generating PDFs or other business logic.
	 * 
	 * @return the first {@link AccessionSource} that is marked as `isOrigin` and `isWebVisible`
	 */
	@JsonIgnore
	public Optional<AccessionSource> findOriginSource() {
		if (this.accessionSources != null && this.accessionSources.size() > 0) {
			return this.accessionSources.stream().filter(AccessionSource::isOrigin).filter(IWebVisible::isWebVisible).findFirst();
		}
		return Optional.empty();
	}

	@Override
	public void lazyLoad() {
		super.lazyLoad();
		lazyLoad(this.site);
		lazyLoad(this.taxonomySpecies);
		lazyLoad(this.backupLocation1Site);
		lazyLoad(this.backupLocation2Site);
	}

	@Override
	public void prepareForIndexing() {
		this.taxonomySpecies.lazyLoad();
		this.names = AppContextHelper.loadNames(this, Inventory.SYSTEM_INVENTORY_FTC); // only system inventory

		// Index accession sources
		this.accessionSources.size();
		this.accessionSources.forEach((accessionSource) -> {
			if (accessionSource != null && accessionSource.getIsOrigin().equals("Y") && accessionSource.getGeography() != null) {
				accessionSource.getGeography().getId();
			}
		});
	}

	@Override
	public Object[] reindexedEntities() {
		return getInventories() == null ? null : this.inventories.toArray();
	}

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