Location.java

/*
 * Copyright 2022 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.community;

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

import java.util.List;
import java.util.UUID;

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.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.genesys.blocks.model.Copyable;
import org.genesys.blocks.model.SelfCleaning;
import org.genesys.blocks.util.EntityIdSerializer;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.custom.validation.javax.CodeValueField;
import org.gringlobal.custom.validation.javax.SimpleString;
import org.gringlobal.model.CooperatorOwnedModel;
import org.gringlobal.model.Geography;
import org.gringlobal.model.Site;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * Location represents a physical place at a {@link Site}: buildings - rooms - racks, fields, greenhouses, etc.
 * Locations are organized into a tree structure where
 * each location with <code>parentLocation == null</code> starts a new tree at the {#link Site}.
 * Location may declare its {@link #capacity} and {@link #capacityUnitCode}, specifying
 * its total available area/volume/length/duration.
 */
@Entity
@Table(name = "location", uniqueConstraints = {
	@UniqueConstraint(columnNames = { "barcode" }),
})
@JsonIdentityInfo(scope = Location.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Getter
@Setter
@NoArgsConstructor
public class Location extends CooperatorOwnedModel implements SelfCleaning, Copyable<Location> {
	private static final long serialVersionUID = -3749063353717875756L;

	@Id
	@JsonProperty
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "location_id", columnDefinition = "int")
	private Long id;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "parent_location_id")
	@JsonSerialize(using = EntityIdSerializer.class)
	private Location parentLocation; // Locations have a hierarchical structure

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "site_id", nullable = false)
	@NotNull
	private Site site; // Needs index

	@SimpleString
	@NotNull
	@Column(name = "location_number_part1", nullable = false)
	private String locationNumberPart1;

	@Column(name = "location_number_part2")
	private Long locationNumberPart2;

	@SimpleString
	@Column(name = "location_number_part3")
	private String locationNumberPart3;

	@CodeValueField(CommunityCodeValues.LOCATION_TYPE)
	@NotNull
	@Column(name = "location_type_code", nullable = false, length = CODE_VALUE_LENGTH)
	private String locationTypeCode;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "geography_id")
	@JsonIgnoreProperties(value = { "createdBy", "modifiedBy", "ownedBy" })
	private Geography geography;

	@Size(max = 100)
	@Column(length = 100)
	private String barcode;

	@Min(0)
	private int capacity = 0; // The capacity of this location, may be 0

	@CodeValueField(CommunityCodeValues.UNIT_OF_CAPACITY)
	@Column(name = "capacity_unit_code", length = CODE_VALUE_LENGTH)
	private String capacityUnitCode; // If capacity != 0 then it must be provided

	@Basic
	@NotNull
	@Size(min = 1, max = 1)
	@Column(name = "is_enabled", nullable = false, length = 1)
	private String isEnabled = "Y";

	@OneToMany(fetch = FetchType.LAZY, cascade = {}, mappedBy = "location")
	private List<LocationData> data;

	@Basic
	@Column
	@Lob
	private String note;

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

	@PrePersist
	protected void prePersist() {
		super.prePersist();
		preUpdate();
		if (StringUtils.isBlank(this.barcode)) {
			this.barcode = UUID.randomUUID().toString();
		}
	}

	@PreUpdate
	protected void preUpdate() {
		if (capacity > 0 && StringUtils.isBlank(capacityUnitCode)) {
			throw new InvalidApiUsageException("capacityUnitCode not specified");
		}
	}

	@Transient
	public boolean isEnabled() {
		return this.isEnabled.equals("Y");
	}

	@Override
	public void trimStringsToNull() {
		SelfCleaning.super.trimStringsToNull();
	}

	@Override
	public void lazyLoad() {
		super.lazyLoad();

		lazyLoad(this.site);
		lazyLoad(this.geography);
		lazyLoad(this.parentLocation);
		if (CollectionUtils.isNotEmpty(data)) {
			data.size();
		}
	}

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