AppSettingTriggers.java

/*
 * Copyright 2025 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.service.triggers;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.gringlobal.application.config.IntegrationConfig;
import org.gringlobal.model.AppSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Objects;

@Aspect
@Component("appSettingTriggers")
@Slf4j
public class AppSettingTriggers {

	@Autowired(required = false)
	private IntegrationConfig.GenesysClientFactory genesysClientFactory;

	@Pointcut("target(org.gringlobal.persistence.AppSettingRepository)")
	public void targetAppSettingRepository() {};

	@Pointcut("execution(* *.save(..)) || execution(* *.saveAndFlush(..)) || execution(* *.delete(..))")
	public void affectsSingleRecord() {};

	@Pointcut("execution(* *.saveAll(..)) || execution(* *.saveAllAndFlush(..)) || execution(* *.deleteAll(..))")
	public void affectsManyRecords() {};

	@Around(value = "targetAppSettingRepository() && affectsSingleRecord() && args(appSetting)")
	public Object aroundAppSettingSave(final ProceedingJoinPoint joinPoint, final AppSetting appSetting) throws Throwable {
		if (genesysClientFactory != null && Objects.equals(appSetting.getCategoryTag(), IntegrationConfig.GenesysClientFactory.SETTINGS_GENESYS)) {
			genesysClientFactory.clearToken();
		}
		return joinPoint.proceed();
	}

	@Around(value = "targetAppSettingRepository() && affectsManyRecords() && args(appSettings)")
	public Object aroundAppSettingsSave(final ProceedingJoinPoint joinPoint, final Collection<AppSetting> appSettings) throws Throwable {
		if (genesysClientFactory != null && appSettings.stream().anyMatch(s -> Objects.equals(s.getCategoryTag(), IntegrationConfig.GenesysClientFactory.SETTINGS_GENESYS))) {
			genesysClientFactory.clearToken();
		}
		return joinPoint.proceed();
	}
}