AccessionInvGroupServiceImpl.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.service.impl;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.gringlobal.custom.elasticsearch.SearchException;
import org.gringlobal.model.Accession;
import org.gringlobal.model.AccessionInvGroup;
import org.gringlobal.model.AccessionInvGroupMap;
import org.gringlobal.model.Inventory;
import org.gringlobal.model.QAccessionInvGroupMap;
import org.gringlobal.model.QInventory;
import org.gringlobal.persistence.AccessionInvGroupMapRepository;
import org.gringlobal.persistence.AccessionInvGroupRepository;
import org.gringlobal.persistence.InventoryRepository;
import org.gringlobal.service.AccessionInvGroupService;
import org.gringlobal.service.filter.AccessionInvGroupFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * The Class AccessionInvGroupServiceImpl.
 */
@Service
@Transactional(readOnly = true)
@Slf4j
public class AccessionInvGroupServiceImpl extends FilteredCRUDService2Impl<AccessionInvGroup, AccessionInvGroupFilter, AccessionInvGroupRepository> implements
		AccessionInvGroupService {

	@Autowired
	private AccessionInvGroupMapRepository accessionInvGroupMapRepository;

	@Autowired
	private InventoryRepository inventoryRepository;

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'CREATE')")
	public AccessionInvGroup create(AccessionInvGroup source) {
		log.debug("Create AccessionInvGroup. Input data {}", source);
		AccessionInvGroup toSave = new AccessionInvGroup();
		toSave.apply(source);

		AccessionInvGroup saved = repository.save(toSave);

		return _lazyLoad(saved);
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'CREATE')")
	public AccessionInvGroup createFast(AccessionInvGroup source) {
		return super.createFast(source);
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'WRITE')")
	public AccessionInvGroup update(AccessionInvGroup updated) {
		return super.update(updated);
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'WRITE')")
	public AccessionInvGroup update(AccessionInvGroup updated, AccessionInvGroup target) {
		final AccessionInvGroup loaded = get(updated.getId());
		log.debug("Update AccessionInvGroup. Input data {}", updated);
		loaded.apply(updated);

		AccessionInvGroup saved = repository.save(loaded);
		return _lazyLoad(saved);
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'WRITE')")
	public AccessionInvGroup updateFast(AccessionInvGroup updated, AccessionInvGroup target) {
		target.apply(updated);
		return repository.save(target);
	}

	/**
	 * Override to clear {@link AccessionInvGroup#members}
	 */
	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'DELETE')")
	public AccessionInvGroup remove(AccessionInvGroup entity) {
		accessionInvGroupMapRepository.deleteByAccessionInvGroup(entity);
		return super.remove(entity);
	}

	@Override
	public Page<AccessionInvGroup> list(AccessionInvGroupFilter filter, Pageable page) throws SearchException {
		return super.list(AccessionInvGroup.class, filter, page);
	}

	@Override
	public Page<AccessionInvGroupMap> listMembers(AccessionInvGroup accessionInvGroup, Pageable page) {
		QInventory inventory = new QInventory("inventory");
		JPAQuery<AccessionInvGroupMap> query = jpaQueryFactory.selectFrom(QAccessionInvGroupMap.accessionInvGroupMap)
			// joins
			.innerJoin(QAccessionInvGroupMap.accessionInvGroupMap.inventory(), inventory).fetchJoin().innerJoin(inventory.accession()).fetchJoin()
			// predicate
			.where(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup().eq(accessionInvGroup));

		return accessionInvGroupMapRepository.findAll(query, page);
	}

	@Override
	public List<AccessionInvGroup> listInventoryGroups(Inventory inventory) {
		return jpaQueryFactory.select(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup())
				.from(QAccessionInvGroupMap.accessionInvGroupMap)
				// joins
				.join(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup())
				// predicate
				.where(QAccessionInvGroupMap.accessionInvGroupMap.inventory().eq(inventory))
				.fetch();
	}

	@Override
	public List<AccessionInvGroup> listAccessionGroups(Accession accession) {
		QInventory inventory = QInventory.inventory;
		return jpaQueryFactory.select(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup())
				.from(QAccessionInvGroupMap.accessionInvGroupMap)
				// joins
				.join(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup())
				.join(QAccessionInvGroupMap.accessionInvGroupMap.inventory(), inventory)
				// predicate
				.where(inventory.formTypeCode.eq(Inventory.SYSTEM_INVENTORY_FTC).and(inventory.accession().eq(accession)))
				.fetch();
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'WRITE')")
	public AccessionInvGroup addMembers(AccessionInvGroup group, List<Inventory> inventories, String note) {

		List<AccessionInvGroupMap> invGroupMaps = inventories.stream().map((inventory) -> {
			AccessionInvGroupMap invGroupMap = new AccessionInvGroupMap();
			invGroupMap.setAccessionInvGroup(group);
			invGroupMap.setInventory(inventory);
			invGroupMap.setNote(note);
			return invGroupMap;
		}).collect(Collectors.toList());
		accessionInvGroupMapRepository.saveAll(invGroupMaps);
		log.info("Added {} entries to group {}", invGroupMaps.size(), group.getGroupName());

		return group;
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'WRITE')")
	public AccessionInvGroup addMembers(AccessionInvGroup group, List<Accession> accessions) {
		if (CollectionUtils.isEmpty(accessions)) {
			return group;
		}
		group = get(group.getId());
		List<Inventory> toAdd = accessions.stream().map(a -> inventoryRepository.getSystemInventory(a)).filter(Objects::nonNull).collect(Collectors.toList());

		return addMembers(group, toAdd, null);
	}

	@Override
	@Transactional
	@PreAuthorize("@ggceSec.actionAllowed('InventoryGroup', 'ADMINISTRATION')")
	public AccessionInvGroup removeMembers(AccessionInvGroup group, List<AccessionInvGroupMap> groupMaps) {
		if (CollectionUtils.isEmpty(groupMaps)) {
			return group;
		}
		group = get(group.getId());

		var existingMaps = Lists.newArrayList(accessionInvGroupMapRepository.findAll(QAccessionInvGroupMap.accessionInvGroupMap.accessionInvGroup().eq(group)));
		var toRemove = existingMaps.stream().filter(groupMaps::contains).collect(Collectors.toList());

		accessionInvGroupMapRepository.deleteAll(toRemove);
		return reload(group);
	}

}