From 07cec5647a9dff221227ffb5ad5e22f6b101ba21 Mon Sep 17 00:00:00 2001 From: Saja Adem Date: Wed, 15 Nov 2023 08:50:16 +0100 Subject: [PATCH 1/2] implemented alert service * Added configured and triggered alerts tables, controllers and services --- .../controllers/AlertController.java | 67 ++++++ .../entities/AlertEntity.java | 47 ++++ .../entities/MaterialDemandEntity.java | 7 +- .../entities/TriggeredAlertEntity.java | 52 +++++ .../entities/enums/AlertThresholdType.java | 6 + .../enums/AlertsMonitoredObjects.java | 8 + .../repositories/AlertsRepository.java | 36 +++ .../MaterialDemandRepository.java | 6 +- .../TriggeredAlertsRepository.java | 33 +++ .../services/AlertService.java | 40 ++++ .../services/impl/AlertServiceImpl.java | 218 ++++++++++++++++++ .../impl/CapacityGroupServiceImpl.java | 2 + .../services/impl/DemandServiceImpl.java | 57 ++++- .../services/impl/FavoriteServiceImpl.java | 13 +- .../impl/SecurityTokenServiceImpl.java | 81 +++---- .../services/impl/StatusManagerImpl.java | 100 ++++---- .../src/contexts/InfoMenuContextProvider.tsx | 2 +- .../src/main/resources/openapi.yml | 162 +++++++++++++ 18 files changed, 832 insertions(+), 105 deletions(-) create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/TriggeredAlertEntity.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertThresholdType.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertsMonitoredObjects.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/AlertsRepository.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/TriggeredAlertsRepository.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java new file mode 100644 index 00000000..f55437d9 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java @@ -0,0 +1,67 @@ +/* + * ****************************************************************************** + * Copyright (c) 2023 BMW AG + * Copyright (c) 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * ******************************************************************************* + */ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.controllers; + +import eclipse.tractusx.demand_capacity_mgmt_specification.api.AlertsApi; +import eclipse.tractusx.demand_capacity_mgmt_specification.model.*; +import jakarta.servlet.http.HttpServletRequest; +import java.util.List; +import lombok.AllArgsConstructor; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.AlertService; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.utils.UserUtil; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@AllArgsConstructor +//@RequestMapping("/alerts") +public class AlertController implements AlertsApi { + + private HttpServletRequest request; + private final AlertService alertService; + + @Override + public ResponseEntity configureAlert(AlertRequest alertRequest) throws Exception { + AlertResponse responseDto = alertService.configureAlert(alertRequest); + return ResponseEntity.status(HttpStatus.CREATED).body(responseDto); + } + + @Override + public ResponseEntity configureTriggeredAlert(TriggeredAlertRequest triggeredAlertRequest) + throws Exception { + TriggeredAlertResponse responseDto = alertService.postTriggeredAlerts(triggeredAlertRequest); + return ResponseEntity.status(HttpStatus.CREATED).body(responseDto); + } + + @Override + public ResponseEntity> getAlerts() throws Exception { + String userID = UserUtil.getUserID(request); + return ResponseEntity.status(HttpStatus.OK).body(alertService.getAlerts(userID)); // ResponseEntity.status(HttpStatus.OK).body(alertService.getAlerts(userID)); + } + + @Override + public ResponseEntity> getTriggeredAlerts() throws Exception { + String userID = UserUtil.getUserID(request); + return ResponseEntity.status(HttpStatus.OK).body(alertService.getTriggeredAlerts(userID)); // + } +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java new file mode 100644 index 00000000..0c2cfa00 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java @@ -0,0 +1,47 @@ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities; + +import jakarta.persistence.*; +import java.util.UUID; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertThresholdType; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertsMonitoredObjects; + +@Entity +@Table(name = "alerts") +@Builder +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AlertEntity { + + @Id + // @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private UUID id; + + @Column(name = "user_id") + private UUID userID; + + @Column(name = "alert_name") + private String alertName; + + @Column(name = "monitored_objects") + @Enumerated(EnumType.STRING) + private AlertsMonitoredObjects monitoredObjects; + + @Column(name = "created") + private String created; + + @Column(name = "type") + @Enumerated(EnumType.STRING) + private AlertThresholdType type; + + @Column(name = "threshold") + private double threshold; + + @Column(name = "description") + private String description; +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/MaterialDemandEntity.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/MaterialDemandEntity.java index 2f7bfc10..a54cb04f 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/MaterialDemandEntity.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/MaterialDemandEntity.java @@ -25,13 +25,12 @@ import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import jakarta.persistence.*; -import lombok.*; -import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.EventType; -import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.MaterialDemandStatus; - import java.time.LocalDateTime; import java.util.List; import java.util.UUID; +import lombok.*; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.EventType; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.MaterialDemandStatus; @Entity @Cacheable(false) diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/TriggeredAlertEntity.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/TriggeredAlertEntity.java new file mode 100644 index 00000000..ccbfafca --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/TriggeredAlertEntity.java @@ -0,0 +1,52 @@ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities; + +import jakarta.persistence.*; +import java.util.UUID; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertThresholdType; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertsMonitoredObjects; + +@Entity +@Table(name = "triggered_alerts") +@Builder +@Data +@NoArgsConstructor +@AllArgsConstructor +public class TriggeredAlertEntity { + + @Id + @Column(name = "id") + private UUID id; + + @Column(name = "user_id") + private UUID userID; + + @Column(name = "alert_name") + private String alertName; + + @Column(name = "monitored_objects") + @Enumerated(EnumType.STRING) + private AlertsMonitoredObjects monitoredObjects; + + @Column(name = "created") + private String created; + + @Column(name = "trigger_times") + private int triggerTimes; + + @Column(name = "trigger_times_in_three_months") + private int triggerTimesInThreeMonths; + + @Column(name = "type") + @Enumerated(EnumType.STRING) + private AlertThresholdType type; + + @Column(name = "threshold") + private double threshold; + + @Column(name = "description") + private String description; +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertThresholdType.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertThresholdType.java new file mode 100644 index 00000000..2fa6d896 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertThresholdType.java @@ -0,0 +1,6 @@ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums; + +public enum AlertThresholdType { + ABSOLUTE, + RELATIVE, +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertsMonitoredObjects.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertsMonitoredObjects.java new file mode 100644 index 00000000..ccc83fa0 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/enums/AlertsMonitoredObjects.java @@ -0,0 +1,8 @@ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums; + +public enum AlertsMonitoredObjects { + ALL_DEMANDS, + ALL_CAPACITIES, + ALL_OBJECTS, + DEDICATED, +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/AlertsRepository.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/AlertsRepository.java new file mode 100644 index 00000000..066b46ac --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/AlertsRepository.java @@ -0,0 +1,36 @@ +/* + * ******************************************************************************* + * Copyright (c) 2023 BMW AG + * Copyright (c) 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * ******************************************************************************** + */ + +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.AlertEntity; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.StatusesEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface AlertsRepository extends JpaRepository { + Optional findByUserID(UUID userID); + List findAllByUserID(UUID userID); + void deleteByUserID(UUID userID); +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/MaterialDemandRepository.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/MaterialDemandRepository.java index 437dc8db..375a7b3a 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/MaterialDemandRepository.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/MaterialDemandRepository.java @@ -23,19 +23,19 @@ package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories; import jakarta.persistence.Cacheable; +import java.util.List; +import java.util.UUID; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.MaterialDemandEntity; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.MaterialDemandStatus; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import java.util.List; -import java.util.UUID; - @Repository @Cacheable(false) public interface MaterialDemandRepository extends JpaRepository { List findBySupplierId_Id(UUID id); + @Query("select m from MaterialDemandEntity m where m.customerId.id = ?1") List findByCustomerId_Id(UUID id); diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/TriggeredAlertsRepository.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/TriggeredAlertsRepository.java new file mode 100644 index 00000000..2172f097 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/repositories/TriggeredAlertsRepository.java @@ -0,0 +1,33 @@ +/* + * ******************************************************************************* + * Copyright (c) 2023 BMW AG + * Copyright (c) 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * ******************************************************************************** + */ + +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.AlertEntity; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.StatusesEntity; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.TriggeredAlertEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface TriggeredAlertsRepository extends JpaRepository {} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java new file mode 100644 index 00000000..50b145e4 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java @@ -0,0 +1,40 @@ +/* + * ******************************************************************************* + * Copyright (c) 2023 BMW AG + * Copyright (c) 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * ******************************************************************************** + */ + +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services; + +import eclipse.tractusx.demand_capacity_mgmt_specification.model.*; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +public interface AlertService { + AlertResponse configureAlert(AlertRequest alertRequest); + void triggerDemandAlertsIfNeeded( + String userID, + boolean isMaterialDemandChange, + double oldDemandValue, + double newDemandValue + ); + List getAlerts(String userID); + List getTriggeredAlerts(String userID); + TriggeredAlertResponse postTriggeredAlerts(TriggeredAlertRequest triggeredAlertRequest); +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java new file mode 100644 index 00000000..7c4b8581 --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java @@ -0,0 +1,218 @@ +/* + * ****************************************************************************** + * Copyright (c) 2023 BMW AG + * Copyright (c) 2023 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License, Version 2.0 which is available at + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + * ******************************************************************************* + */ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl; + +import eclipse.tractusx.demand_capacity_mgmt_specification.model.AlertRequest; +import eclipse.tractusx.demand_capacity_mgmt_specification.model.AlertResponse; +import eclipse.tractusx.demand_capacity_mgmt_specification.model.TriggeredAlertRequest; +import eclipse.tractusx.demand_capacity_mgmt_specification.model.TriggeredAlertResponse; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.*; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertThresholdType; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertsMonitoredObjects; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories.AlertsRepository; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories.TriggeredAlertsRepository; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.AlertService; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +@Lazy +@RequiredArgsConstructor +@Service +@Slf4j +public class AlertServiceImpl implements AlertService { + + private final AlertsRepository alertsRepository; + private final TriggeredAlertsRepository triggeredAlertsRepository; + + @Override + public AlertResponse configureAlert(AlertRequest alertRequest) { + AlertEntity alertEntity = convertDtoToEntity(alertRequest); + alertsRepository.save(alertEntity); + return convertAlertsResponseDto(alertEntity); + } + @Override + public void triggerDemandAlertsIfNeeded( + String userID, + boolean isMaterialDemandChange, + double oldValue, + double newValue + ) { + List alerts = alertsRepository.findAll(); // TODO : only bring my alerts + alerts.forEach( + alertEntity -> { + TriggeredAlertEntity triggeredAlertEntity = new TriggeredAlertEntity(); + triggeredAlertEntity.setId(UUID.randomUUID()); + triggeredAlertEntity.setAlertName(alertEntity.getAlertName()); + triggeredAlertEntity.setDescription(alertEntity.getDescription()); + triggeredAlertEntity.setType(alertEntity.getType()); + triggeredAlertEntity.setUserID(alertEntity.getUserID()); + triggeredAlertEntity.setMonitoredObjects(alertEntity.getMonitoredObjects()); + triggeredAlertEntity.setThreshold(alertEntity.getThreshold()); + LocalDateTime currentLocalDateTime = LocalDateTime.now(); + triggeredAlertEntity.setCreated(Timestamp.valueOf(currentLocalDateTime).toString()); + //triggeredAlertEntity.setTriggerTimesInThreeMonths(alertEntity.getTriggerTimesInThreeMonths()); + //triggeredAlertEntity.setTriggerTimes(alertEntity.getTriggerTimes()); + + if ( + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_DEMANDS) || + ( + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_CAPACITIES) && + !isMaterialDemandChange + ) || + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_OBJECTS) + ) { + if (alertEntity.getType().equals(AlertThresholdType.RELATIVE)) { + double threshold = alertEntity.getThreshold(); + double demandDelta = threshold * oldValue; + if ( + threshold >= 0 && + (newValue - oldValue >= demandDelta) || + (threshold < 0 && (newValue - oldValue <= demandDelta)) + ) { + // TODO : adjust the demand description , trigger times here + triggeredAlertsRepository.save(triggeredAlertEntity); + } + } + } else if (alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.DEDICATED)) { + if (alertEntity.getType().equals(AlertThresholdType.ABSOLUTE)) { + double threshold = alertEntity.getThreshold(); + if ( + threshold >= 0 && + (newValue - oldValue >= threshold) || + (threshold < 0 && (newValue - oldValue <= threshold)) + ) { + // TODO : adjust the demand description , trigger times here + triggeredAlertsRepository.save(triggeredAlertEntity); + } + } else { + double threshold = alertEntity.getThreshold(); + double demandDelta = alertEntity.getThreshold() * oldValue; + if ( + threshold >= 0 && + (newValue - oldValue >= demandDelta) || + (threshold < 0 && (newValue - oldValue <= demandDelta)) + ) { + // TODO : adjust the demand description , trigger times here + triggeredAlertsRepository.save(triggeredAlertEntity); + } + } + } + } + ); + } + + @Override + public List getAlerts(String userID) { + List alerts = alertsRepository.findAll(); + + getAlertByUserId(userID, alerts); + return alerts.stream().map(this::convertAlertsResponseDto).toList(); + } + + private static void getTriggeredAlertByUserId(String userID, List alerts) { + alerts + .stream() + .filter( + alertEntity -> { + if (alertEntity.getUserID().toString().equals(userID)) { + alerts.add(alertEntity); + } + return false; + } + ); + } + + private static void getAlertByUserId(String userID, List alerts) { + alerts + .stream() + .filter( + alertEntity -> { + if (alertEntity.getUserID().toString().equals(userID)) { + alerts.add(alertEntity); + } + return false; + } + ); + } + + @Override + public List getTriggeredAlerts(String userID) { + List alerts = triggeredAlertsRepository.findAll(); + + getTriggeredAlertByUserId(userID, alerts); + return alerts.stream().map(this::convertTriggeredAlertsResponseDto).toList(); + } + + @Override + public TriggeredAlertResponse postTriggeredAlerts(TriggeredAlertRequest triggeredAlertRequest) { + return null; + } + + private AlertResponse convertAlertsResponseDto(AlertEntity alertEntity) { + AlertResponse responseDto = new AlertResponse(); + responseDto.setType(alertEntity.getType().name()); + responseDto.setAlertId("" + alertEntity.getId()); + responseDto.setAlertName(alertEntity.getAlertName()); + responseDto.setCreated(alertEntity.getCreated()); + responseDto.setDescription(alertEntity.getDescription()); + responseDto.setMonitoredObjects(alertEntity.getMonitoredObjects().name()); + responseDto.setThreshold(String.valueOf(alertEntity.getThreshold())); + responseDto.setUser(alertEntity.getUserID().toString()); + return responseDto; + } + + private TriggeredAlertResponse convertTriggeredAlertsResponseDto(TriggeredAlertEntity alertEntity) { + TriggeredAlertResponse responseDto = new TriggeredAlertResponse(); + responseDto.setType(alertEntity.getType().name()); + responseDto.setAlertId("" + alertEntity.getId()); + responseDto.setAlertName(alertEntity.getAlertName()); + responseDto.setCreated(alertEntity.getCreated()); + responseDto.setDescription(alertEntity.getDescription()); + responseDto.setMonitoredObjects(alertEntity.getMonitoredObjects().name()); + responseDto.setThreshold(String.valueOf(alertEntity.getThreshold())); + // responseDto.setTriggerTimes(alertEntity.getTriggerTimes()); + // responseDto.setTriggerTimesInThreeMonths(alertEntity.getTriggerTimesInThreeMonths()); + responseDto.setUser(alertEntity.getUserID().toString()); + return responseDto; + } + + private AlertEntity convertDtoToEntity(AlertRequest alertRequest) { + return AlertEntity + .builder() + .id(UUID.randomUUID()) + .alertName(alertRequest.getAlertName()) + .created(alertRequest.getCreated()) + .description(alertRequest.getDescription()) + .monitoredObjects(AlertsMonitoredObjects.valueOf(alertRequest.getMonitoredObjects())) + .threshold(Double.parseDouble(alertRequest.getThreshold().toString())) + .userID(UUID.fromString(alertRequest.getUser())) + .type(AlertThresholdType.valueOf(alertRequest.getType())) + .build(); + } +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/CapacityGroupServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/CapacityGroupServiceImpl.java index 99370f39..f654b3b5 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/CapacityGroupServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/CapacityGroupServiceImpl.java @@ -60,6 +60,7 @@ public class CapacityGroupServiceImpl implements CapacityGroupService { private final LoggingHistoryService loggingHistoryService; private final FavoriteService favoriteService; private final StatusManagerImpl statusManager; + private final AlertService alertService; @Override public CapacityGroupResponse createCapacityGroup(CapacityGroupRequest capacityGroupRequest, String userID) { @@ -88,6 +89,7 @@ public CapacityGroupResponse createCapacityGroup(CapacityGroupRequest capacityGr capacityGroupRepository.save(capacityGroupEntity); } statusManager.calculateTodos(userID); + return convertCapacityGroupDto(capacityGroupEntity); } diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java index 4c1598a0..a4e55e25 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java @@ -27,11 +27,9 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; +import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.*; @@ -67,6 +65,8 @@ public class DemandServiceImpl implements DemandService { private final DemandSeriesRepository demandSeriesRepository; + private final AlertService alertService; + private final CapacityGroupRepository capacityGroupRepository; private final LinkedCapacityGroupMaterialDemandRepository linkedCapacityGroupMaterialDemandRepository; private final HttpServletRequest request; @@ -165,6 +165,10 @@ public MaterialDemandResponse updateDemand( } } ); + + + triggerDemandAlertsIfNeeded(demandId, userID, demand); + demand = materialDemandRepository.save(demand); postLogs(demandId, "MATERIAL DEMAND Updated", EventType.GENERAL_EVENT, userID); statusManager.calculateBottleneck(userID, true); @@ -172,6 +176,51 @@ public MaterialDemandResponse updateDemand( return convertDemandResponseDto(demand); } + private void triggerDemandAlertsIfNeeded(String demandId, String userID, MaterialDemandEntity demand) { + List oldDemandValues = new ArrayList<>(List.of()); + List newDemandValues = new ArrayList<>(List.of()); + + demand + .getDemandSeries() + .forEach( + demandSeries -> { + demandSeries + .getDemandSeriesValues() + .forEach( + demandSeriesValues -> { + newDemandValues.add(demandSeriesValues.getDemand()); + + System.out.println( + "sajaaaaaaa" + demandId + " " + "to" + demandSeriesValues.getDemand() + ); + } + ); + } + ); + + materialDemandRepository + .findById(UUID.fromString(demandId)) + .get() + .getDemandSeries() + .forEach( + demandSeries1 -> { + demandSeries1 + .getDemandSeriesValues() + .forEach( + demandSeriesValues -> { + oldDemandValues.add(demandSeriesValues.getDemand()); + } + ); + } + ); + + for (int i = 0; i < newDemandValues.size(); i++) { + if (!Objects.equals(oldDemandValues.get(i), newDemandValues.get(i))) { + alertService.triggerDemandAlertsIfNeeded(userID, true, oldDemandValues.get(i), newDemandValues.get(i)); + } + } + } + private List getAllDemands() { return materialDemandRepository.findAll(); } diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/FavoriteServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/FavoriteServiceImpl.java index 7b505dfd..abefa2b4 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/FavoriteServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/FavoriteServiceImpl.java @@ -23,6 +23,12 @@ package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl; import eclipse.tractusx.demand_capacity_mgmt_specification.model.*; +import java.sql.Timestamp; +import java.time.Instant; +import java.util.ArrayList; +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.*; @@ -32,13 +38,6 @@ import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.FavoriteService; import org.springframework.stereotype.Service; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - @RequiredArgsConstructor @Service @Slf4j diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java index 69616cd2..1ba38638 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java @@ -30,6 +30,7 @@ import eclipse.tractusx.demand_capacity_mgmt_specification.model.Role; import eclipse.tractusx.demand_capacity_mgmt_specification.model.TokenResponse; import eclipse.tractusx.demand_capacity_mgmt_specification.model.User; +import java.util.*; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.UserEntity; @@ -46,8 +47,6 @@ import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; -import java.util.*; - @RequiredArgsConstructor @Service @Slf4j @@ -95,14 +94,12 @@ private void logoutToken(String refreshToken) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(formData) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ) - .onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ).onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak"))) .bodyToMono(Void.class) .block(); } @@ -122,13 +119,13 @@ private TokenResponse loginToken(String username, String password) { .bodyValue(formData) .retrieve() .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ) - .onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ) + .onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(TokenResponse.class) .block(); } @@ -146,14 +143,13 @@ private TokenResponse refreshToken(String refreshToken) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(formData) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ) - .onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ).onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(TokenResponse.class) .block(); } @@ -166,14 +162,13 @@ public IntrospectTokenResponse introspectToken(String token) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue("client_id=" + clientId + "&client_secret=" + clientSecret + "&token=" + token) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ) - .onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ).onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(IntrospectTokenResponse.class) .block(); } @@ -217,17 +212,17 @@ private UserEntity generateUser(String userID, DecodedJWT decodedJWT) { newUserEntity.setEmail(Optional.ofNullable(decodedJWT.getClaim("email")).map(Claim::asString).orElse("")); newUserEntity.setName(Optional.ofNullable(decodedJWT.getClaim("given_name")).map(Claim::asString).orElse("")); newUserEntity.setLastName( - Optional.ofNullable(decodedJWT.getClaim("family_name")).map(Claim::asString).orElse("") + Optional.ofNullable(decodedJWT.getClaim("family_name")).map(Claim::asString).orElse("") ); newUserEntity.setUsername( - Optional.ofNullable(decodedJWT.getClaim("preferred_username")).map(Claim::asString).orElse("") + Optional.ofNullable(decodedJWT.getClaim("preferred_username")).map(Claim::asString).orElse("") ); Claim rolesClaim = decodedJWT.getClaim("realm_access"); Map realmAccessMap = Optional - .ofNullable(rolesClaim) - .map(Claim::asMap) - .orElse(Collections.emptyMap()); + .ofNullable(rolesClaim) + .map(Claim::asMap) + .orElse(Collections.emptyMap()); Object rolesObject = realmAccessMap.get("roles"); @@ -238,7 +233,7 @@ private UserEntity generateUser(String userID, DecodedJWT decodedJWT) { String roleStr = (String) roleObj; try { org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.Role role = org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.Role.valueOf( - roleStr + roleStr ); newUserEntity.setRole(role); break; @@ -262,17 +257,17 @@ private User convertUserEntity(UserEntity userEntity, String accessToken, String user.setAccessToken(accessToken); user.setRefreshToken(refreshToken); user.setExpiresIn(expiresIn); - statusManager.calculateBottleneck(user.getUserID(), false); - statusManager.calculateTodos(user.getUserID()); + // statusManager.calculateBottleneck(user.getUserID(), false); + // statusManager.calculateTodos(user.getUserID()); return user; } private String tokenUrl() { - return String.format("%s/auth/realms/%s/protocol/openid-connect/token", keycloakBaseUrl, realm); + return String.format("%s/realms/%s/protocol/openid-connect/token", keycloakBaseUrl, realm); } private String introspectTokenUrl() { - return String.format("%s/auth/realms/%s/protocol/openid-connect/token/introspect", keycloakBaseUrl, realm); + return String.format("%s/realms/%s/protocol/openid-connect/token/introspect", keycloakBaseUrl, realm); } private String logoutTokenUrl() { diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/StatusManagerImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/StatusManagerImpl.java index 91695b0b..b241b72f 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/StatusManagerImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/StatusManagerImpl.java @@ -22,6 +22,11 @@ package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; @@ -33,12 +38,6 @@ 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.*; -import java.util.stream.Collectors; - @RequiredArgsConstructor @Service @Slf4j @@ -55,19 +54,19 @@ public class StatusManagerImpl implements StatusManager { @Override public void calculateTodos(String userID) { userRepository - .findById(UUID.fromString(userID)) - .ifPresent( - user -> { - List demands = fetchDemandsBasedOnRole(user, userID); + .findById(UUID.fromString(userID)) + .ifPresent( + user -> { + List demands = fetchDemandsBasedOnRole(user, userID); - StatusesEntity statusesEntity = statusesRepository - .findByUserID(UUID.fromString(userID)) - .orElseGet(() -> generateNewEntity(userID)); + StatusesEntity statusesEntity = statusesRepository + .findByUserID(UUID.fromString(userID)) + .orElseGet(() -> generateNewEntity(userID)); - statusesEntity.setTodosCount(demands.size()); - statusesRepository.save(statusesEntity); - } - ); + statusesEntity.setTodosCount(demands.size()); + statusesRepository.save(statusesEntity); + } + ); } private StatusesEntity generateNewEntity(String userID) { @@ -78,12 +77,28 @@ private List fetchDemandsBasedOnRole(UserEntity user, Stri List demands = new ArrayList<>(); if (user.getRole().equals(Role.CUSTOMER)) { - demands = materialDemandRepository.findAll() //TODO SUPPLIER AQUI findbysupplierID + demands = + materialDemandRepository + .findAll() //TODO SUPPLIER AQUI findbysupplierID .stream() - .filter(d -> d.getDemandSeries().stream().allMatch(series -> series.getDemandSeriesValues().stream().allMatch(value -> value.getDemand() == 0))) + .filter( + d -> + d + .getDemandSeries() + .stream() + .allMatch( + series -> + series + .getDemandSeriesValues() + .stream() + .allMatch(value -> value.getDemand() == 0) + ) + ) .collect(Collectors.toList()); } else if (user.getRole().equals(Role.SUPPLIER)) { - demands = materialDemandRepository.findAll() //TODO CUSTOMER AQUI findbycustomerID + demands = + materialDemandRepository + .findAll() //TODO CUSTOMER AQUI findbycustomerID .stream() .filter(d -> d.getLinkStatus() == EventType.UN_LINKED) .collect(Collectors.toList()); @@ -91,7 +106,6 @@ private List fetchDemandsBasedOnRole(UserEntity user, Stri return demands; } - @Override public void calculateBottleneck(String userID, boolean postLog) { UserEntity user = getUser(userID).orElseThrow(() -> new IllegalArgumentException("User not found")); @@ -122,20 +136,20 @@ private void updateAndLogStatus(String userID, boolean postLog, int improvements if (improvements > 0) { logEvent( - EventType.STATUS_IMPROVEMENT, - userID, - postLog, - "Status improved for " + improvements + " weeks", - cgID + EventType.STATUS_IMPROVEMENT, + userID, + postLog, + "Status improved for " + improvements + " weeks", + cgID ); } if (degradations > 0) { logEvent( - EventType.STATUS_REDUCTION, - userID, - postLog, - "Status degraded for " + degradations + " weeks", - cgID + EventType.STATUS_REDUCTION, + userID, + postLog, + "Status degraded for " + degradations + " weeks", + cgID ); } @@ -155,7 +169,7 @@ private StatusesEntity createInitialStatus(String userID) { private Pair processCapacityGroup(String userID, CapacityGroupEntity cgs, boolean postLog) { List matchedEntities = matchedDemandsRepository.findByCapacityGroupID( - cgs.getId() + cgs.getId() ); int weeklyImprovements = 0; @@ -165,7 +179,7 @@ private Pair processCapacityGroup(String userID, CapacityGroup for (LinkedCapacityGroupMaterialDemandEntity entity : matchedEntities) { Optional materialDemand = materialDemandRepository.findById( - entity.getMaterialDemandID() + entity.getMaterialDemandID() ); if (materialDemand.isPresent()) { Map weeklyDemands = getWeeklyDemands(materialDemand.get().getDemandSeries()); @@ -197,15 +211,15 @@ private Pair processCapacityGroup(String userID, CapacityGroup private Map getWeeklyDemands(List matchedDemandSeries) { return matchedDemandSeries - .stream() - .flatMap(demand -> demand.getDemandSeriesValues().stream()) - .filter(value -> !value.getCalendarWeek().isBefore(TWO_WEEKS_FROM_NOW)) - .collect( - Collectors.groupingBy( - DemandSeriesValues::getCalendarWeek, - Collectors.summingDouble(DemandSeriesValues::getDemand) - ) - ); + .stream() + .flatMap(demand -> demand.getDemandSeriesValues().stream()) + .filter(value -> !value.getCalendarWeek().isBefore(TWO_WEEKS_FROM_NOW)) + .collect( + Collectors.groupingBy( + DemandSeriesValues::getCalendarWeek, + Collectors.summingDouble(DemandSeriesValues::getDemand) + ) + ); } private void logEvent(EventType eventType, String userID, boolean postLog, String descriptionOverride, UUID cgID) { @@ -220,7 +234,7 @@ private void logEvent(EventType eventType, String userID, boolean postLog, Strin logEntity.setLogID(UUID.randomUUID()); logEntity.setDescription( - Optional.ofNullable(descriptionOverride).orElseGet(() -> getEventDescription(eventType)) + Optional.ofNullable(descriptionOverride).orElseGet(() -> getEventDescription(eventType)) ); if (logEntity.getDescription() != null) { loggingRepository.save(logEntity); diff --git a/demand-capacity-mgmt-frontend/src/contexts/InfoMenuContextProvider.tsx b/demand-capacity-mgmt-frontend/src/contexts/InfoMenuContextProvider.tsx index 16ace9f9..594a6505 100644 --- a/demand-capacity-mgmt-frontend/src/contexts/InfoMenuContextProvider.tsx +++ b/demand-capacity-mgmt-frontend/src/contexts/InfoMenuContextProvider.tsx @@ -23,7 +23,7 @@ import React, { FunctionComponent, createContext, useCallback, useContext, useEffect, useState } from 'react'; -import { InfoMenuData } from '../interfaces/infomenu_interfaces'; +import { InfoMenuData } from '../interfaces/InfoMenu_interfaces'; import createAPIInstance from "../util/Api"; import { CapacityGroupContext } from './CapacityGroupsContextProvider'; import { DemandContext } from './DemandContextProvider'; diff --git a/demand-capacity-mgmt-specification/src/main/resources/openapi.yml b/demand-capacity-mgmt-specification/src/main/resources/openapi.yml index c34f15bb..6f45574f 100644 --- a/demand-capacity-mgmt-specification/src/main/resources/openapi.yml +++ b/demand-capacity-mgmt-specification/src/main/resources/openapi.yml @@ -331,6 +331,77 @@ paths: $ref: '#/components/schemas/LoggingHistoryResponse' 404: description: loggingHistory not found + + /alerts: + post: + tags: + - alerts + summary: configureAlert + operationId: configureAlert + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/AlertRequest' + responses: + 200: + description: General greeting + content: + application/json: + schema: + $ref: '#/components/schemas/AlertResponse' + + get: + tags: + - alerts + summary: get alerts + operationId: getAlerts + responses: + 200: + description: General greeting + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/AlertResponse' + + /triggeredAlerts: + post: + tags: + - alerts + summary: configureTriggeredAlert + operationId: configureTriggeredAlert + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/TriggeredAlertRequest' + responses: + 200: + description: General greeting + content: + application/json: + schema: + $ref: '#/components/schemas/TriggeredAlertResponse' + + get: + tags: + - alerts + summary: get triggered alerts + operationId: getTriggeredAlerts + responses: + 200: + description: General greeting + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/TriggeredAlertResponse' + /statuses: post: tags: @@ -959,6 +1030,97 @@ components: statusDegradation: type: integer + AlertRequest: + type: object + properties: + alertId: + type: string + alertName: + type: string + monitoredObjects: + type: string + created: + type: string + type: + type: string + threshold: + type: number + description: + type: string + user: + type: string + + + TriggeredAlertRequest: + type: object + properties: + alertId: + type: string + alertName: + type: string + monitoredObjects: + type: string + created: + type: string + triggerTimes: + type: number + triggerTimesInThreeMonths: + type: number + type: + type: string + threshold: + type: number + description: + type: string + user: + type: string + + AlertResponse: + type: object + properties: + alertId: + type: string + alertName: + type: string + monitoredObjects: + type: string + created: + type: string + type: + type: string + threshold: + type: string + description: + type: string + user: + type: string + + + TriggeredAlertResponse: + type: object + properties: + alertId: + type: string + alertName: + type: string + monitoredObjects: + type: string + created: + type: string + triggerTimes: + type: integer + triggerTimesInThreeMonths: + type: integer + type: + type: string + threshold: + type: string + description: + type: string + user: + type: string + + DemandRequestDto: type: object properties: From 9efd0a251cb659a3f9428a3eea13e2f662b3a2c6 Mon Sep 17 00:00:00 2001 From: Saja Adem Date: Thu, 16 Nov 2023 09:59:33 +0100 Subject: [PATCH 2/2] Applied Review Comments --- .../controllers/AlertController.java | 2 +- .../entities/AlertEntity.java | 16 ++- .../entities/DedicatedAlertEntity.java | 33 +++++ .../services/AlertService.java | 3 +- .../services/impl/AlertServiceImpl.java | 121 ++++++++++++------ .../services/impl/DemandServiceImpl.java | 13 +- .../impl/SecurityTokenServiceImpl.java | 62 ++++----- .../src/main/resources/openapi.yml | 20 +++ 8 files changed, 187 insertions(+), 83 deletions(-) create mode 100644 demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/DedicatedAlertEntity.java diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java index f55437d9..3080c226 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/controllers/AlertController.java @@ -56,7 +56,7 @@ public ResponseEntity configureTriggeredAlert(TriggeredA @Override public ResponseEntity> getAlerts() throws Exception { String userID = UserUtil.getUserID(request); - return ResponseEntity.status(HttpStatus.OK).body(alertService.getAlerts(userID)); // ResponseEntity.status(HttpStatus.OK).body(alertService.getAlerts(userID)); + return ResponseEntity.status(HttpStatus.OK).body(alertService.getAlerts(userID)); } @Override diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java index 0c2cfa00..6af4f346 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/AlertEntity.java @@ -1,11 +1,9 @@ package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities; import jakarta.persistence.*; +import java.util.List; import java.util.UUID; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; +import lombok.*; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertThresholdType; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertsMonitoredObjects; @@ -18,8 +16,8 @@ public class AlertEntity { @Id - // @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") + @GeneratedValue + @Column(columnDefinition = "uuid", updatable = false, name = "id") private UUID id; @Column(name = "user_id") @@ -44,4 +42,10 @@ public class AlertEntity { @Column(name = "description") private String description; + + @ToString.Exclude + @EqualsAndHashCode.Exclude + @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY) + @JoinColumn(name = "alert_id") + private List dedicatedAlerts; } diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/DedicatedAlertEntity.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/DedicatedAlertEntity.java new file mode 100644 index 00000000..98f933fd --- /dev/null +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/entities/DedicatedAlertEntity.java @@ -0,0 +1,33 @@ +package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities; + +import jakarta.persistence.*; +import java.util.List; +import java.util.UUID; +import lombok.*; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.EventObjectType; + +@Entity +@Table(name = "dedicated_alerts") +@Builder +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DedicatedAlertEntity { + + @Id + @GeneratedValue + @Column(columnDefinition = "uuid", updatable = false, name = "id") + private UUID id; + + @Column(name = "object_id") + private UUID objectId; + + @Column(name = "type") + @Enumerated(EnumType.STRING) + private EventObjectType type; + + @ManyToOne(fetch = FetchType.LAZY) + @ToString.Exclude + @EqualsAndHashCode.Exclude + private AlertEntity alertEntity; +} diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java index 50b145e4..40cf9395 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/AlertService.java @@ -32,7 +32,8 @@ void triggerDemandAlertsIfNeeded( String userID, boolean isMaterialDemandChange, double oldDemandValue, - double newDemandValue + double newDemandValue, + String materialDemandId ); List getAlerts(String userID); List getTriggeredAlerts(String userID); diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java index 7c4b8581..bb3903bb 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/AlertServiceImpl.java @@ -21,13 +21,11 @@ */ package org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.impl; -import eclipse.tractusx.demand_capacity_mgmt_specification.model.AlertRequest; -import eclipse.tractusx.demand_capacity_mgmt_specification.model.AlertResponse; -import eclipse.tractusx.demand_capacity_mgmt_specification.model.TriggeredAlertRequest; -import eclipse.tractusx.demand_capacity_mgmt_specification.model.TriggeredAlertResponse; +import eclipse.tractusx.demand_capacity_mgmt_specification.model.*; import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import lombok.RequiredArgsConstructor; @@ -35,6 +33,7 @@ import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.*; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertThresholdType; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.AlertsMonitoredObjects; +import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.entities.enums.EventObjectType; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories.AlertsRepository; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.repositories.TriggeredAlertsRepository; import org.eclipse.tractusx.demandcapacitymgmt.demandcapacitymgmtbackend.services.AlertService; @@ -56,12 +55,14 @@ public AlertResponse configureAlert(AlertRequest alertRequest) { alertsRepository.save(alertEntity); return convertAlertsResponseDto(alertEntity); } + @Override public void triggerDemandAlertsIfNeeded( String userID, boolean isMaterialDemandChange, double oldValue, - double newValue + double newValue, + String materialDemandId ) { List alerts = alertsRepository.findAll(); // TODO : only bring my alerts alerts.forEach( @@ -76,17 +77,8 @@ public void triggerDemandAlertsIfNeeded( triggeredAlertEntity.setThreshold(alertEntity.getThreshold()); LocalDateTime currentLocalDateTime = LocalDateTime.now(); triggeredAlertEntity.setCreated(Timestamp.valueOf(currentLocalDateTime).toString()); - //triggeredAlertEntity.setTriggerTimesInThreeMonths(alertEntity.getTriggerTimesInThreeMonths()); - //triggeredAlertEntity.setTriggerTimes(alertEntity.getTriggerTimes()); - - if ( - alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_DEMANDS) || - ( - alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_CAPACITIES) && - !isMaterialDemandChange - ) || - alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_OBJECTS) - ) { + // TODO : Adjust trigger times + if (isGlobalAlert(isMaterialDemandChange, alertEntity)) { if (alertEntity.getType().equals(AlertThresholdType.RELATIVE)) { double threshold = alertEntity.getThreshold(); double demandDelta = threshold * oldValue; @@ -100,33 +92,52 @@ public void triggerDemandAlertsIfNeeded( } } } else if (alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.DEDICATED)) { - if (alertEntity.getType().equals(AlertThresholdType.ABSOLUTE)) { - double threshold = alertEntity.getThreshold(); - if ( - threshold >= 0 && - (newValue - oldValue >= threshold) || - (threshold < 0 && (newValue - oldValue <= threshold)) - ) { - // TODO : adjust the demand description , trigger times here - triggeredAlertsRepository.save(triggeredAlertEntity); - } - } else { - double threshold = alertEntity.getThreshold(); - double demandDelta = alertEntity.getThreshold() * oldValue; - if ( - threshold >= 0 && - (newValue - oldValue >= demandDelta) || - (threshold < 0 && (newValue - oldValue <= demandDelta)) - ) { - // TODO : adjust the demand description , trigger times here - triggeredAlertsRepository.save(triggeredAlertEntity); - } - } + alertEntity + .getDedicatedAlerts() + .forEach( + dedicatedAlert -> { + if (Objects.equals(materialDemandId, dedicatedAlert.getObjectId().toString())) { + if (alertEntity.getType().equals(AlertThresholdType.ABSOLUTE)) { + double threshold = alertEntity.getThreshold(); + if ( + threshold >= 0 && + (newValue - oldValue >= threshold) || + (threshold < 0 && (newValue - oldValue <= threshold)) + ) { + // TODO : adjust the demand description , trigger times here + triggeredAlertsRepository.save(triggeredAlertEntity); + } + } else { + double threshold = alertEntity.getThreshold(); + double demandDelta = alertEntity.getThreshold() * oldValue; + if ( + threshold >= 0 && + (newValue - oldValue >= demandDelta) || + (threshold < 0 && (newValue - oldValue <= demandDelta)) + ) { + // TODO : adjust the demand description , trigger times here + triggeredAlertsRepository.save(triggeredAlertEntity); + } + } + } + } + ); } } ); } + private static boolean isGlobalAlert(boolean isMaterialDemandChange, AlertEntity alertEntity) { + return ( + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_DEMANDS) || + ( + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_CAPACITIES) && + !isMaterialDemandChange + ) || + alertEntity.getMonitoredObjects().equals(AlertsMonitoredObjects.ALL_OBJECTS) + ); + } + @Override public List getAlerts(String userID) { List alerts = alertsRepository.findAll(); @@ -175,6 +186,12 @@ public TriggeredAlertResponse postTriggeredAlerts(TriggeredAlertRequest triggere } private AlertResponse convertAlertsResponseDto(AlertEntity alertEntity) { + List dedicatedAlerts = alertEntity + .getDedicatedAlerts() + .stream() + .map(this::enrichDedicateAlertResponse) + .toList(); + AlertResponse responseDto = new AlertResponse(); responseDto.setType(alertEntity.getType().name()); responseDto.setAlertId("" + alertEntity.getId()); @@ -184,10 +201,20 @@ private AlertResponse convertAlertsResponseDto(AlertEntity alertEntity) { responseDto.setMonitoredObjects(alertEntity.getMonitoredObjects().name()); responseDto.setThreshold(String.valueOf(alertEntity.getThreshold())); responseDto.setUser(alertEntity.getUserID().toString()); + responseDto.setDedicatedAlerts(dedicatedAlerts); return responseDto; } + DedicatedAlert enrichDedicateAlertResponse(DedicatedAlertEntity alertEntity) { + DedicatedAlert dedicatedAlert = new DedicatedAlert(); + dedicatedAlert.setId(alertEntity.getId().toString()); + dedicatedAlert.setType(alertEntity.getType().toString()); + dedicatedAlert.setObjectId(alertEntity.getObjectId().toString()); + return dedicatedAlert; + } + private TriggeredAlertResponse convertTriggeredAlertsResponseDto(TriggeredAlertEntity alertEntity) { + //TODO: Set triggerTimes TriggeredAlertResponse responseDto = new TriggeredAlertResponse(); responseDto.setType(alertEntity.getType().name()); responseDto.setAlertId("" + alertEntity.getId()); @@ -196,13 +223,26 @@ private TriggeredAlertResponse convertTriggeredAlertsResponseDto(TriggeredAlertE responseDto.setDescription(alertEntity.getDescription()); responseDto.setMonitoredObjects(alertEntity.getMonitoredObjects().name()); responseDto.setThreshold(String.valueOf(alertEntity.getThreshold())); - // responseDto.setTriggerTimes(alertEntity.getTriggerTimes()); - // responseDto.setTriggerTimesInThreeMonths(alertEntity.getTriggerTimesInThreeMonths()); responseDto.setUser(alertEntity.getUserID().toString()); return responseDto; } + DedicatedAlertEntity convertDedicatedAlertsDtoToEntity(DedicatedAlert dedicatedAlert) { + return DedicatedAlertEntity + .builder() + .id(UUID.fromString(dedicatedAlert.getId())) + .type(EventObjectType.valueOf(dedicatedAlert.getType())) + .objectId(UUID.fromString(dedicatedAlert.getObjectId())) + .build(); + } + private AlertEntity convertDtoToEntity(AlertRequest alertRequest) { + List dedicatedAlertEntities = alertRequest + .getDedicatedAlerts() + .stream() + .map(this::convertDedicatedAlertsDtoToEntity) + .toList(); + return AlertEntity .builder() .id(UUID.randomUUID()) @@ -213,6 +253,7 @@ private AlertEntity convertDtoToEntity(AlertRequest alertRequest) { .threshold(Double.parseDouble(alertRequest.getThreshold().toString())) .userID(UUID.fromString(alertRequest.getUser())) .type(AlertThresholdType.valueOf(alertRequest.getType())) + .dedicatedAlerts(dedicatedAlertEntities) .build(); } } diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java index a4e55e25..337c65b0 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/DemandServiceImpl.java @@ -166,7 +166,6 @@ public MaterialDemandResponse updateDemand( } ); - triggerDemandAlertsIfNeeded(demandId, userID, demand); demand = materialDemandRepository.save(demand); @@ -189,10 +188,6 @@ private void triggerDemandAlertsIfNeeded(String demandId, String userID, Materia .forEach( demandSeriesValues -> { newDemandValues.add(demandSeriesValues.getDemand()); - - System.out.println( - "sajaaaaaaa" + demandId + " " + "to" + demandSeriesValues.getDemand() - ); } ); } @@ -216,7 +211,13 @@ private void triggerDemandAlertsIfNeeded(String demandId, String userID, Materia for (int i = 0; i < newDemandValues.size(); i++) { if (!Objects.equals(oldDemandValues.get(i), newDemandValues.get(i))) { - alertService.triggerDemandAlertsIfNeeded(userID, true, oldDemandValues.get(i), newDemandValues.get(i)); + alertService.triggerDemandAlertsIfNeeded( + userID, + true, + oldDemandValues.get(i), + newDemandValues.get(i), + demandId + ); } } } diff --git a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java index 1ba38638..d8865380 100644 --- a/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java +++ b/demand-capacity-mgmt-backend/src/main/java/org/eclipse/tractusx/demandcapacitymgmt/demandcapacitymgmtbackend/services/impl/SecurityTokenServiceImpl.java @@ -94,12 +94,14 @@ private void logoutToken(String refreshToken) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(formData) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ).onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak"))) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ) + .onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(Void.class) .block(); } @@ -119,13 +121,13 @@ private TokenResponse loginToken(String username, String password) { .bodyValue(formData) .retrieve() .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ) - .onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ) + .onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(TokenResponse.class) .block(); } @@ -143,13 +145,14 @@ private TokenResponse refreshToken(String refreshToken) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue(formData) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ).onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ) + .onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(TokenResponse.class) .block(); } @@ -162,13 +165,14 @@ public IntrospectTokenResponse introspectToken(String token) { .contentType(MediaType.APPLICATION_FORM_URLENCODED) .bodyValue("client_id=" + clientId + "&client_secret=" + clientSecret + "&token=" + token) .retrieve() - .onStatus( - HttpStatusCode::is4xxClientError, - response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) - ).onStatus( - HttpStatusCode::is5xxServerError, - response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) - ) + .onStatus( + HttpStatusCode::is4xxClientError, + response -> Mono.error(new RuntimeException("4xx error calling Keycloak")) + ) + .onStatus( + HttpStatusCode::is5xxServerError, + response -> Mono.error(new RuntimeException("5xx error calling Keycloak")) + ) .bodyToMono(IntrospectTokenResponse.class) .block(); } @@ -257,8 +261,8 @@ private User convertUserEntity(UserEntity userEntity, String accessToken, String user.setAccessToken(accessToken); user.setRefreshToken(refreshToken); user.setExpiresIn(expiresIn); - // statusManager.calculateBottleneck(user.getUserID(), false); - // statusManager.calculateTodos(user.getUserID()); + statusManager.calculateBottleneck(user.getUserID(), false); + statusManager.calculateTodos(user.getUserID()); return user; } diff --git a/demand-capacity-mgmt-specification/src/main/resources/openapi.yml b/demand-capacity-mgmt-specification/src/main/resources/openapi.yml index 6f45574f..71e688a4 100644 --- a/demand-capacity-mgmt-specification/src/main/resources/openapi.yml +++ b/demand-capacity-mgmt-specification/src/main/resources/openapi.yml @@ -1049,6 +1049,10 @@ components: type: string user: type: string + dedicatedAlerts: + type: array + items: + $ref: '#/components/schemas/DedicatedAlert' TriggeredAlertRequest: @@ -1075,6 +1079,7 @@ components: user: type: string + AlertResponse: type: object properties: @@ -1094,6 +1099,21 @@ components: type: string user: type: string + dedicatedAlerts: + type: array + items: + $ref: '#/components/schemas/DedicatedAlert' + + DedicatedAlert: + type: object + properties: + id: + type: string + objectId: + type: string + type: + type: string + TriggeredAlertResponse: