AbstractAction.java

/*
 * Copyright 2020 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 java.time.Instant;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Transient;
import javax.validation.constraints.AssertTrue;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Getter;
import lombok.Setter;
import org.genesys.blocks.model.Copyable;
import org.genesys.blocks.security.model.AclSid;
import org.genesys.blocks.util.JsonSidConverter;
import org.gringlobal.api.exception.InvalidApiUsageException;
import org.gringlobal.custom.elasticsearch.IgnoreField;
import org.gringlobal.custom.json.IgnoreEntityRefDeserializer;
import org.gringlobal.custom.json.converter.JsonAclSidConverter;
import org.gringlobal.custom.validation.javax.CodeValueField;
import org.gringlobal.model.community.CommunityCodeValues;
import org.hibernate.annotations.Formula;

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

/**
 * The base class for all Action records.
 *
 * @author Matija Obreza
 */
@MappedSuperclass
@Getter
@Setter
public abstract class AbstractAction<T extends AbstractAction<T>> extends CooperatorOwnedModel implements Copyable<T> {

	private static final long serialVersionUID = 1L;

	/**
	 * A utility enum to filter actions by their current state.
	 *
	 * The states are exclusive and under no circumstances
	 * should one action fall into more than one state. 
	 */
	public static enum ActionState {
		PENDING, // Action is due to start!
		INPROGRESS, // Action is started, but not finished
		SCHEDULED, // Action is not yet due to start
		COMPLETED // Action is completed
	}

	@Basic
	@Column(name = "started_date")
	protected Instant startedDate;

	@Basic
	@Column(name = "started_date_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.DATE_FORMAT)
	protected String startedDateCode;

	@Basic
	@Column(name = "not_before_date")
	protected Instant notBeforeDate;

	@Basic
	@Column(name = "not_before_date_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.DATE_FORMAT)
	protected String notBeforeDateCode;

	@Basic
	@Column(name = "completed_date")
	protected Instant completedDate;

	@Basic
	@Column(name = "completed_date_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.DATE_FORMAT)
	protected String completedDateCode;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "cooperator_id")
	protected Cooperator cooperator;

	@Basic
	@Column
	@Lob
	protected String note;

	@Basic
	@Column(name = "action_name_code", nullable = false, length = CODE_VALUE_LENGTH)
	protected String actionNameCode;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "assignee_id")
	@JsonSerialize(converter = JsonSidConverter.class)
	@JsonDeserialize(converter = JsonAclSidConverter.class)
	@IgnoreEntityRefDeserializer
	protected AclSid assignee;

	/**
	 * The age of an action is the difference (in days) between startedDate and completedDate (or today if null).
	 */
	@IgnoreField
	@Formula("datediff( day, started_date, isnull( completed_date, CURRENT_TIMESTAMP) )")
	private Integer durationInDays;


	protected AbstractAction() {
		super();
	}

	@PrePersist
	@PreUpdate
	private void updateDateFormatCodes() {
		if (this.startedDate == null) {
			this.startedDateCode = null;
		} else if (this.startedDateCode == null) {
			throw new InvalidApiUsageException("startedDateCode not specified");
		}
		if (this.completedDate == null) {
			this.completedDateCode = null;
		} else if (this.completedDateCode == null) {
			throw new InvalidApiUsageException("completedDateCode not specified");
		}
		if (this.notBeforeDate == null) {
			this.notBeforeDateCode = null;
		} else if (this.notBeforeDateCode == null) {
			throw new InvalidApiUsageException("notBeforeDateCode not specified");
		}
	}

	/**
	 * Gets the owning entity id.
	 *
	 * @return the owning entity id
	 */
	public abstract Long getOwningEntityId();

	public abstract String getActionNameCode();

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

	@AssertTrue(message = "'completedDate' cannot be before 'startedDate'")
	@Transient
	private boolean isValidDates() {
		if (startedDate != null && completedDate != null) {
			// 'completedDate' cannot be before 'startedDate'
			return !completedDate.isBefore(startedDate);
		}
		return true;
	}

}