OrderRequest.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 java.util.Date;
import java.util.List;
import javax.persistence.*;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.genesys.blocks.model.Copyable;
import org.gringlobal.custom.elasticsearch.IgnoreField;
import org.gringlobal.custom.validation.javax.CodeValueField;
import org.gringlobal.model.community.CommunityCodeValues;
import org.hibernate.annotations.Formula;
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 static org.gringlobal.model.community.CommunityCodeValues.CODE_VALUE_LENGTH;

/**
 * Auto-generated by:
 * org.apache.openjpa.jdbc.meta.ReverseMappingTool$AnnotatedCodeGenerator
 */
@Entity
@Table(name = "order_request")
@JsonIdentityInfo(scope = OrderRequest.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Getter
@Setter
@NoArgsConstructor
public class OrderRequest extends CooperatorOwnedModel implements Copyable<OrderRequest> {

	private static final long serialVersionUID = -8164102072510508951L;

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

	@Basic
	@Column(name = "local_number", length = 50)
	private String localNumber;

	@Basic
	@Column(name = "order_type_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.ORDER_REQUEST_TYPE)
	private String orderTypeCode;

	@Basic
	@Column(name = "ordered_date")
	private Date orderedDate;

	@Basic
	@Column(name = "completed_date")
	private Date completedDate;

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

	/**
	 * The number of order request items.
	 */
	@Formula("(SELECT COUNT(*) FROM order_request_item ori WHERE ori.order_request_id = order_request_id)")
	private Integer numberOfItems;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "feedback_id")
	@Field(type = FieldType.Object)
	private Feedback feedback;

	@Basic
	@Column(name = "intended_use_code", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.ORDER_INTENDED_USE)
	private String intendedUseCode;

	@Basic
	@Column(name = "intended_use_note")
	@Lob
	private String intendedUseNote;

	@Basic
	@Column
	@Lob
	private String note;

	@Basic
	@Column(name = "special_instruction")
	@Lob
	private String specialInstruction;

	@Basic
	@Column(name = "order_obtained_via", length = 20)
	private String orderObtainedVia;

	@Basic
	@Column(name = "mta_type", length = CODE_VALUE_LENGTH)
	@CodeValueField(CommunityCodeValues.MTA_TYPE)
	private String mtaType;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "original_order_request_id")
	@JsonIdentityInfo(scope = OrderRequest.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
	@JsonIdentityReference(alwaysAsId = true)
	private OrderRequest originalOrderRequest;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "requestor_cooperator_id")
	@Field(type = FieldType.Object)
	private Cooperator requestorCooperator;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "ship_to_cooperator_id")
	@Field(type = FieldType.Object)
	private Cooperator shipToCooperator;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "final_recipient_cooperator_id", nullable = false)
	@Field(type = FieldType.Object)
	private Cooperator finalRecipientCooperator;

	/**
	 * Authorized Official is the legal signatory of MTA. Must be a person (not an organization) Cooperator.
	 */
	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "authorized_official_cooperator_id", nullable = true)
	@Field(type = FieldType.Object)
	private Cooperator authorizedOfficialCooperator;

	@ManyToOne(fetch = FetchType.LAZY, cascade = {})
	@JoinColumn(name = "web_order_request_id")
	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy" })
	private WebOrderRequest webOrderRequest;

	@Formula("(SELECT ora.action_name_code FROM order_request_action ora WHERE ora.order_request_id = order_request_id AND ora.completed_date IS NOT NULL ORDER BY ora.completed_date desc OFFSET 0 ROWS FETCH FIRST 1 ROWS ONLY)")
	@IgnoreField
	private String lastCompletedAction;

	@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.REMOVE }, mappedBy = "orderRequest")
	@JsonIgnore
	private List<OrderRequestItem> orderRequestItems;

	@OneToMany(cascade = {}, fetch = FetchType.LAZY, mappedBy = "orderRequest")
	@JsonIgnore
	private List<OrderRequestAttach> attachments;

	@OneToMany(cascade = {}, fetch = FetchType.LAZY, mappedBy = "orderRequest")
	@JsonIgnore
	private List<OrderRequestAction> actions;

	@PrePersist
	@PreUpdate
	private void preupdate() {
		if (this.shipToCooperator == null) {
			this.shipToCooperator = this.finalRecipientCooperator;
		}
		if (this.requestorCooperator == null) {
			this.requestorCooperator = this.finalRecipientCooperator;
		}
	}

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

	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy", "sysLang", "note", "geography", "secondaryGeography", "webCooperator" } )
	@JsonIdentityReference
	public Cooperator getFinalRecipientCooperator() {
		return finalRecipientCooperator;
	}

	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy", "sysLang", "note", "geography", "secondaryGeography", "webCooperator" } )
	@JsonIdentityReference
	public Cooperator getRequestorCooperator() {
		return requestorCooperator;
	}

	@JsonIgnoreProperties({ "ownedBy", "createdBy", "modifiedBy", "sysLang", "note", "geography", "secondaryGeography", "webCooperator" } )
	@JsonIdentityReference
	public Cooperator getShipToCooperator() {
		return shipToCooperator;
	}
	
	public String reportFinalRecipientCountryCode() {
		return cooperatorCountryCode(this.finalRecipientCooperator);
	}
	
	public String reportShipToCountryCode() {
		return cooperatorCountryCode(this.shipToCooperator);
	}

	public String reportRequestorCountryCode() {
		return cooperatorCountryCode(this.requestorCooperator);
	}
	
	private static String cooperatorCountryCode(Cooperator cooperator) {
		if (cooperator != null) {
			var geography = cooperator.getGeography();
			if (geography != null) {
				return geography.getCountryCode();
			}
		}
		return null;
	}

	@Override
	public void lazyLoad() {
		super.lazyLoad();
		lazyLoad(this.feedback);
		lazyLoad(this.finalRecipientCooperator);
		lazyLoad(this.originalOrderRequest);
		lazyLoad(this.requestorCooperator);
		lazyLoad(this.shipToCooperator);
		lazyLoad(this.authorizedOfficialCooperator);
		lazyLoad(this.webOrderRequest);
	}

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