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.EnumType;
import javax.persistence.Enumerated;
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 javax.validation.constraints.Pattern;

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.compatibility.SysTableFieldInfo;
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.gringlobal.model.workflow.WorkflowActionStep;
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
		CANCELED // Action is canceled
	}

	@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;

	@Column(name = "is_done", length = 1)
	@Pattern(regexp = "^Y|N$")
	protected String isDone;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "workflow_step_id")
	@SysTableFieldInfo(ignore = true)
	protected WorkflowActionStep workflowStep;

	/**
	 * 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;

	@IgnoreField
	@Formula("case when completed_date is not null and is_done = 'Y' then 'COMPLETED' when completed_date is not null and is_done = 'N' then 'CANCELED' when started_date is not null then 'INPROGRESS' when not_before_date is null or not_before_date < CURRENT_TIMESTAMP then 'PENDING' else 'SCHEDULED' end")
	@Enumerated(EnumType.STRING)
	private ActionState state;

	protected AbstractAction() {
		super();
	}

	/**
	 * Get the codevalue group of {@link #actionNameCode}
	 * @return Group tag
	 */
	@Transient
	public abstract String getActionGroupName();

	public ActionState getState() {
		if (completedDate != null) { // COMPLETED or CANCELED
			if ("Y".equals(isDone)) {
				return ActionState.COMPLETED;
			} else {
				return ActionState.CANCELED;
			}
		} else { // PENDING or SCHEDULED or INPROGRESS
			if (startedDate != null) {
				return ActionState.INPROGRESS;
			} else if (notBeforeDate == null || notBeforeDate.compareTo(Instant.now()) <= 0){
				return ActionState.PENDING;
			} else {
				return ActionState.SCHEDULED;
			}
		}
	}

	@PrePersist
	@PreUpdate
	private void prePersistUpdate() {
		updateDateFormatCodes();
		updateIsDone();
	}

	private void updateIsDone() {
		if (completedDate != null) {
			isDone = isDone == null ? "Y" : isDone;
		} else if (isDone != null) {
			completedDate = Instant.now();
			completedDateCode = CommunityCodeValues.DATE_FORMAT_DATETIME.value;
		}
	}

	private void updateDateFormatCodes() {
		if (this.startedDate == null) {
			this.startedDateCode = null;
		} else if (this.startedDateCode == null) {
			this.startedDateCode = CommunityCodeValues.DATE_FORMAT_DATE.value;
		}
		if (this.completedDate == null) {
			this.completedDateCode = null;
		} else if (this.completedDateCode == null) {
			this.completedDateCode = CommunityCodeValues.DATE_FORMAT_DATE.value;
		}
		if (this.notBeforeDate == null) {
			this.notBeforeDateCode = null;
		} else if (this.notBeforeDateCode == null) {
			this.notBeforeDateCode = CommunityCodeValues.DATE_FORMAT_DATE.value;
		}
	}

	/**
	 * 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;
	}

}