forked from folio-org/mod-circulation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlipsResource.java
More file actions
279 lines (238 loc) · 12.8 KB
/
SlipsResource.java
File metadata and controls
279 lines (238 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
package org.folio.circulation.resources;
import static java.util.Collections.emptyList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.Collectors.toSet;
import static org.folio.circulation.support.fetching.RecordFetching.findWithCqlQuery;
import static org.folio.circulation.support.http.client.CqlQuery.exactMatch;
import static org.folio.circulation.support.http.client.CqlQuery.exactMatchAny;
import static org.folio.circulation.support.results.Result.ofAsync;
import static org.folio.circulation.support.results.Result.succeeded;
import static org.folio.circulation.support.results.ResultBinding.flatMapResult;
import static org.folio.circulation.support.utils.LogUtil.collectionAsString;
import static org.folio.circulation.support.utils.LogUtil.multipleRecordsAsString;
import java.lang.invoke.MethodHandles;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.folio.circulation.domain.Item;
import org.folio.circulation.domain.ItemStatus;
import org.folio.circulation.domain.Location;
import org.folio.circulation.domain.MultipleRecords;
import org.folio.circulation.domain.Request;
import org.folio.circulation.domain.RequestType;
import org.folio.circulation.domain.ServicePoint;
import org.folio.circulation.domain.mapper.StaffSlipMapper;
import org.folio.circulation.infrastructure.storage.ServicePointRepository;
import org.folio.circulation.infrastructure.storage.inventory.ItemRepository;
import org.folio.circulation.infrastructure.storage.inventory.LocationRepository;
import org.folio.circulation.infrastructure.storage.users.AddressTypeRepository;
import org.folio.circulation.infrastructure.storage.users.DepartmentRepository;
import org.folio.circulation.infrastructure.storage.users.PatronGroupRepository;
import org.folio.circulation.infrastructure.storage.users.UserRepository;
import org.folio.circulation.resources.context.StaffSlipsContext;
import org.folio.circulation.services.CirculationSettingsService;
import org.folio.circulation.services.RequestFetchService;
import org.folio.circulation.storage.mappers.LocationMapper;
import org.folio.circulation.support.Clients;
import org.folio.circulation.support.RouteRegistration;
import org.folio.circulation.support.http.client.CqlQuery;
import org.folio.circulation.support.http.client.PageLimit;
import org.folio.circulation.support.http.server.JsonHttpResponse;
import org.folio.circulation.support.http.server.WebContext;
import org.folio.circulation.support.results.Result;
import io.vertx.core.http.HttpClient;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
public abstract class SlipsResource extends Resource {
private static final Logger log = LogManager.getLogger(MethodHandles.lookup().lookupClass());
private static final PageLimit LOCATIONS_LIMIT = PageLimit.oneThousand();
private static final String LOCATIONS_KEY = "locations";
private static final String STATUS_NAME_KEY = "status.name";
private static final String TOTAL_RECORDS_KEY = "totalRecords";
private static final String SEARCH_SLIPS_KEY = "searchSlips";
private static final String SERVICE_POINT_ID_PARAM = "servicePointId";
private static final String EFFECTIVE_LOCATION_ID_KEY = "effectiveLocationId";
private static final String PRIMARY_SERVICE_POINT_KEY = "primaryServicePoint";
private final String rootPath;
private final String collectionName;
private final RequestType requestType;
private final Collection<ItemStatus> itemStatuses;
protected SlipsResource(String rootPath, HttpClient client, String collectionName,
RequestType requestType, ItemStatus itemStatus) {
this(rootPath, client, collectionName, requestType, List.of(itemStatus));
}
protected SlipsResource(String rootPath, HttpClient client, String collectionName,
RequestType requestType, Collection<ItemStatus> itemStatuses) {
super(client);
this.rootPath = rootPath;
this.requestType = requestType;
this.itemStatuses = itemStatuses;
this.collectionName = collectionName;
}
@Override
public void register(Router router) {
RouteRegistration routeRegistration = new RouteRegistration(rootPath, router);
routeRegistration.getMany(this::getMany);
}
private void getMany(RoutingContext routingContext) {
final WebContext context = new WebContext(routingContext);
final Clients clients = Clients.create(context, client);
final UUID servicePointId = UUID.fromString(
routingContext.request().getParam(SERVICE_POINT_ID_PARAM));
log.info("getMany:: servicePointId: {}", servicePointId);
isStaffSlipsPrintingDisabled(clients)
.thenCompose(r -> r.after(isPrintingDisabled -> buildStaffSlips(
servicePointId, clients, isPrintingDisabled)))
.thenApply(r -> r.map(JsonHttpResponse::ok))
.thenAccept(context::writeResultToHttpResponse);
}
private CompletableFuture<Result<JsonObject>> buildStaffSlips(UUID servicePointId,
Clients clients, boolean isPrintingDisabled) {
if (isPrintingDisabled) {
return ofAsync(new JsonObject()
.put(collectionName, new JsonArray())
.put(TOTAL_RECORDS_KEY, 0));
}
final var userRepository = new UserRepository(clients);
final var itemRepository = new ItemRepository(clients);
final var addressTypeRepository = new AddressTypeRepository(clients);
final var servicePointRepository = new ServicePointRepository(clients);
final var patronGroupRepository = new PatronGroupRepository(clients);
final var departmentRepository = new DepartmentRepository(clients);
final var requestFetchService = new RequestFetchService(clients, requestType);
return fetchLocationsForServicePoint(servicePointId, clients)
.thenComposeAsync(r -> r.after(ctx -> fetchItemsForLocations(ctx,
itemRepository, LocationRepository.using(clients, servicePointRepository))))
.thenComposeAsync(r -> r.after(requestFetchService::fetchRequests))
.thenComposeAsync(r -> r.after(ctx -> userRepository.findUsersForRequests(
ctx.getRequests())))
.thenComposeAsync(r -> r.after(patronGroupRepository::findPatronGroupsForRequestsUsers))
.thenComposeAsync(r -> r.after(departmentRepository::findDepartmentsForRequestUsers))
.thenComposeAsync(r -> r.after(addressTypeRepository::findAddressTypesForRequests))
.thenComposeAsync(r -> r.after(servicePointRepository::findServicePointsForRequests))
.thenApply(flatMapResult(this::mapResultToJson))
.thenComposeAsync(r -> r.combineAfter(() -> servicePointRepository.getServicePointById(servicePointId),
this::addPrimaryServicePointNameToStaffSlipContext));
}
private CompletableFuture<Result<Boolean>> isStaffSlipsPrintingDisabled(Clients clients) {
if (SEARCH_SLIPS_KEY.equals(collectionName) && requestType == RequestType.HOLD) {
log.info("isStaffSlipsPrintingDisabled:: SEARCH_SLIPS_KEY and HOLD requestType condition met");
return new CirculationSettingsService(clients)
.getPrintHoldRequestsEnabled()
.thenApply(r -> r.map(setting -> !setting.isPrintHoldRequestsEnabled()));
} else {
return ofAsync(false);
}
}
private CompletableFuture<Result<StaffSlipsContext>> fetchLocationsForServicePoint(
UUID servicePointId, Clients clients) {
log.debug("fetchLocationsForServicePoint:: parameters servicePointId: {}", servicePointId);
return findWithCqlQuery(clients.locationsStorage(), LOCATIONS_KEY, new LocationMapper()::toDomain)
.findByQuery(exactMatch(PRIMARY_SERVICE_POINT_KEY, servicePointId.toString()), LOCATIONS_LIMIT)
.thenApply(r -> r.map(locations -> new StaffSlipsContext().withLocations(locations)));
}
private CompletableFuture<Result<StaffSlipsContext>> fetchItemsForLocations(
StaffSlipsContext context, ItemRepository itemRepository,
LocationRepository locationRepository) {
log.debug("fetchPagedItemsForLocations:: multipleLocations: {}",
() -> multipleRecordsAsString(context.getLocations()));
Collection<Location> locations = context.getLocations().getRecords();
Set<String> locationIds = locations.stream()
.map(Location::getId)
.filter(StringUtils::isNoneBlank)
.collect(toSet());
if (locationIds.isEmpty()) {
log.info("fetchPagedItemsForLocations:: locationIds is empty");
return ofAsync(context.withItems(emptyList()));
}
List<String> itemStatusValues = itemStatuses.stream()
.map(ItemStatus::getValue)
.toList();
Result<CqlQuery> statusQuery = exactMatchAny(STATUS_NAME_KEY, itemStatusValues);
return itemRepository.findByIndexNameAndQuery(locationIds, EFFECTIVE_LOCATION_ID_KEY, statusQuery)
.thenComposeAsync(r -> r.after(items -> fetchLocationDetailsForItems(items, locations,
locationRepository)))
.thenApply(r -> r.map(context::withItems));
}
private CompletableFuture<Result<Collection<Item>>> fetchLocationDetailsForItems(
MultipleRecords<Item> items, Collection<Location> locationsForServicePoint,
LocationRepository locationRepository) {
log.debug("fetchLocationDetailsForItems:: parameters items: {}",
() -> multipleRecordsAsString(items));
Set<String> locationIdsFromItems = items.toKeys(Item::getEffectiveLocationId);
Set<Location> locationsForItems = locationsForServicePoint.stream()
.filter(location -> locationIdsFromItems.contains(location.getId()))
.collect(toSet());
if (locationsForItems.isEmpty()) {
log.info("fetchLocationDetailsForItems:: locationsForItems is empty");
return ofAsync(emptyList());
}
return ofAsync(locationsForItems)
.thenComposeAsync(r -> r.after(locationRepository::fetchLibraries))
.thenComposeAsync(r -> r.after(locationRepository::fetchInstitutions))
.thenComposeAsync(r -> r.after(locationRepository::fetchCampuses))
.thenApply(flatMapResult(locations -> matchLocationsToItems(items, locations)));
}
private Result<Collection<Item>> matchLocationsToItems(
MultipleRecords<Item> items, Collection<Location> locations) {
log.debug("matchLocationsToItems:: parameters items: {}, locations: {}",
() -> multipleRecordsAsString(items), () -> collectionAsString(locations));
Map<String, Location> locationsMap = locations.stream()
.collect(toMap(Location::getId, identity(), (a, b) -> a));
return succeeded(items.mapRecords(item -> item.withLocation(
locationsMap.getOrDefault(item.getEffectiveLocationId(),
Location.unknown(item.getEffectiveLocationId()))))
.getRecords());
}
private Result<JsonObject> mapResultToJson(MultipleRecords<Request> requests) {
log.debug("mapResultToJson:: parameters requests: {}", () -> multipleRecordsAsString(requests));
List<JsonObject> representations = requests.getRecords().stream()
.map(StaffSlipMapper::createStaffSlipContext)
.sorted(new ByLocationThenShelvingOrderAlternativelyTitle())
.toList();
JsonObject jsonRepresentations = new JsonObject()
.put(collectionName, representations)
.put(TOTAL_RECORDS_KEY, representations.size());
return succeeded(jsonRepresentations);
}
public static class ByLocationThenShelvingOrderAlternativelyTitle implements Comparator<JsonObject> {
@Override
public int compare(JsonObject firstSlip, JsonObject secondSlip) {
JsonObject item1 = firstSlip.getJsonObject("item");
JsonObject item2 = secondSlip.getJsonObject("item");
if (item1.getString("effectiveLocationSpecific","No effective location specific")
.equals(item2.getString("effectiveLocationSpecific", "No effective location specific"))) {
if (item1.getString("shelvingOrder") == null && item2.getString("shelvingOrder") == null) {
return item1.getString("title").compareTo(item2.getString("title"));
} else {
if (item1.getString("shelvingOrder") == null) {
return 1;
} else if (item2.getString("shelvingOrder") == null) {
return -1;
} else {
return firstSlip.getJsonObject("item").getString("shelvingOrder")
.compareTo(secondSlip.getJsonObject("item").getString("shelvingOrder"));
}
}
} else {
return firstSlip.getJsonObject("item").getString("effectiveLocationSpecific")
.compareTo(secondSlip.getJsonObject("item").getString("effectiveLocationSpecific"));
}
}
}
private JsonObject addPrimaryServicePointNameToStaffSlipContext(JsonObject context,
ServicePoint servicePoint) {
return StaffSlipMapper.addPrimaryServicePointNameToStaffSlipContext(
context, servicePoint, collectionName);
}
}