Commit a833df1e authored by Kostis Trantzas's avatar Kostis Trantzas
Browse files

Merge branch '120-introduce-a-new-reset-route-for-a-failed-order-is-on-the-branch' into 'develop'

fix for #120

See merge request !117
parents 5cfffc48 adabb620
Loading
Loading
Loading
Loading
Loading
+15
Changes for src/main/java/org/etsi/osl/tmf/so641/api/ServiceOrderApiRouteBuilder.java: 15 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -69,6 +69,9 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
	@Value("${CATALOG_UPD_SERVICEORDER_BY_ID}")
	@Value("${CATALOG_UPD_SERVICEORDER_BY_ID}")
	private String CATALOG_UPD_SERVICEORDER_BY_ID = "";
	private String CATALOG_UPD_SERVICEORDER_BY_ID = "";


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

	@Value("${CATALOG_ADD_SERVICEORDER}")
	@Value("${CATALOG_ADD_SERVICEORDER}")
	private String CATALOG_ADD_SERVICEORDER = "";
	private String CATALOG_ADD_SERVICEORDER = "";
	
	
@@ -154,6 +157,18 @@ public class ServiceOrderApiRouteBuilder extends RouteBuilder {
				.bean(serviceOrderRepoService, "updateServiceOrder(${header.orderid}, ${body})");
				.bean(serviceOrderRepoService, "updateServiceOrder(${header.orderid}, ${body})");
		
		


		/**
		 * Resets a FAILED service order back to INITIAL, clearing its items' supporting service refs.
		 * Expected header: orderid. Body: JSON {"dropItemIds": [...], "note": "..."}.
		 * Replies with the order as JSON (unchanged if it was not FAILED), or null if there is no such order
		 */
		from(CATALOG_UPD_SERVICEORDER_RESET)
				.log(LoggingLevel.INFO, log, CATALOG_UPD_SERVICEORDER_RESET + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
				.json(JsonLibrary.Jackson, Map.class, true)
				.bean(serviceOrderRepoService, "resetServiceOrderAsString(${header.orderid}, ${body})")
				.convertBodyTo(String.class);

		from(CATALOG_ADD_SERVICEORDER)
		from(CATALOG_ADD_SERVICEORDER)
				.log(LoggingLevel.INFO, log, CATALOG_ADD_SERVICEORDER + " message received!")
				.log(LoggingLevel.INFO, log, CATALOG_ADD_SERVICEORDER + " message received!")
				.to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
				.to("log:DEBUG?showBody=true&showHeaders=true").unmarshal()
+135
Changes for src/main/java/org/etsi/osl/tmf/so641/reposervices/ServiceOrderRepoService.java: 135 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -966,6 +966,141 @@ public class ServiceOrderRepoService {
	
	
	
	


	/**
	 * Resets a FAILED service order so that it can be re-planned and fulfilled again.
	 * <ul>
	 * <li>every order item loses its supporting service and resource refs: they point to the services the
	 * failed run created, which the caller terminates. Left in place, the next run would read them back as
	 * TERMINATED and fail the order again. A plain update cannot do this, it only adds refs</li>
	 * <li>the items named in dropItemIds become CANCELLED, so that they are neither fulfilled nor awaited;
	 * every other item becomes INITIAL and keeps its action</li>
	 * <li>the order becomes INITIAL, so it waits to be planned and acknowledged again</li>
	 * <li>when given, the order is re-dated to the new window: the failed run's start is in the past, and
	 * an order that starts in the past cannot be planned. Both names of each date are set, as an approval
	 * that re-dates an order does</li>
	 * </ul>
	 *
	 * @param id                     the service order id
	 * @param dropItemIds            ids of the order items to cancel, may be null
	 * @param note                   the operator's reason, added as a note if not empty
	 * @param startDate              the new start, or null to keep the order's
	 * @param expectedCompletionDate the new completion, or null to keep the order's
	 * @return the order, unchanged when it is not FAILED or the completion is not after the start, or
	 *         null when there is no such order
	 */
	@Transactional
	public ServiceOrder resetServiceOrder(String id, List<String> dropItemIds, String note,
			OffsetDateTime startDate, OffsetDateTime expectedCompletionDate) {

		logger.info("Will resetServiceOrder:" + id + " dropItemIds=" + dropItemIds
				+ " startDate=" + startDate + " expectedCompletionDate=" + expectedCompletionDate);

		ServiceOrder so = this.findByUuid(id);
		if (so == null) {
			return null;
		}
		if (!ServiceOrderStateType.FAILED.equals(so.getState())) {
			logger.warn("resetServiceOrder: order " + id + " is " + so.getState() + ", not FAILED - not reset");
			return so;
		}
		OffsetDateTime newStart = (startDate != null) ? startDate : so.getStartDate();
		OffsetDateTime newEnd = (expectedCompletionDate != null) ? expectedCompletionDate : so.getExpectedCompletionDate();
		boolean reDated = (startDate != null) || (expectedCompletionDate != null);
		if (reDated && (newStart != null) && (newEnd != null) && !newEnd.isAfter(newStart)) {
			logger.warn("resetServiceOrder: order " + id + " completion " + newEnd + " is not after start "
					+ newStart + " - not reset");
			return so;
		}

		Set<String> drop = (dropItemIds != null) ? new HashSet<>(dropItemIds) : Collections.emptySet();
		ServiceStateType initialServiceState = new ServiceRestriction().getState();
		for (ServiceOrderItem soi : so.getOrderItem()) {
			if (soi.getService() != null) {
				soi.getService().getSupportingService().clear();
				soi.getService().getSupportingResource().clear();
				soi.getService().setState(initialServiceState);
			}
			soi.setState(drop.contains(soi.getId()) ? ServiceOrderStateType.CANCELLED : ServiceOrderStateType.INITIAL);
		}

		so.setState(ServiceOrderStateType.INITIAL);
		so.setCompletionDate((OffsetDateTime) null);
		if (startDate != null) {
			so.setStartDate(startDate);
			so.setRequestedStartDate(startDate);
		}
		if (expectedCompletionDate != null) {
			so.setExpectedCompletionDate(expectedCompletionDate);
			so.setRequestedCompletionDate(expectedCompletionDate);
		}

		Note resetNote = new Note();
		resetNote.setText("Service Order reset from FAILED to INITIAL"
				+ (drop.isEmpty() ? "" : ", dropped order items " + drop)
				+ (reDated
						? ", re-dated to " + newStart + " - " + newEnd : "")
				+ (((note != null) && !note.isBlank()) ? ": " + note.trim() : ""));
		resetNote.setAuthor("SO641API-failedOrderReset");
		resetNote.setDate(OffsetDateTime.now(ZoneOffset.UTC));
		so.addNoteItem(resetNote);

		so = this.serviceOrderRepo.saveAndFlush(so);
		raiseSOStateChangedNotification(so);
		return so;
	}

	/**
	 * Same as {@link #resetServiceOrder(String, List, String, OffsetDateTime, OffsetDateTime)}, for the
	 * message bus: the request is a map with "dropItemIds" (a list of order item ids), "note", and the
	 * optional ISO-8601 "startDate" / "expectedCompletionDate"; the reply is the eager order as JSON.
	 * <p>
	 * The transaction is opened here, not by {@link #resetServiceOrder}: that call is made on this, so it
	 * does not pass through the transactional proxy, and the order's lazy item collection would have no
	 * session. The reply is serialised inside the same transaction too, because
	 * {@link #getServiceORderEager} opens a separate session that cannot see the not yet committed reset.
	 */
	@Transactional
	public String resetServiceOrderAsString(String id, Map<String, Object> request) throws JsonProcessingException {
		List<String> dropItemIds = new ArrayList<>();
		String note = null;
		if (request != null) {
			if (request.get("dropItemIds") instanceof Collection<?> ids) {
				for (Object itemId : ids) {
					dropItemIds.add(String.valueOf(itemId));
				}
			}
			if (request.get("note") != null) {
				note = String.valueOf(request.get("note"));
			}
		}
		ServiceOrder so = resetServiceOrder(id, dropItemIds, note,
				dateOf(request, "startDate"), dateOf(request, "expectedCompletionDate"));
		if (so == null) {
			return null;
		}
		Hibernate.initialize(so.getRelatedParty());
		Hibernate.initialize(so.getNote());
		for (ServiceOrderItem soi : so.getOrderItem()) {
			if (soi.getService() != null) {
				Hibernate.initialize(soi.getService().getSupportingService());
				Hibernate.initialize(soi.getService().getSupportingResource());
				Hibernate.initialize(soi.getService().getServiceCharacteristic());
				Hibernate.initialize(soi.getService().getRelatedParty());
			}
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new Hibernate5JakartaModule());
		return mapper.writeValueAsString(so);
	}

	/** An ISO-8601 date of the reset request, or null when it is absent or blank */
	private static OffsetDateTime dateOf(Map<String, Object> request, String key) {
		if ((request == null) || (request.get(key) == null) || String.valueOf(request.get(key)).isBlank()) {
			return null;
		}
		return OffsetDateTime.parse(String.valueOf(request.get(key)).trim());
	}

	public ServiceOrder findByUuid(String id) {
	public ServiceOrder findByUuid(String id) {
		Optional<ServiceOrder> optionalCat = this.serviceOrderRepo.findByUuid(id);
		Optional<ServiceOrder> optionalCat = this.serviceOrderRepo.findByUuid(id);
		return optionalCat.orElse(null);
		return optionalCat.orElse(null);
+1
Changes for src/main/resources/application-testing.yml: 1 added line, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -121,6 +121,7 @@ CATALOG_GET_SERVICEORDERS: "jms:queue:CATALOG.GET.SERVICEORDERS"
CATALOG_GET_SERVICEORDER_BY_ID: "jms:queue:CATALOG.GET.SERVICEORDER_BY_ID"
CATALOG_GET_SERVICEORDER_BY_ID: "jms:queue:CATALOG.GET.SERVICEORDER_BY_ID"
CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_UPD_SERVICEORDER_RESET: "jms:queue:CATALOG.UPD.SERVICEORDER_RESET"
CATALOG_GET_INITIAL_SERVICEORDERS_IDS: "jms:queue:CATALOG.GET.INITIAL_SERVICEORDERS"
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_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_SERVICEORDERS_BY_STATE_AND_DATES: "jms:queue:CATALOG.GET.SERVICEORDERS_BY_STATE_AND_DATES"
+1
Changes for src/main/resources/application.yml: 1 added line, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -137,6 +137,7 @@ CATALOG_GET_SERVICEORDERS: "jms:queue:CATALOG.GET.SERVICEORDERS"
CATALOG_GET_SERVICEORDER_BY_ID: "jms:queue:CATALOG.GET.SERVICEORDER_BY_ID"
CATALOG_GET_SERVICEORDER_BY_ID: "jms:queue:CATALOG.GET.SERVICEORDER_BY_ID"
CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_ADD_SERVICEORDER: "jms:queue:CATALOG.ADD.SERVICEORDER"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_UPD_SERVICEORDER_BY_ID: "jms:queue:CATALOG.UPD.SERVICEORDER_BY_ID"
CATALOG_UPD_SERVICEORDER_RESET: "jms:queue:CATALOG.UPD.SERVICEORDER_RESET"
CATALOG_GET_INITIAL_SERVICEORDERS_IDS: "jms:queue:CATALOG.GET.INITIAL_SERVICEORDERS"
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_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_SERVICEORDERS_BY_STATE_AND_DATES: "jms:queue:CATALOG.GET.SERVICEORDERS_BY_STATE_AND_DATES"
+124
Changes for src/test/java/org/etsi/osl/services/api/so641/ServiceOrderRepoServiceTest.java: 124 added lines, 0 removed lines.
Original line number Original line Diff line number Diff line
@@ -22,6 +22,7 @@ import java.util.stream.Collectors;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.Any;
import org.etsi.osl.tmf.common.model.service.Characteristic;
import org.etsi.osl.tmf.common.model.service.Characteristic;
import org.etsi.osl.tmf.common.model.service.Note;
import org.etsi.osl.tmf.common.model.service.Note;
import org.etsi.osl.tmf.common.model.service.ServiceRef;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.common.model.service.ServiceSpecificationRef;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.common.model.service.ServiceStateType;
import org.etsi.osl.tmf.sim638.model.ServiceCreate;
import org.etsi.osl.tmf.sim638.model.ServiceCreate;
@@ -48,6 +49,8 @@ import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequ
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.WebApplicationContext;




@@ -542,6 +545,127 @@ public class ServiceOrderRepoServiceTest extends BaseIT {
    }
    }




    /**
     * A FAILED order is reset: its items lose the refs of the services the failed run created, the
     * dropped item is cancelled, the others and the order go back to INITIAL
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testResetServiceOrderClearsRefsAndMovesToInitial() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();
        ServiceOrderItem originalItem = createdServiceOrder.getOrderItem().iterator().next();
        String specId = originalItem.getService().getServiceSpecification().getId();

        // a second item, then a failed run: both items carry a created service ref
        ServiceOrderUpdate addItem = new ServiceOrderUpdate();
        addItem.addOrderItemItem(newOrderItem(specId, "secondRestriction", "v"));
        serviceOrderRepoService.updateServiceOrder(soId, addItem);

        ServiceOrderUpdate failed = new ServiceOrderUpdate();
        failed.setState(ServiceOrderStateType.FAILED);
        for (ServiceOrderItem soi : serviceOrderFromDb(soId).getOrderItem()) {
            ServiceOrderItem upd = new ServiceOrderItem();
            upd.setUuid(soi.getId());
            upd.setState(ServiceOrderStateType.FAILED);
            ServiceRestriction restriction = new ServiceRestriction();
            ServiceRef ref = new ServiceRef();
            ref.setId("created-" + soi.getId());
            ref.setName("created");
            restriction.addSupportingServiceItem(ref);
            upd.setService(restriction);
            failed.addOrderItemItem(upd);
        }
        serviceOrderRepoService.updateServiceOrder(soId, failed);
        assertThat(serviceOrderFromDb(soId).getOrderItem())
                .allSatisfy(soi -> assertThat(soi.getService().getSupportingService()).hasSize(1));

        String dropped = originalItem.getId();
        String json = serviceOrderRepoService.resetServiceOrderAsString(soId,
                Map.of("dropItemIds", List.of(dropped), "note", "operator retry"));

        ServiceOrder reset = JsonUtils.toJsonObj(json, ServiceOrder.class);
        assertThat(reset.getState()).isEqualTo(ServiceOrderStateType.INITIAL);
        assertThat(reset.getOrderItem()).hasSize(2);
        for (ServiceOrderItem soi : reset.getOrderItem()) {
            assertThat(soi.getService().getSupportingService()).isEmpty();
            // back to the state a new item's service starts in, never null
            assertThat(soi.getService().getState()).isEqualTo(ServiceStateType.FEASIBILITYCHECKED);
            assertThat(soi.getState()).isEqualTo(soi.getId().equals(dropped)
                    ? ServiceOrderStateType.CANCELLED : ServiceOrderStateType.INITIAL);
        }
        assertThat(reset.getNote()).anySatisfy(n -> assertThat(n.getText()).contains("operator retry"));
    }

    /**
     * Only a FAILED order is reset; any other is returned unchanged, and an unknown order is null
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    public void testResetServiceOrderRefusesOrderThatIsNotFailed() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();
        ServiceOrderStateType before = serviceOrderFromDb(soId).getState();

        ServiceOrder notReset = serviceOrderRepoService.resetServiceOrder(soId, List.of(), null, null, null);
        assertThat(notReset.getState()).isEqualTo(before);
        assertThat(serviceOrderFromDb(soId).getState()).isEqualTo(before);

        assertThat(serviceOrderRepoService.resetServiceOrderAsString("no-such-order", Map.of())).isNull();
    }

    /**
     * The message bus calls the reset with no transaction open, unlike the other tests here, which all
     * run inside the test's own. The reset must open its own, and commit it: it used to fail on the
     * order's lazy item collection
     */
    @WithMockUser(username="osadmin", roles = {"ADMIN","USER"})
    @Test
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void testResetServiceOrderOutsideAnyTransaction() throws Exception {

        ServiceOrder createdServiceOrder = JsonUtils.toJsonObj(createServiceOrder(), ServiceOrder.class);
        String soId = createdServiceOrder.getId();

        ServiceOrderUpdate failed = new ServiceOrderUpdate();
        failed.setState(ServiceOrderStateType.FAILED);
        for (ServiceOrderItem soi : serviceOrderFromDb(soId).getOrderItem()) {
            ServiceOrderItem upd = new ServiceOrderItem();
            upd.setUuid(soi.getId());
            upd.setState(ServiceOrderStateType.FAILED);
            ServiceRestriction restriction = new ServiceRestriction();
            ServiceRef ref = new ServiceRef();
            ref.setId("created-" + soi.getId());
            ref.setName("created");
            restriction.addSupportingServiceItem(ref);
            upd.setService(restriction);
            failed.addOrderItemItem(upd);
        }
        serviceOrderRepoService.updateServiceOrder(soId, failed);

        OffsetDateTime newStart = OffsetDateTime.now(ZoneOffset.UTC).plusDays(1).withNano(0);
        OffsetDateTime newEnd = newStart.plusHours(4);
        String json = serviceOrderRepoService.resetServiceOrderAsString(soId, Map.of("note", "bus call",
                "startDate", newStart.toString(), "expectedCompletionDate", newEnd.toString()));

        ServiceOrder reset = JsonUtils.toJsonObj(json, ServiceOrder.class);
        assertThat(reset.getState()).isEqualTo(ServiceOrderStateType.INITIAL);
        // committed: a separate session reads the reset back, re-dated to the new window
        ServiceOrder stored = serviceOrderFromDb(soId);
        assertThat(stored.getState()).isEqualTo(ServiceOrderStateType.INITIAL);
        assertThat(stored.getStartDate().toInstant()).isEqualTo(newStart.toInstant());
        assertThat(stored.getRequestedStartDate().toInstant()).isEqualTo(newStart.toInstant());
        assertThat(stored.getExpectedCompletionDate().toInstant()).isEqualTo(newEnd.toInstant());
        assertThat(stored.getRequestedCompletionDate().toInstant()).isEqualTo(newEnd.toInstant());
        assertThat(stored.getOrderItem()).allSatisfy(soi -> {
            assertThat(soi.getState()).isEqualTo(ServiceOrderStateType.INITIAL);
            assertThat(soi.getService().getSupportingService()).isEmpty();
        });
    }


    /**
    /**
     * An update of an existing order item that carries only its id and an action
     * An update of an existing order item that carries only its id and an action
     */
     */