Search in sources :

Example 1 with Item

use of org.folio.inventory.domain.items.Item in project mod-inventory by folio-org.

the class ItemApiExamples method CanGetAllItemsWithDifferentTemporaryLoanType.

@Test
public void CanGetAllItemsWithDifferentTemporaryLoanType() throws InterruptedException, MalformedURLException, TimeoutException, ExecutionException {
    JsonObject smallAngryInstance = createInstance(smallAngryPlanet(UUID.randomUUID()));
    UUID smallAngryHoldingId = holdingsStorageClient.create(new HoldingRequestBuilder().forInstance(UUID.fromString(smallAngryInstance.getString("id")))).getId();
    itemsClient.create(new ItemRequestBuilder().forHolding(smallAngryHoldingId).book().canCirculate().withBarcode("645398607547"));
    itemsClient.create(new ItemRequestBuilder().forHolding(smallAngryHoldingId).book().canCirculate().temporarilyCourseReserves().withBarcode("175848607547"));
    final var getAllCompleted = okapiClient.get(ApiRoot.items());
    Response getAllResponse = getAllCompleted.toCompletableFuture().get(5, SECONDS);
    assertThat(getAllResponse.getStatusCode(), is(200));
    List<JsonObject> items = JsonArrayHelper.toList(getAllResponse.getJson().getJsonArray("items"));
    assertThat(items.size(), is(2));
    assertThat(getAllResponse.getJson().getInteger("totalRecords"), is(2));
    assertThat(items.stream().filter(item -> StringUtils.equals(item.getString("barcode"), "645398607547")).findFirst().orElse(new JsonObject()).getJsonObject("permanentLoanType").getString("id"), is(ApiTestSuite.getCanCirculateLoanType()));
    assertThat(items.stream().filter(item -> StringUtils.equals(item.getString("barcode"), "645398607547")).findFirst().orElse(new JsonObject()).containsKey("temporaryLoanType"), is(false));
    assertThat(items.stream().filter(item -> StringUtils.equals(item.getString("barcode"), "175848607547")).findFirst().orElse(new JsonObject()).getJsonObject("permanentLoanType").getString("id"), is(ApiTestSuite.getCanCirculateLoanType()));
    assertThat(items.stream().filter(item -> StringUtils.equals(item.getString("barcode"), "175848607547")).findFirst().orElse(new JsonObject()).getJsonObject("temporaryLoanType").getString("id"), is(ApiTestSuite.getCourseReserveLoanType()));
    items.forEach(ItemApiExamples::hasConsistentPermanentLoanType);
    items.forEach(ItemApiExamples::hasConsistentTemporaryLoanType);
    items.forEach(ItemApiExamples::hasConsistentPermanentLocation);
    items.forEach(ItemApiExamples::hasConsistentTemporaryLocation);
}
Also used : Response(org.folio.inventory.support.http.client.Response) CoreMatchers.is(org.hamcrest.CoreMatchers.is) ApiTestSuite.getCanCirculateLoanType(api.ApiTestSuite.getCanCirculateLoanType) InstanceSamples.nod(api.support.InstanceSamples.nod) CoreMatchers(org.hamcrest.CoreMatchers) ApiTestSuite(api.ApiTestSuite) DateTimeZone(org.joda.time.DateTimeZone) URL(java.net.URL) ApiTestSuite.getDvdMaterialType(api.ApiTestSuite.getDvdMaterialType) ApiTestSuite.getMainLibraryLocation(api.ApiTestSuite.getMainLibraryLocation) TimeoutException(java.util.concurrent.TimeoutException) JsonArrayHelper(org.folio.inventory.support.JsonArrayHelper) DATE_KEY(org.folio.inventory.domain.items.CirculationNote.DATE_KEY) Item(org.folio.inventory.domain.items.Item) StringUtils(org.apache.commons.lang3.StringUtils) USER_ID(api.ApiTestSuite.USER_ID) InstanceSamples.girlOnTheTrain(api.support.InstanceSamples.girlOnTheTrain) FIRST_NAME_KEY(org.folio.inventory.domain.user.Personal.FIRST_NAME_KEY) Seconds(org.joda.time.Seconds) JsonObject(io.vertx.core.json.JsonObject) JUnitParamsRunner(junitparams.JUnitParamsRunner) NOTE_TYPE_KEY(org.folio.inventory.domain.items.CirculationNote.NOTE_TYPE_KEY) STAFF_ONLY_KEY(org.folio.inventory.domain.items.CirculationNote.STAFF_ONLY_KEY) ApiRoot(api.support.ApiRoot) CIRCULATION_NOTES_KEY(org.folio.inventory.domain.items.Item.CIRCULATION_NOTES_KEY) ItemRequestBuilder(api.support.builders.ItemRequestBuilder) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) ID_KEY(org.folio.inventory.domain.user.User.ID_KEY) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) Matchers.contains(org.hamcrest.Matchers.contains) InstanceSamples.smallAngryPlanet(api.support.InstanceSamples.smallAngryPlanet) Assert.assertFalse(org.junit.Assert.assertFalse) IndividualResource(org.folio.inventory.support.http.client.IndividualResource) StringUtil.urlEncode(org.folio.util.StringUtil.urlEncode) Parameters(junitparams.Parameters) LAST_NAME_KEY(org.folio.inventory.domain.user.Personal.LAST_NAME_KEY) ResponseMatchers.hasValidationError(support.matchers.ResponseMatchers.hasValidationError) SOURCE_KEY(org.folio.inventory.domain.items.CirculationNote.SOURCE_KEY) ApiTestSuite.getReadingRoomLocation(api.ApiTestSuite.getReadingRoomLocation) CoreMatchers.not(org.hamcrest.CoreMatchers.not) RunWith(org.junit.runner.RunWith) Response(org.folio.inventory.support.http.client.Response) PERSONAL_KEY(org.folio.inventory.domain.user.User.PERSONAL_KEY) InstanceApiClient(api.support.InstanceApiClient) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) BusinessLogicInterfaceUrls.items(api.support.http.BusinessLogicInterfaceUrls.items) HoldingRequestBuilder(api.support.builders.HoldingRequestBuilder) MalformedURLException(java.net.MalformedURLException) CoreMatchers.hasItems(org.hamcrest.CoreMatchers.hasItems) Assert.assertNotNull(org.junit.Assert.assertNotNull) DateTime(org.joda.time.DateTime) Test(org.junit.Test) NOTE_KEY(org.folio.inventory.domain.items.CirculationNote.NOTE_KEY) ApiTests(api.support.ApiTests) ExecutionException(java.util.concurrent.ExecutionException) JsonArray(io.vertx.core.json.JsonArray) Matchers.hasItem(org.hamcrest.Matchers.hasItem) TextDateTimeMatcher.withinSecondsAfter(support.matchers.TextDateTimeMatcher.withinSecondsAfter) Assert(org.junit.Assert) ApiTestSuite.getThirdFloorLocation(api.ApiTestSuite.getThirdFloorLocation) SECONDS(java.util.concurrent.TimeUnit.SECONDS) HoldingRequestBuilder(api.support.builders.HoldingRequestBuilder) JsonObject(io.vertx.core.json.JsonObject) UUID(java.util.UUID) ItemRequestBuilder(api.support.builders.ItemRequestBuilder) Test(org.junit.Test)

Example 2 with Item

use of org.folio.inventory.domain.items.Item in project mod-inventory by folio-org.

the class MoveApi method updateItems.

private void updateItems(RoutingContext routingContext, WebContext context, List<String> idsToUpdate, List<Item> itemsToUpdate) {
    ItemCollection storageItemCollection = storage.getItemCollection(context);
    List<CompletableFuture<Item>> updates = itemsToUpdate.stream().map(storageItemCollection::update).collect(Collectors.toList());
    CompletableFuture.allOf(updates.toArray(new CompletableFuture[0])).handle((vVoid, throwable) -> updates.stream().filter(future -> !future.isCompletedExceptionally()).map(CompletableFuture::join).map(Item::getId).collect(toList())).thenAccept(updatedIds -> respond(routingContext, idsToUpdate, updatedIds));
}
Also used : WebContext(org.folio.inventory.common.WebContext) ItemUtil(org.folio.inventory.support.ItemUtil) WebClient(io.vertx.ext.web.client.WebClient) URL(java.net.URL) Router(io.vertx.ext.web.Router) CompletableFuture(java.util.concurrent.CompletableFuture) Item(org.folio.inventory.domain.items.Item) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ArrayList(java.util.ArrayList) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) HoldingsRecordCollection(org.folio.inventory.domain.HoldingsRecordCollection) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) MoveValidator.holdingsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.holdingsMoveHasRequiredFields) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) JsonArrayHelper.toListOfStrings(org.folio.inventory.support.JsonArrayHelper.toListOfStrings) MalformedURLException(java.net.MalformedURLException) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) JsonResponse.unprocessableEntity(org.folio.inventory.support.http.server.JsonResponse.unprocessableEntity) JsonResponse.success(org.folio.inventory.support.http.server.JsonResponse.success) Collectors(java.util.stream.Collectors) HoldingsRecord(org.folio.HoldingsRecord) Storage(org.folio.inventory.storage.Storage) Objects(java.util.Objects) Collectors.toList(java.util.stream.Collectors.toList) MoveValidator.itemsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.itemsMoveHasRequiredFields) List(java.util.List) ListUtils(org.apache.commons.collections15.ListUtils) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ValidationError(org.folio.inventory.support.http.server.ValidationError) Optional(java.util.Optional) CqlQuery(org.folio.inventory.storage.external.CqlQuery) HttpClient(io.vertx.core.http.HttpClient) CompletableFuture(java.util.concurrent.CompletableFuture) ItemCollection(org.folio.inventory.domain.items.ItemCollection)

Example 3 with Item

use of org.folio.inventory.domain.items.Item in project mod-inventory by folio-org.

the class MoveApi method moveItems.

private void moveItems(RoutingContext routingContext) {
    WebContext context = new WebContext(routingContext);
    JsonObject itemsMoveJsonRequest = routingContext.getBodyAsJson();
    Optional<ValidationError> validationError = itemsMoveHasRequiredFields(itemsMoveJsonRequest);
    if (validationError.isPresent()) {
        unprocessableEntity(routingContext.response(), validationError.get());
        return;
    }
    String toHoldingsRecordId = itemsMoveJsonRequest.getString(TO_HOLDINGS_RECORD_ID);
    List<String> itemIdsToUpdate = toListOfStrings(itemsMoveJsonRequest.getJsonArray(ITEM_IDS));
    storage.getHoldingCollection(context).findById(toHoldingsRecordId).thenAccept(holding -> {
        if (Objects.nonNull(holding)) {
            try {
                CollectionResourceClient itemsStorageClient = createItemStorageClient(createHttpClient(routingContext, context), context);
                MultipleRecordsFetchClient itemsFetchClient = createItemsFetchClient(itemsStorageClient);
                itemsFetchClient.find(itemIdsToUpdate, this::fetchByIdCql).thenAccept(jsons -> {
                    List<Item> itemsToUpdate = updateHoldingsRecordIdForItems(toHoldingsRecordId, jsons);
                    updateItems(routingContext, context, itemIdsToUpdate, itemsToUpdate);
                }).exceptionally(e -> {
                    ServerErrorResponse.internalError(routingContext.response(), e);
                    return null;
                });
            } catch (Exception e) {
                ServerErrorResponse.internalError(routingContext.response(), e);
            }
        } else {
            JsonResponse.unprocessableEntity(routingContext.response(), String.format("Holding with id=%s not found", toHoldingsRecordId));
        }
    }).exceptionally(e -> {
        ServerErrorResponse.internalError(routingContext.response(), e);
        return null;
    });
}
Also used : WebContext(org.folio.inventory.common.WebContext) ItemUtil(org.folio.inventory.support.ItemUtil) WebClient(io.vertx.ext.web.client.WebClient) URL(java.net.URL) Router(io.vertx.ext.web.Router) CompletableFuture(java.util.concurrent.CompletableFuture) Item(org.folio.inventory.domain.items.Item) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ArrayList(java.util.ArrayList) ServerErrorResponse(org.folio.inventory.support.http.server.ServerErrorResponse) JsonResponse(org.folio.inventory.support.http.server.JsonResponse) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) HoldingsRecordCollection(org.folio.inventory.domain.HoldingsRecordCollection) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) MoveValidator.holdingsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.holdingsMoveHasRequiredFields) ItemCollection(org.folio.inventory.domain.items.ItemCollection) JsonObject(io.vertx.core.json.JsonObject) JsonArrayHelper.toListOfStrings(org.folio.inventory.support.JsonArrayHelper.toListOfStrings) MalformedURLException(java.net.MalformedURLException) OkapiHttpClient(org.folio.inventory.support.http.client.OkapiHttpClient) JsonResponse.unprocessableEntity(org.folio.inventory.support.http.server.JsonResponse.unprocessableEntity) JsonResponse.success(org.folio.inventory.support.http.server.JsonResponse.success) Collectors(java.util.stream.Collectors) HoldingsRecord(org.folio.HoldingsRecord) Storage(org.folio.inventory.storage.Storage) Objects(java.util.Objects) Collectors.toList(java.util.stream.Collectors.toList) MoveValidator.itemsMoveHasRequiredFields(org.folio.inventory.validation.MoveValidator.itemsMoveHasRequiredFields) List(java.util.List) ListUtils(org.apache.commons.collections15.ListUtils) HttpServerResponse(io.vertx.core.http.HttpServerResponse) ValidationError(org.folio.inventory.support.http.server.ValidationError) Optional(java.util.Optional) CqlQuery(org.folio.inventory.storage.external.CqlQuery) HttpClient(io.vertx.core.http.HttpClient) Item(org.folio.inventory.domain.items.Item) CollectionResourceClient(org.folio.inventory.storage.external.CollectionResourceClient) WebContext(org.folio.inventory.common.WebContext) JsonObject(io.vertx.core.json.JsonObject) MultipleRecordsFetchClient(org.folio.inventory.storage.external.MultipleRecordsFetchClient) ValidationError(org.folio.inventory.support.http.server.ValidationError) MalformedURLException(java.net.MalformedURLException)

Example 4 with Item

use of org.folio.inventory.domain.items.Item in project mod-inventory by folio-org.

the class ItemUtil method jsonToItem.

public static Item jsonToItem(JsonObject itemRequest) {
    List<String> formerIds = toListOfStrings(itemRequest.getJsonArray(Item.FORMER_IDS_KEY));
    List<String> statisticalCodeIds = toListOfStrings(itemRequest.getJsonArray(Item.STATISTICAL_CODE_IDS_KEY));
    List<String> yearCaption = toListOfStrings(itemRequest.getJsonArray(Item.YEAR_CAPTION_KEY));
    Status status = converterForClass(Status.class).fromJson(itemRequest.getJsonObject(Item.STATUS_KEY));
    List<String> administrativeNotes = toListOfStrings(itemRequest.getJsonArray(Item.ADMINISTRATIVE_NOTES_KEY));
    List<Note> notes = itemRequest.containsKey(Item.NOTES_KEY) ? JsonArrayHelper.toList(itemRequest.getJsonArray(Item.NOTES_KEY)).stream().map(Note::new).collect(Collectors.toList()) : new ArrayList<>();
    List<CirculationNote> circulationNotes = itemRequest.containsKey(Item.CIRCULATION_NOTES_KEY) ? JsonArrayHelper.toList(itemRequest.getJsonArray(Item.CIRCULATION_NOTES_KEY)).stream().map(CirculationNote::new).collect(Collectors.toList()) : new ArrayList<>();
    List<ElectronicAccess> electronicAccess = itemRequest.containsKey(Item.ELECTRONIC_ACCESS_KEY) ? JsonArrayHelper.toList(itemRequest.getJsonArray(Item.ELECTRONIC_ACCESS_KEY)).stream().map(ElectronicAccess::new).collect(Collectors.toList()) : new ArrayList<>();
    List<String> tags = itemRequest.containsKey(Item.TAGS_KEY) ? getTags(itemRequest) : new ArrayList<>();
    String materialTypeId = getNestedProperty(itemRequest, MATERIAL_TYPE, ID);
    String permanentLocationId = getNestedProperty(itemRequest, PERMANENT_LOCATION, ID);
    String temporaryLocationId = getNestedProperty(itemRequest, TEMPORARY_LOCATION, ID);
    String permanentLoanTypeId = getNestedProperty(itemRequest, PERMANENT_LOAN_TYPE, ID);
    String temporaryLoanTypeId = getNestedProperty(itemRequest, TEMPORARY_LOAN_TYPE, ID);
    return new Item(itemRequest.getString(ID), itemRequest.getString(Item.VERSION_KEY), itemRequest.getString(HOLDINGS_RECORD_ID), itemRequest.getString(Item.TRANSIT_DESTINATION_SERVICE_POINT_ID_KEY), status, materialTypeId, permanentLoanTypeId, null).withHrid(itemRequest.getString(Item.HRID_KEY)).withFormerIds(formerIds).withDiscoverySuppress(itemRequest.getBoolean(Item.DISCOVERY_SUPPRESS_KEY)).withBarcode(itemRequest.getString(BARCODE)).withItemLevelCallNumber(itemRequest.getString(Item.ITEM_LEVEL_CALL_NUMBER_KEY)).withEffectiveShelvingOrder(itemRequest.getString(Item.EFFECTIVE_SHELVING_ORDER_KEY)).withItemLevelCallNumberPrefix(itemRequest.getString(Item.ITEM_LEVEL_CALL_NUMBER_PREFIX_KEY)).withItemLevelCallNumberSuffix(itemRequest.getString(Item.ITEM_LEVEL_CALL_NUMBER_SUFFIX_KEY)).withItemLevelCallNumberTypeId(itemRequest.getString(Item.ITEM_LEVEL_CALL_NUMBER_TYPE_ID_KEY)).withVolume(itemRequest.getString(Item.VOLUME_KEY)).withEnumeration(itemRequest.getString(ENUMERATION)).withChronology(itemRequest.getString(CHRONOLOGY)).withNumberOfPieces(itemRequest.getString(NUMBER_OF_PIECES)).withDescriptionOfPieces(itemRequest.getString(Item.DESCRIPTION_OF_PIECES_KEY)).withNumberOfMissingPieces(itemRequest.getString(Item.NUMBER_OF_MISSING_PIECES_KEY)).withMissingPieces(itemRequest.getString(Item.MISSING_PIECES_KEY)).withMissingPiecesDate(itemRequest.getString(Item.MISSING_PIECES_DATE_KEY)).withItemDamagedStatusId(itemRequest.getString(Item.ITEM_DAMAGED_STATUS_ID_KEY)).withItemDamagedStatusDate(itemRequest.getString(Item.ITEM_DAMAGED_STATUS_DATE_KEY)).withPermanentLocationId(permanentLocationId).withTemporaryLocationId(temporaryLocationId).withTemporaryLoanTypeId(temporaryLoanTypeId).withCopyNumber(itemRequest.getString(Item.COPY_NUMBER_KEY)).withAdministrativeNotes(administrativeNotes).withNotes(notes).withCirculationNotes(circulationNotes).withAccessionNumber(itemRequest.getString(Item.ACCESSION_NUMBER_KEY)).withItemIdentifier(itemRequest.getString(Item.ITEM_IDENTIFIER_KEY)).withYearCaption(yearCaption).withElectronicAccess(electronicAccess).withStatisticalCodeIds(statisticalCodeIds).withPurchaseOrderLineIdentifier(itemRequest.getString(Item.PURCHASE_ORDER_LINE_IDENTIFIER)).withLastCheckIn(LastCheckIn.from(itemRequest.getJsonObject(Item.LAST_CHECK_IN))).withTags(tags);
}
Also used : Status(org.folio.inventory.domain.items.Status) Item(org.folio.inventory.domain.items.Item) ElectronicAccess(org.folio.inventory.domain.sharedproperties.ElectronicAccess) Note(org.folio.inventory.domain.items.Note) CirculationNote(org.folio.inventory.domain.items.CirculationNote) CirculationNote(org.folio.inventory.domain.items.CirculationNote)

Example 5 with Item

use of org.folio.inventory.domain.items.Item in project mod-inventory by folio-org.

the class MatchItemEventHandlerUnitTest method shouldNotMatchOnHandleEventPayload.

@Test
public void shouldNotMatchOnHandleEventPayload(TestContext testContext) throws UnsupportedEncodingException {
    Async async = testContext.async();
    doAnswer(ans -> {
        Consumer<Success<MultipleRecords<Item>>> callback = ans.getArgument(2);
        Success<MultipleRecords<Item>> result = new Success<>(new MultipleRecords<>(new ArrayList<>(), 0));
        callback.accept(result);
        return null;
    }).when(itemCollection).findByCql(anyString(), any(PagingParameters.class), any(Consumer.class), any(Consumer.class));
    EventHandler eventHandler = new MatchItemEventHandler(mappingMetadataCache);
    DataImportEventPayload eventPayload = createEventPayload();
    eventHandler.handle(eventPayload).whenComplete((updatedEventPayload, throwable) -> {
        testContext.assertNull(throwable);
        testContext.assertEquals(1, updatedEventPayload.getEventsChain().size());
        testContext.assertEquals(updatedEventPayload.getEventsChain(), singletonList(DI_SRS_MARC_BIB_RECORD_CREATED.value()));
        testContext.assertEquals(DI_INVENTORY_ITEM_NOT_MATCHED.value(), updatedEventPayload.getEventType());
        async.complete();
    });
}
Also used : PagingParameters(org.folio.inventory.common.api.request.PagingParameters) ArrayList(java.util.ArrayList) EventHandler(org.folio.processing.events.services.handler.EventHandler) MatchItemEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchItemEventHandler) Success(org.folio.inventory.common.domain.Success) DataImportEventPayload(org.folio.DataImportEventPayload) Item(org.folio.inventory.domain.items.Item) Consumer(java.util.function.Consumer) MatchItemEventHandler(org.folio.inventory.dataimport.handlers.matching.MatchItemEventHandler) Async(io.vertx.ext.unit.Async) MultipleRecords(org.folio.inventory.common.domain.MultipleRecords) Test(org.junit.Test)

Aggregations

Item (org.folio.inventory.domain.items.Item)74 Test (org.junit.Test)59 Status (org.folio.inventory.domain.items.Status)41 Parameters (junitparams.Parameters)32 JsonObject (io.vertx.core.json.JsonObject)28 PagingParameters (org.folio.inventory.common.api.request.PagingParameters)28 MultipleRecords (org.folio.inventory.common.domain.MultipleRecords)26 Success (org.folio.inventory.common.domain.Success)24 DataImportEventPayload (org.folio.DataImportEventPayload)23 HashMap (java.util.HashMap)20 Consumer (java.util.function.Consumer)20 CompletableFuture (java.util.concurrent.CompletableFuture)16 Record (org.folio.rest.jaxrs.model.Record)14 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)13 ItemCollection (org.folio.inventory.domain.items.ItemCollection)12 Storage (org.folio.inventory.storage.Storage)11 EventHandler (org.folio.processing.events.services.handler.EventHandler)11 List (java.util.List)9 Collectors (java.util.stream.Collectors)9 HoldingsRecord (org.folio.HoldingsRecord)9