Commit 63ff07fa authored by Kostis Trantzas's avatar Kostis Trantzas
Browse files

Merge branch '104-find-currently-active-service-orders-that-have-active-services' into 'develop'

Resolve "Find currently-active Service Orders that have active Services"

See merge request !109
parents 22a371b3 799aa515
Loading
Loading
Loading
Loading
Loading
+35
Changes for src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilder.java: 35 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -60,6 +60,12 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
	@Value("${CATALOG_GET_SERVICEORDER_IDS_BY_STATE}")
	private String CATALOG_GET_SERVICEORDER_IDS_BY_STATE = "";

	@Value("${CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES}")
	private String CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES = "";

	@Value("${CATALOG_GET_ACTIVE_SERVICEORDERS}")
	private String CATALOG_GET_ACTIVE_SERVICEORDERS = "";

	@Value("${CATALOG_UPD_SERVICEORDER_BY_ID}")
	private String CATALOG_UPD_SERVICEORDER_BY_ID = "";

@@ -107,6 +113,35 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
				.unmarshal().json(JsonLibrary.Jackson, Map.class, true)
				.bean(serviceOrderRepoService, "findAllParamsJsonOrderIDs").convertBodyTo(String.class);

		/**
		 * Retrieves the service orders ordered between two dates and, optionally, in a
		 * specific state. Expected headers:
		 * <ul>
		 * <li>startDate: ISO-8601 date or date time, e.g. 2024-01-01 or 2024-01-01T00:00:00Z</li>
		 * <li>endDate: ISO-8601 date or date time</li>
		 * <li>orderstate: e.g. ACKNOWLEDGED. If absent, orders of any state are returned</li>
		 * </ul>
		 * Returns a JSON array of service order summaries
		 */
		from(CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES)
				.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
				.bean(serviceOrderRepoService,
						"findAllByStateBetweenDatesAsString(${header.orderstate}, ${header.startDate}, ${header.endDate})")
				.convertBodyTo(String.class);

		/**
		 * Retrieves the service orders which are currently in force (COMPLETED, already started
		 * and not yet expected to be completed) and have at least one active service.
		 * No headers are expected. Returns a JSON array of service order summaries, each one
		 * carrying the ids of its active services
		 */
		from(CATALOG_GET_ACTIVE_SERVICEORDERS)
				.log(LoggingLevel.INFO, log, CATALOG_GET_ACTIVE_SERVICEORDERS + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
				.bean(serviceOrderRepoService, "findActiveServiceOrdersWithActiveServicesAsString")
				.convertBodyTo(String.class);

		from(CATALOG_GET_SERVICEORDER_BY_ID)
				.log(LoggingLevel.INFO, log, CATALOG_GET_SERVICEORDER_BY_ID + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true")
+40
Changes for src/main/java/org/etsi/osl/tmf/so641/repo/ServiceOrderRepository.java: 40 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -23,6 +23,7 @@ import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import org.etsi.osl.tmf.common.model.UserPartRoleType;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.so641.model.ServiceOrder;
import org.etsi.osl.tmf.so641.model.ServiceOrderStateType;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -53,6 +54,45 @@ public interface ServiceOrderRepository extends JpaRepository<ServiceOrder, Long
			+ "ORDER BY an.date ASC")
	Optional<ServiceOrder> findNotesOfServOrder(String id);

	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate "
			+ "FROM ServiceOrder sor "
			+ "WHERE sor.orderDate >= :starttime AND sor.orderDate <= :endtime "
			+ "AND sor.state = :state "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findByStateBetweenDates(OffsetDateTime starttime, OffsetDateTime endtime, ServiceOrderStateType state);

	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate "
			+ "FROM ServiceOrder sor "
			+ "WHERE sor.orderDate >= :starttime AND sor.orderDate <= :endtime "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findBetweenDates(OffsetDateTime starttime, OffsetDateTime endtime);

	/**
	 * Service orders that are currently in force, together with the uuid of each of their
	 * services that is in one of the given states. There is no mapped association between
	 * ServiceOrder and Service; they are linked through Service.serviceOrder refs, whose id
	 * holds the uuid of the order (same link as ServiceRepository.findServicesFromOrderID).
	 * A null startDate is considered as already started and a null expectedCompletionDate as
	 * open-ended.
	 */
	@Query("SELECT sor.uuid, sor.type, sor.externalId, sor.category, sor.description, sor.state, "
			+ "sor.orderDate, sor.requestedStartDate, sor.requestedCompletionDate, "
			+ "sor.startDate, sor.expectedCompletionDate, sor.completionDate, "
			+ "srv.uuid "
			+ "FROM ServiceOrder sor, Service srv JOIN srv.serviceOrder sref "
			+ "WHERE sref.id = sor.uuid "
			+ "AND sor.state = :orderState "
			+ "AND ( sor.startDate IS NULL OR sor.startDate < :now ) "
			+ "AND ( sor.expectedCompletionDate IS NULL OR sor.expectedCompletionDate > :now ) "
			+ "AND srv.state IN :serviceStates "
			+ "ORDER BY sor.orderDate DESC")
	List<Object[]> findActiveOrdersWithServicesInStates(OffsetDateTime now,
			ServiceOrderStateType orderState, List<ServiceStateType> serviceStates);


	// Methods for metrics

+151
Changes for src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java: 151 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -22,14 +22,18 @@ package org.etsi.osl.tmf.so641.reposervices;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
//import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.hibernate5.jakarta.Hibernate5JakartaModule;

@@ -73,6 +77,10 @@ public class ServiceOrderRepoService {

	private static final transient Log logger = LogFactory.getLog(ServiceOrderRepoService.class.getName());

	/** the service states which are considered as an active service of an order */
	private static final List<ServiceStateType> ACTIVE_SERVICE_STATES =
			List.of(ServiceStateType.ACTIVE, ServiceStateType.RESERVED);

	@Autowired
	ObjectMapper objectMapper;

@@ -291,6 +299,149 @@ public class ServiceOrderRepoService {

	}
	
	/**
	 * Retrieve the service orders which have an orderDate within the given period and
	 * (optionally) are in a specific state. A lean summary of each order is returned.
	 *
	 * @param state     a {@link ServiceOrderStateType} value, e.g. ACKNOWLEDGED. If null or
	 *                  empty, orders of any state are returned
	 * @param startDate the beginning of the period, ISO-8601 (e.g. 2024-01-01T00:00:00Z or
	 *                  2024-01-01). If null, no lower bound is applied
	 * @param endDate   the end of the period, ISO-8601. If null, no upper bound is applied
	 * @return a list of service order summaries
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findAllByStateBetweenDates(String state, String startDate, String endDate) {

		OffsetDateTime starttime = toOffsetDateTime(startDate, OffsetDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC));
		OffsetDateTime endtime = toOffsetDateTime(endDate, OffsetDateTime.now(ZoneOffset.UTC).plusYears(100));

		logger.info("findAllByStateBetweenDates state=" + state + " startDate=" + starttime + " endDate=" + endtime);

		List<Object[]> rows;
		if ((state != null) && (state.trim().length() > 0)) {
			ServiceOrderStateType stateType = ServiceOrderStateType.fromValue(state.trim().toUpperCase());
			if (stateType == null) {
				throw new IllegalArgumentException("There is no such Service Order state: " + state);
			}
			rows = serviceOrderRepo.findByStateBetweenDates(starttime, endtime, stateType);
		} else {
			rows = serviceOrderRepo.findBetweenDates(starttime, endtime);
		}

		List<Map<String, Object>> result = new ArrayList<>();
		for (Object[] row : rows) {
			result.add(toServiceOrderSummary(row));
		}

		return result;
	}

	/**
	 * Same as {@link #findAllByStateBetweenDates(String, String, String)} but the result is
	 * marshaled to a JSON array, so that it can be returned over the message bus.
	 */
	public String findAllByStateBetweenDatesAsString(String state, String startDate, String endDate)
			throws JsonProcessingException {
		return toJsonArray(findAllByStateBetweenDates(state, startDate, endDate));
	}

	/**
	 * Retrieve the service orders which are currently in force, that is they are COMPLETED,
	 * they have already started and they are not expected to be completed yet, and which are
	 * backed by at least one active service (a service in ACTIVE or RESERVED state).
	 *
	 * A null startDate is considered as already started and a null expectedCompletionDate as
	 * open-ended, so that orders created without requested dates are not silently dropped.
	 *
	 * @return a list of service order summaries, each one carrying under "activeServices" the
	 *         ids of its services which are active
	 */
	@Transactional(readOnly = true)
	public List<Map<String, Object>> findActiveServiceOrdersWithActiveServices() {

		OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
		logger.info("findActiveServiceOrdersWithActiveServices now=" + now);

		List<Object[]> rows = serviceOrderRepo.findActiveOrdersWithServicesInStates(now,
				ServiceOrderStateType.COMPLETED, ACTIVE_SERVICE_STATES);

		// an order appears once per active service, so fold the rows per order.
		// A LinkedHashMap preserves the orderDate DESC ordering of the query
		Map<String, Map<String, Object>> ordersByUuid = new LinkedHashMap<>();
		for (Object[] row : rows) {
			String orderUuid = (String) row[0];
			Map<String, Object> so = ordersByUuid.get(orderUuid);
			if (so == null) {
				so = toServiceOrderSummary(row);
				so.put("activeServices", new ArrayList<String>());
				ordersByUuid.put(orderUuid, so);
			}
			@SuppressWarnings("unchecked")
			List<String> activeServices = (List<String>) so.get("activeServices");
			activeServices.add((String) row[12]);
		}

		return new ArrayList<>(ordersByUuid.values());
	}

	/**
	 * Same as {@link #findActiveServiceOrdersWithActiveServices()} but the result is marshaled
	 * to a JSON array, so that it can be returned over the message bus.
	 */
	public String findActiveServiceOrdersWithActiveServicesAsString() throws JsonProcessingException {
		return toJsonArray(findActiveServiceOrdersWithActiveServices());
	}

	/**
	 * Maps the first 12 columns of a service order scalar projection to a lean summary
	 */
	private Map<String, Object> toServiceOrderSummary(Object[] row) {
		Map<String, Object> so = new LinkedHashMap<>();
		so.put("id", row[0]);
		so.put("@type", row[1]);
		so.put("externalId", row[2]);
		so.put("category", row[3]);
		so.put("description", row[4]);
		so.put("state", row[5] != null ? row[5].toString() : null);
		so.put("orderDate", row[6]);
		so.put("requestedStartDate", row[7]);
		so.put("requestedCompletionDate", row[8]);
		so.put("startDate", row[9]);
		so.put("expectedCompletionDate", row[10]);
		so.put("completionDate", row[11]);
		return so;
	}

	private String toJsonArray(List<Map<String, Object>> summaries) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new Hibernate5JakartaModule());
		mapper.registerModule(new JavaTimeModule());
		mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		return mapper.writeValueAsString(summaries);
	}

	/**
	 * Accepts either a full ISO-8601 offset date time (2024-01-01T00:00:00Z) or a plain
	 * ISO date (2024-01-01), which is then considered as the start of that day in UTC.
	 */
	private OffsetDateTime toOffsetDateTime(String date, OffsetDateTime defaultValue) {
		if ((date == null) || (date.trim().length() == 0)) {
			return defaultValue;
		}
		String d = date.trim();
		try {
			return OffsetDateTime.parse(d);
		} catch (DateTimeParseException e) {
			try {
				return LocalDate.parse(d).atStartOfDay().atOffset(ZoneOffset.UTC);
			} catch (DateTimeParseException e2) {
				throw new IllegalArgumentException("Cannot parse date: " + date
						+ ". Expecting an ISO-8601 date (2024-01-01) or date time (2024-01-01T00:00:00Z)");
			}
		}
	}

	public String findAllParamsJsonOrderIDs(Map<String, String> allParams) throws JsonProcessingException {
		List<ServiceOrder> lso = findAllParams(allParams);
		ArrayList<String> oids = new ArrayList<>();
+2
Changes for src/main/resources/application-testing.yml: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -123,6 +123,8 @@ CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_GET_INITIAL_SERVICEORDERS_IDS: "jms:queue:CATALOG.GET.INITIAL_SERVICEORDERS"
CATALOG_GET_SERVICEORDER_IDS_BY_STATE: "jms:queue:CATALOG.GET.ACKNOWLEDGED_SERVICEORDERS"
CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES: "jms:queue:CATALOG.GET.SERVICEORDERS_BY_STATE_AND_DATES"
CATALOG_GET_ACTIVE_SERVICEORDERS: "jms:queue:CATALOG.GET.ACTIVE_SERVICEORDERS"
CATALOG_GET_PRODUCTCATALOGS: "jms:queue:CATALOG.GET.PRODUCTCATALOGS"
CATALOG_GET_PRODUCTCATALOG_BY_ID: "jms:queue:CATALOG.GET.PRODUCTCATALOG_BY_ID"
CATALOG_GET_PRODUCTCATALOG_BY_NAME: "jms:queue:CATALOG.GET.PRODUCTCATALOG_BY_NAME"
+2
Changes for src/main/resources/application.yml: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -139,6 +139,8 @@ CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_GET_INITIAL_SERVICEORDERS_IDS: "jms:queue:CATALOG.GET.INITIAL_SERVICEORDERS"
CATALOG_GET_SERVICEORDER_IDS_BY_STATE: "jms:queue:CATALOG.GET.ACKNOWLEDGED_SERVICEORDERS"
CATALOG_GET_SERVICEORDERS_BY_STATE_AND_DATES: "jms:queue:CATALOG.GET.SERVICEORDERS_BY_STATE_AND_DATES"
CATALOG_GET_ACTIVE_SERVICEORDERS: "jms:queue:CATALOG.GET.ACTIVE_SERVICEORDERS"


#SERVICE CATALOGS, CATEGORIES
Loading