-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathAdminServiceHandler.java
More file actions
290 lines (254 loc) · 10.4 KB
/
Copy pathAdminServiceHandler.java
File metadata and controls
290 lines (254 loc) · 10.4 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
280
281
282
283
284
285
286
287
288
289
290
package my.bookshop.handlers;
import static cds.gen.adminservice.AdminService_.ORDERS;
import static cds.gen.my.bookshop.Bookshop_.BOOKS;
import cds.gen.adminservice.AdminService;
import cds.gen.adminservice.AdminService_;
import cds.gen.adminservice.Books;
import cds.gen.adminservice.BooksAddToOrderContext;
import cds.gen.adminservice.BooksCovers;
import cds.gen.adminservice.Books_;
import cds.gen.adminservice.OrderItems;
import cds.gen.adminservice.OrderItems_;
import cds.gen.adminservice.Orders;
import cds.gen.adminservice.Upload;
import cds.gen.adminservice.Upload_;
import cds.gen.my.bookshop.Bookshop_;
import com.sap.cds.ql.Select;
import com.sap.cds.ql.Update;
import com.sap.cds.ql.Upsert;
import com.sap.cds.ql.cqn.CqnAnalyzer;
import com.sap.cds.ql.cqn.CqnStructuredTypeRef;
import com.sap.cds.reflect.CdsModel;
import com.sap.cds.services.ErrorStatuses;
import com.sap.cds.services.EventContext;
import com.sap.cds.services.ServiceException;
import com.sap.cds.services.cds.CdsUpdateEventContext;
import com.sap.cds.services.cds.CqnService;
import com.sap.cds.services.draft.DraftCancelEventContext;
import com.sap.cds.services.draft.DraftPatchEventContext;
import com.sap.cds.services.draft.DraftService;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.Before;
import com.sap.cds.services.handler.annotations.On;
import com.sap.cds.services.handler.annotations.ServiceName;
import com.sap.cds.services.messages.Messages;
import com.sap.cds.services.persistence.PersistenceService;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;
import my.bookshop.MessageKeys;
import org.springframework.stereotype.Component;
/**
* Custom business logic for the "Admin Service" (see admin-service.cds)
*
* Handles creating and editing orders.
*/
@Component
@ServiceName(AdminService_.CDS_NAME)
class AdminServiceHandler implements EventHandler {
private final AdminService.Draft adminService;
private final PersistenceService db;
private final Messages messages;
private final CqnAnalyzer analyzer;
AdminServiceHandler(AdminService.Draft adminService, PersistenceService db, Messages messages, CdsModel model) {
this.adminService = adminService;
this.db = db;
this.messages = messages;
// model is a tenant-dependant model proxy
this.analyzer = CqnAnalyzer.create(model);
}
/**
* Validate correctness of an order before finishing the order proces:
* 1. Check Order quantity for each Item and return a message if quantity is empty or <= 0
* 2. Check Order quantity for each Item is available, return message if the stock is too low
*
* @param orders
*/
@Before(event = { CqnService.EVENT_CREATE, CqnService.EVENT_UPSERT, CqnService.EVENT_UPDATE })
public void beforeCreateOrder(Stream<Orders> orders, EventContext context) {
orders.forEach(order -> {
// reset total
order.setTotal(BigDecimal.valueOf(0));
if(order.getItems() != null) {
order.getItems().forEach(orderItem -> {
// validation of the Order creation request
Integer quantity = orderItem.getQuantity();
String bookId = orderItem.getBookId();
if(quantity == null || quantity <= 0 || bookId == null) {
return; // follow up validations rely on these
}
// calculate the actual quantity difference
// FIXME this should handle book changes, currently only quantity changes are handled
int diffQuantity = quantity - db.run(Select.from(Bookshop_.ORDER_ITEMS).columns(i -> i.quantity()).byId(orderItem.getId()))
.first().map(i -> i.getQuantity()).orElse(0);
// check if enough books are available
var result = db.run(Select.from(BOOKS).columns(b -> b.ID(), b -> b.stock(), b -> b.price()).byId(bookId));
result.first().ifPresent(book -> {
if (book.getStock() < diffQuantity) {
// Tip: you can have localized messages and use parameters in your messages
messages.error(MessageKeys.BOOK_REQUIRE_STOCK, book.getStock())
.target(ORDERS, o -> o.Items(i -> i.ID().eq(orderItem.getId()).and(i.IsActiveEntity().eq(orderItem.getIsActiveEntity()))).quantity());
return; // no need to update follow-up values with invalid quantity / stock
}
// update the book with the new stock
book.setStock(book.getStock() - diffQuantity);
db.run(Update.entity(BOOKS).data(book));
// update the amount
BigDecimal updatedAmount = book.getPrice().multiply(BigDecimal.valueOf(quantity));
orderItem.setAmount(updatedAmount);
// update the total
order.setTotal(order.getTotal().add(updatedAmount));
});
});
}
});
}
/*
* Calculate the total order value preview when editing an order item
*/
@Before
public void patchOrderItems(DraftPatchEventContext context, OrderItems_ ref, OrderItems orderItem) {
// check if quantity or book was updated
Integer quantity = orderItem.getQuantity();
String bookId = orderItem.getBookId();
BigDecimal amount = calculateAmountInDraft(ref, quantity, bookId);
if (amount != null) {
orderItem.setAmount(amount);
}
}
/*
* Calculate the total order value preview when deleting an order item from the order
*/
@Before
public void cancelOrderItems(DraftCancelEventContext context, OrderItems_ ref) {
if(ref.asRef().targetSegment().filter().isPresent()) {
calculateAmountInDraft(ref, 0, null);
}
}
private BigDecimal calculateAmountInDraft(OrderItems_ ref, Integer newQuantity, String newBookId) {
Integer quantity = newQuantity;
String bookId = newBookId;
if (quantity == null && bookId == null) {
return null; // nothing changed
}
// get the order item that was updated (to get access to the book price, quantity and order total)
var result = adminService.run(Select.from(ref)
.columns(o -> o.quantity(), o -> o.amount(),
o -> o.book().expand(b -> b.ID(), b -> b.price()),
o -> o.parent().expand(p -> p.ID(), p -> p.total())));
OrderItems itemToPatch = result.single();
BigDecimal bookPrice = null;
// fallback to existing values
if(quantity == null) {
quantity = itemToPatch.getQuantity();
}
if(bookId == null && itemToPatch.getBook() != null) {
bookId = itemToPatch.getBook().getId();
bookPrice = itemToPatch.getBook().getPrice();
}
if(quantity == null || bookId == null) {
return null; // not enough data available
}
// get the price of the updated book ID
if(bookPrice == null) {
var bookResult = db.run(Select.from(BOOKS).byId(bookId).columns(b -> b.price()));
bookPrice = bookResult.single().getPrice();
}
// update the amount of the order item
BigDecimal updatedAmount = bookPrice.multiply(BigDecimal.valueOf(quantity));
// update the order's total
BigDecimal previousAmount = defaultZero(itemToPatch.getAmount());
BigDecimal currentTotal = defaultZero(itemToPatch.getParent().getTotal());
BigDecimal newTotal = currentTotal.subtract(previousAmount).add(updatedAmount);
adminService.patchDraft(Update.entity(ORDERS)
.where(o -> o.ID().eq(itemToPatch.getParent().getId()).and(o.IsActiveEntity().eq(false)))
.data(Orders.TOTAL, newTotal));
return updatedAmount;
}
/**
* Adds a book to an order
* @param context
*/
@On(entity = Books_.CDS_NAME)
public Orders addBookToOrder(BooksAddToOrderContext context) {
String orderId = context.getOrderId();
List<Orders> orders = adminService.run(Select.from(ORDERS).columns(o -> o._all(), o -> o.Items().expand()).where(o -> o.ID().eq(orderId))).list();
Orders order = orders.stream().filter(p -> p.getIsActiveEntity()).findFirst().orElse(null);
// check that the order with given ID exists and is not in draft-mode
if((orders.size() > 0 && order == null) || orders.size() > 1) {
throw new ServiceException(ErrorStatuses.CONFLICT, MessageKeys.ORDER_INDRAFT);
} else if (orders.size() <= 0) {
throw new ServiceException(ErrorStatuses.NOT_FOUND, MessageKeys.ORDER_MISSING);
}
if(order.getItems() == null) {
order.setItems(new ArrayList<>());
}
// get ID of the book on which the action was called (bound action)
String bookId = (String) analyzer.analyze(context.getCqn()).targetKeys().get(Books.ID);
// create order item
OrderItems newItem = OrderItems.create();
newItem.setId(UUID.randomUUID().toString());
newItem.setBookId(bookId);
newItem.setQuantity(context.getQuantity());
order.getItems().add(newItem);
Orders updatedOrder = adminService.run(Update.entity(ORDERS).data(order)).single();
messages.success(MessageKeys.BOOK_ADDED_ORDER);
return updatedOrder;
}
/**
* @return the static CSV singleton upload entity
*/
@On(entity = Upload_.CDS_NAME, event = CqnService.EVENT_READ)
public Upload getUploadSingleton() {
return Upload.create();
}
/**
* Handles CSV uploads with book data
* @param context
* @param csv
*/
@On
public List<Upload> addBooksViaCsv(CdsUpdateEventContext context, Upload upload) {
InputStream is = upload.getCsv();
if (is != null) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
br.lines().skip(1).forEach((line) -> {
String[] p = line.split(";");
Books book = Books.create();
book.setId(p[0]);
book.setTitle(p[1]);
book.setDescr(p[2]);
book.setAuthorId(p[3]);
book.setStock(Integer.valueOf(p[4]).intValue());
book.setPrice(BigDecimal.valueOf(Double.valueOf(p[5])));
book.setCurrencyCode(p[6]);
book.setGenreId(String.valueOf(p[7]));
// separate transaction per line
context.getCdsRuntime().changeSetContext().run(ctx -> {
db.run(Upsert.into(BOOKS).entry(book));
});
});
} catch (IOException e) {
throw new ServiceException(ErrorStatuses.SERVER_ERROR, MessageKeys.BOOK_IMPORT_FAILED, e);
} catch (IndexOutOfBoundsException e) {
throw new ServiceException(ErrorStatuses.SERVER_ERROR, MessageKeys.BOOK_IMPORT_INVALID_CSV, e);
}
}
return Arrays.asList(upload);
}
@Before(event = {CqnService.EVENT_CREATE, CqnService.EVENT_UPDATE, DraftService.EVENT_DRAFT_NEW, DraftService.EVENT_DRAFT_PATCH})
public void restoreCoversUpId(CqnStructuredTypeRef ref, BooksCovers cover) {
// restore up__ID, which is not provided via OData due to containment
cover.setUpId((String) analyzer.analyze(ref).rootKeys().get(Books.ID));
}
private BigDecimal defaultZero(BigDecimal decimal) {
return decimal == null ? BigDecimal.valueOf(0) : decimal;
}
}