WorkflowHelperMethods.java

/*
 * Copyright 2024 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.workflow;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.gringlobal.model.Inventory;
import org.gringlobal.model.InventoryMaintenancePolicy;
import org.gringlobal.model.QInventory;
import org.gringlobal.model.Site;
import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class WorkflowHelperMethods {

	private static JPAQueryFactory jpaQueryFactory;

	public static Map<String, Method> methods;
	
	static {
		methods = new HashMap<>();
		ReflectionUtils.doWithMethods(WorkflowHelperMethods.class,
			method -> methods.put(method.getName(), method),
			method -> method.isAnnotationPresent(WorkflowHelperMethods.HelperMethod.class)
		);
	}
	
	public static void setJpaQueryFactory(JPAQueryFactory jpaQueryFactory) {
		WorkflowHelperMethods.jpaQueryFactory = jpaQueryFactory;
	}
	
	@Retention(RetentionPolicy.RUNTIME)
	public @interface HelperMethod{
	}

	@HelperMethod
	public static Number sumOfQuantity(Site site, InventoryMaintenancePolicy policy) {
		if (jpaQueryFactory == null) {
			throw new RuntimeException("JPAQueryFactory is not configured");
		}
		return jpaQueryFactory.select(QInventory.inventory.quantityOnHand.sum())
			.from(QInventory.inventory)
			.where(
				QInventory.inventory.formTypeCode.ne(Inventory.SYSTEM_INVENTORY_FTC)
					.and(QInventory.inventory.site().eq(site))
					.and(QInventory.inventory.inventoryMaintenancePolicy().eq(policy))
			)
			.fetchOne();
	}

	@HelperMethod
	public static Number quantityOnHandBySiteAndPolicy(Inventory inventory) {
		return sumOfQuantity(inventory.getSite(), inventory.getInventoryMaintenancePolicy());
	}
}