All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.infusers.core.audit.AuditService Maven / Gradle / Ivy

package com.infusers.core.audit;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import com.infusers.core.audit.response.AuditRecordsListDto;
import com.infusers.core.audit.search.AuditSpecification;
import com.infusers.core.exception.user.UserNotFoundException;
import com.infusers.core.logger.ILogger;
import com.infusers.core.reports.dto.ReportColumn;
import com.infusers.core.reports.dto.ReportData;
import com.infusers.core.reports.dto.ReportRow;
import com.infusers.core.reports.utility.ReportsUtility;
import com.infusers.core.user.dto.UserDetailsDto;
import com.infusers.core.user.remote.RemoteUserService;
import com.infusers.core.util.InfusersUtility;

@Service
public class AuditService {	
	
	public enum ResultsType {
	    ALL,
	    SELF
	}
	
	private final Logger log = LogManager.getLogger(AuditService.class);
	private static final String CLASS_NAME = "AuditService";	

	@Autowired(required = true)
	private AuditRepository auditRepository;
	
	@Autowired(required = true)
	private RemoteUserService userService;	
	
    @Autowired
    private InfusersUtility infusersUtility;	
	
	public AuditRecordsListDto getAllAuditRecords(Integer pageNo, Integer pageSize, String sortBy, String order, String searchString, String userName) {
		log.debug(String.format(CLASS_NAME+".getAllAuditRecords() Fetching List of Audit Records on Pagination :: pageNo =%d  :: pageSize = %d :: sortBy = '%s' :: order = '%s' :: searchString = %s :: userName = %s", pageNo, pageSize, sortBy, order, searchString, userName));
		
		UserDetailsDto userDto = userService.getUser(userName);
	    Page pagedResult = getReportRaw( ResultsType.ALL, pageNo,  pageSize, sortBy,  order,  searchString,  userDto);
		
		AuditRecordsListDto auditList = new AuditRecordsListDto(userService);

		if (pagedResult.hasContent()) {
			auditList.copy(pagedResult.getContent(), pagedResult.getTotalElements());
		}
		return auditList;
	}
	
	public ReportData getReport(ResultsType resultsType, Integer pageNo, Integer pageSize, String sortBy, String order, String searchString, String userName) {
	    log.debug(String.format(CLASS_NAME + ".getReport() :: resultsType =%s :: pageNo =%d  :: pageSize = %d :: sortBy = '%s' :: order = '%s' :: searchString = %s :: userName = %s",
	    		resultsType, pageNo, pageSize, sortBy, order, searchString, userName));

	    UserDetailsDto userDto = userService.getUser(userName);
	    Page pagedResult = getReportRaw( resultsType, pageNo,  pageSize, sortBy,  order,  searchString,  userDto);

	    // Extract columns from the AuditRecord class
	    List columns = ReportsUtility.getColumnsFromEntity(AuditRecord.class);

	    // Convert Page to List
	    List rows = pagedResult.getContent().stream()
	            .map(entity -> new ReportRow(ReportsUtility.getValuesFromEntity(entity)))
	            .collect(Collectors.toList());

	    // Prepare and return the report data
	    ReportData data = new ReportData("Audit Report", columns, rows, pagedResult.getTotalPages(), pagedResult.getNumber(), pagedResult.getSize(), pagedResult.getTotalElements());

	    log.debug(CLASS_NAME + ".getReport() return data : " + data.toString());
	    return data;
	}
	
	private Page getReportRaw(ResultsType resultsType, Integer pageNo, Integer pageSize, String sortBy, String order, String searchString, UserDetailsDto userDto) {
	    log.debug(String.format(CLASS_NAME + ".getReportRaw() :: resultsType =%s :: pageNo =%d  :: pageSize = %d :: sortBy = '%s' :: order = '%s' :: searchString = %s :: userName = %s",
	    		resultsType, pageNo, pageSize, sortBy, order, searchString, userDto!=null ? userDto.getUsername() : "User DTO is NULL!"));
	    
	    if(userDto==null) {
			throw new UserNotFoundException("User not found/No access! :: userName = "+userDto!=null ? userDto.getUsername() : "User DTO is NULL!");	    	
	    }

	    // Handling null or empty sortBy and order parameters
	    Pageable paging;
	    if (sortBy == null || sortBy.isEmpty() || "undefined".equalsIgnoreCase(sortBy)) {
	        // No sorting if sortBy is empty or undefined
	        paging = PageRequest.of(pageNo, pageSize); // No sorting
	    } else {
	        Sort sort = Sort.by(sortBy);
	        if (order == null || order.isEmpty() || order.equalsIgnoreCase("asc")) {
	            paging = PageRequest.of(pageNo, pageSize, sort.ascending());
	        } else {
	            paging = PageRequest.of(pageNo, pageSize, sort.descending());
	        }
	    }

	    Page pagedResult;
	    boolean searchActive = searchString != null && !searchString.isEmpty();

	    if (searchActive) {
	        AuditSpecification spec;
	        if (userDto.isAdmin()) {
	            spec = new AuditSpecification(null, searchString);
	        } else {
	            spec = new AuditSpecification(userDto != null ? userDto.getUsername() : "", searchString);
	        }
	        pagedResult = auditRepository.findAll((Specification) spec.getSpec(), paging);
	    } else {
	        if (userDto.isAdmin() && resultsType==ResultsType.ALL) {
	            pagedResult = auditRepository.findAll(paging);
	        } else {
	            pagedResult = auditRepository.findByUserEmailId(userDto.getUsername(), paging);
	        }
	    }
	    
	    log.debug(CLASS_NAME + ".getReportRaw() :: Total Pages = " + pagedResult.getTotalPages()+" :: Number = "+pagedResult.getNumber()+" :: Size = "+pagedResult.getSize()+" :: Total Elements = "+pagedResult.getTotalElements());	    
	    return pagedResult;
	}	
		
	private ResponseEntity createAuditRecord(AuditRecord auditRecord) {
		log.debug(CLASS_NAME+".createAuditRecord() Creating new audit record, audit id = ", auditRecord.getId());
		
		try {

			AuditRecord savedAuditRecord = auditRepository.save(auditRecord);
			URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedAuditRecord.getId())
					.toUri();
	
			return ResponseEntity.created(location).build();
		
		}
		catch(Exception e) {
			log.error(CLASS_NAME+".createAuditRecord() Creation of new audit record Failed!! auditRecord = ", auditRecord+" :: error = "+e.getMessage());
			return null;
		}
	}
    
    public boolean log(ILogger callerLogger, ILogger.LogTypes logType, String entityName, String action, String entityId, String comments) {
    	if(callerLogger!=null) {
    		callerLogger.log(logType, String.format("entityName = %s :: action = %s :: entityId = %s :: comments: %s", entityName, action, entityId, comments));
    	}
    	AuditRecord auditLog = new AuditRecord( infusersUtility.getLoggedInUserName(),  entityName,  action, entityId, comments);
    	ResponseEntity createdLog = this.createAuditRecord(auditLog);
    	
    	return createdLog!=null;
    }    
}