Skip to content

Commit

Permalink
update status manager
Browse files Browse the repository at this point in the history
  • Loading branch information
OSousa117 committed Oct 30, 2023
1 parent 143e4cd commit 74e4492
Showing 1 changed file with 83 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,6 @@

package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.*;
Expand All @@ -36,6 +31,10 @@
import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.StatusManager;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
@RequiredArgsConstructor
@Service
@Slf4j
Expand All @@ -48,9 +47,11 @@ public class StatusManagerImpl implements StatusManager {
private final LinkedCapacityGroupMaterialDemandRepository matchedDemandsRepository;
private final LoggingHistoryRepository loggingRepository;

private static final LocalDate TWO_WEEKS_FROM_NOW = LocalDate.now().plusWeeks(2);

@Override
public void calculateBottleneck(String userID, boolean postLog) {
UserEntity user = getUser(userID);
UserEntity user = getUser(userID).orElseThrow(() -> new IllegalArgumentException("User not found"));
List<CapacityGroupEntity> capacityGroups = capacityGroupRepository.findByUserID(user.getId());

int accumulatedImprovements = 0;
Expand All @@ -65,67 +66,100 @@ public void calculateBottleneck(String userID, boolean postLog) {
accumulatedDegradations++;
}
}
StatusesEntity status = getStatus(userID);
status.setStatusImprovementCount(accumulatedImprovements);
status.setStatusDegradationCount(accumulatedDegradations);

updateAndLogStatus(userID, postLog, accumulatedImprovements, accumulatedDegradations);
}

private Optional<UserEntity> getUser(String userID) {
return userRepository.findById(UUID.fromString(userID));
}

private Optional<StatusesEntity> getStatus(String userID) {
return statusesRepository.findByUserID(UUID.fromString(userID));
}

private void updateAndLogStatus(String userID, boolean postLog, int improvements, int degradations) {
StatusesEntity status = getStatus(userID).orElseGet(() -> createInitialStatus(userID));

if (improvements > 0) {
logEvent(EventType.STATUS_IMPROVEMENT, userID, postLog, "Status improved for " + improvements + " weeks", null);
}
if (degradations > 0) {
logEvent(EventType.STATUS_REDUCTION, userID, postLog, "Status degraded for " + degradations + " weeks", null);
}

status.setStatusImprovementCount(improvements);
status.setStatusDegradationCount(degradations);
statusesRepository.save(status);
}

private StatusesEntity createInitialStatus(String userID) {
StatusesEntity status = new StatusesEntity();
status.setUserID(UUID.fromString(userID));
status.setStatusImprovementCount(0);
status.setStatusDegradationCount(0);
statusesRepository.save(status);
return status;
}

private EventType processCapacityGroup(String userID, CapacityGroupEntity cgs, boolean postLog) {
List<LinkedCapacityGroupMaterialDemandEntity> matchedEntities = matchedDemandsRepository.findByCapacityGroupID(
cgs.getId()
);

double aggregatedAverageDemand = 0.0;

for (LinkedCapacityGroupMaterialDemandEntity entity : matchedEntities) {
Optional<MaterialDemandEntity> materialDemand = materialDemandRepository.findById(
entity.getMaterialDemandID()
);
if (materialDemand.isPresent()) {
aggregatedAverageDemand += calculateAverageDemand(materialDemand.get().getDemandSeries());
}
}
double aggregatedAverageDemand = calculateAggregatedAverageDemand(cgs);

EventType eventType = determineEventType(cgs, aggregatedAverageDemand);
cgs.setLinkStatus(eventType);
capacityGroupRepository.save(cgs);
logEvent(eventType, userID, postLog, cgs.getId().toString());
logEvent(eventType, userID, postLog, null, cgs.getId());
return eventType;
}

private UserEntity getUser(String userID) {
return userRepository
.findById(UUID.fromString(userID))
.orElseThrow(() -> new IllegalArgumentException("User not found"));
}

private StatusesEntity getStatus(String userID) {
return statusesRepository
.findByUserID(UUID.fromString(userID))
.orElseGet(
() -> {
StatusesEntity status = new StatusesEntity();
status.setUserID(UUID.fromString(userID));
status.setStatusImprovementCount(0);
status.setStatusDegradationCount(0);
statusesRepository.save(status);
return status;
}
);
private double calculateAggregatedAverageDemand(CapacityGroupEntity cgs) {
return matchedDemandsRepository.findByCapacityGroupID(cgs.getId()).stream()
.map(entity -> materialDemandRepository.findById(entity.getMaterialDemandID()))
.filter(Optional::isPresent)
.map(Optional::get)
.mapToDouble(demand -> calculateAverageDemand(demand.getDemandSeries()))
.sum();
}

private double calculateAverageDemand(List<DemandSeries> matchedDemandSeries) {
double totalDemand = matchedDemandSeries
.stream()
.flatMap(demand -> demand.getDemandSeriesValues().stream())
.mapToDouble(DemandSeriesValues::getDemand)
.sum();
long count = matchedDemandSeries.stream().mapToLong(demand -> demand.getDemandSeriesValues().size()).sum();
double totalDemand = matchedDemandSeries.stream()
.flatMap(demand -> demand.getDemandSeriesValues().stream())
.filter(value -> !value.getCalendarWeek().isBefore(TWO_WEEKS_FROM_NOW))
.mapToDouble(DemandSeriesValues::getDemand)
.sum();

long count = matchedDemandSeries.stream()
.flatMap(demand -> demand.getDemandSeriesValues().stream())
.filter(value -> !value.getCalendarWeek().isBefore(TWO_WEEKS_FROM_NOW))
.count();

return count == 0 ? 0 : totalDemand / count;
}

private void logEvent(EventType eventType, String userID, boolean postLog, String descriptionOverride, UUID cgID) {
if (!postLog) return;

LoggingHistoryEntity logEntity = new LoggingHistoryEntity();
logEntity.setObjectType(EventObjectType.CAPACITY_GROUP);
Optional.ofNullable(cgID).ifPresent(logEntity::setCapacityGroupId);
logEntity.setEventType(eventType);
logEntity.setUserAccount(getUser(userID).map(UserEntity::getUsername).orElse("Unknown"));
logEntity.setTime_created(Timestamp.valueOf(LocalDateTime.now()));
logEntity.setLogID(UUID.randomUUID());

logEntity.setDescription(Optional.ofNullable(descriptionOverride).orElseGet(() -> getEventDescription(eventType)));
if (logEntity.getDescription() != null) {
loggingRepository.save(logEntity);
}
}

private String getEventDescription(EventType eventType) {
Map<EventType, String> descriptions = new HashMap<>();
descriptions.put(EventType.STATUS_IMPROVEMENT, "Status improvement");
descriptions.put(EventType.STATUS_REDUCTION, "Status degradation");
return descriptions.get(eventType);
}

private EventType determineEventType(CapacityGroupEntity capacityGroup, double totalDemand) {
double actualCapacity = capacityGroup.getDefaultActualCapacity();
double maxCapacity = capacityGroup.getDefaultMaximumCapacity();
Expand All @@ -140,29 +174,4 @@ private EventType determineEventType(CapacityGroupEntity capacityGroup, double t
return EventType.GENERAL_EVENT;
}
}

private void logEvent(EventType eventType, String userID, boolean postLog, String cgID) {
if (postLog) {
LoggingHistoryEntity logEntity = new LoggingHistoryEntity();
logEntity.setObjectType(EventObjectType.CAPACITY_GROUP);
logEntity.setCapacityGroupId(UUID.fromString(cgID));
logEntity.setEventType(eventType);
logEntity.setUserAccount(getUser(userID).getUsername());
logEntity.setTime_created(Timestamp.valueOf(LocalDateTime.now()));
logEntity.setLogID(UUID.randomUUID());

switch (eventType) {
case STATUS_IMPROVEMENT:
logEntity.setDescription("Status improvement");
break;
case STATUS_REDUCTION:
logEntity.setDescription("Status degradation");
break;
default:
return;
}

loggingRepository.save(logEntity);
}
}
}

0 comments on commit 74e4492

Please sign in to comment.