001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.petstore.console.orders;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.time.*;
022import java.time.format.DateTimeFormatter;
023import java.util.*;
024
025import org.apache.juneau.commons.beanquery.*;
026import org.apache.juneau.commons.Schema;
027import org.apache.juneau.http.*;
028import org.apache.juneau.http.response.*;
029import org.apache.juneau.marshall.collections.*;
030import org.apache.juneau.petstore.console.*;
031import org.apache.juneau.petstore.console.pages.*;
032import org.apache.juneau.petstore.dto.*;
033import org.apache.juneau.petstore.service.*;
034import org.apache.juneau.rest.server.*;
035import org.apache.juneau.console.datatables.*;
036import org.apache.juneau.console.datatables.adapter.*;
037import org.apache.juneau.rest.server.view.*;
038import org.apache.juneau.rest.server.view.freemarker.*;
039import org.apache.juneau.console.views.*;
040import org.apache.juneau.console.widgets.*;
041
042/**
043 * The Orders page and its endpoints: the server-mode datatable query over BeanQuery, the {@code approve} and
044 * {@code deliver} status transitions, and the cancel dialog form with its {@code DELETE}.
045 *
046 * <h2 class='section'>Example:</h2>
047 * <p class='bjava'>
048 *    <jc>// PLACED to APPROVED; any other status is a 409.</jc>
049 *    <ja>@RestPost</ja>(path=<js>"/{id}/approve"</js>)
050 *    <jk>public</jk> ActionResult approve(RestRequest <jv>req</jv>, <ja>@Path</ja>(<js>"id"</js>) <jk>long</jk> <jv>id</jv>) {
051 *       <jk>return</jk> transition(<jv>req</jv>, <jv>id</jv>, <js>"approve"</js>, OrderStatus.<jsf>PLACED</jsf>, OrderStatus.<jsf>APPROVED</jsf>);
052 *    }
053 * </p>
054 * <p class='bcode'>
055 *    &lt;@card type="datatables" id="orders"&gt;
056 *    { dataMode:'server', dataUrl:'/console/orders/query', rowActions:[{id:'approve', endpoint:'/console/orders/{id}/approve', method:'POST'}] }
057 *    &lt;/@card&gt;
058 * </p>
059 */
060@Rest(path="/orders", title="Orders")
061@SuppressWarnings({
062   "java:S110", // Inheritance depth comes from the BasicRestServlet hierarchy, not this page.
063   "java:S1192" // Route paths and field names repeat as inline literals by design.
064})
065public class OrdersRest extends PetstoreConsolePage implements RowDetailMixin {
066
067   private static final long serialVersionUID = 1L;
068
069   /**
070    * The Orders page.
071    *
072    * @param req The request; {@code ?builder} renders the builder twin.
073    * @return The page.
074    */
075   @RestGet(path="/")
076   public View page(RestRequest req) {
077      return builder(req) ? twin(req, OrdersPageBuilders.orders()) : FreemarkerView.of("orders.ftlh");
078   }
079
080   @SuppressWarnings({
081      "java:S1948" // Servlets are nominally Serializable, but these REST resources are never serialized.
082   })
083   private final RowDetail orderDetail = RowDetails.order(this::lookup);
084
085   @Override
086   public Collection<RowDetail> rowDetails() {
087      return List.of(orderDetail);
088   }
089
090   private Order lookup(String id) {
091      try {
092         return store().getOrder(Long.parseLong(id));
093      } catch (@SuppressWarnings("unused") NumberFormatException e) {
094         return null;
095      }
096   }
097
098   /**
099    * The Pet tab of the order row detail: the pet an order is for, as a one-row table.
100    *
101    * @param orderId The order id.
102    * @return The pet.
103    * @throws NotFound If {@code orderId} is missing or names no order, or its pet is gone.
104    */
105   @RestGet(path="/pet/rows")
106   public List<Pet> petRows(@Query("orderId") Long orderId) {
107      var order = orderId == null ? null : store().getOrder(orderId);
108      var pet = order == null ? null : store().getPet(order.getPetId());
109      if (pet == null)
110         throw new NotFound("Unknown order '%s'", orderId);
111      return List.of(pet);
112   }
113
114   /**
115    * Server-mode DataTables query over all orders.
116    *
117    * <p>
118    * The optional {@code day} query parameter ({@code yyyy-mm-dd}) narrows the orders to those whose ship date falls in
119    * that day's window, before the request's own column filters apply, so the two combine.  A missing, blank or
120    * malformed value is ignored.
121    *
122    * <p>
123    * The optional {@code start} and {@code end} query parameters (the {@code window} URL-state directive's defaults;
124    * each a {@code yyyy-mm-dd} date or an ISO date-time, whose calendar date is used) keep the orders whose ship date
125    * falls between them, both days included, and either may be given alone.  A bound that is blank or malformed is
126    * ignored.  An order with no readable ship date is outside any window that has a usable bound.  The window and
127    * {@code day} combine with each other and with the request's own column filters.
128    *
129    * @param req The DataTables request.
130    * @param day The day to keep, or {@code null}.
131    * @param start The first ship day to keep, or {@code null}.
132    * @param end The last ship day to keep, or {@code null}.
133    * @return One page of orders, or a 200 {@code error} envelope for a malformed search expression.
134    */
135   @RestPost(path="/query")
136   public DataTablesResults<Order> query(@Content DataTablesRequest req, @Query("day") @Schema(aev=true) String day,
137         @Query("start") @Schema(aev=true) String start, @Query("end") @Schema(aev=true) String end) {
138      var wanted = parseDay(day);
139      var from = shipDay(start);
140      var to = shipDay(end);
141      var orders = store().getOrders();
142      if (wanted != null)
143         orders = orders.stream().filter(o -> wanted.equals(shipDay(o.getShipDate()))).toList();
144      if (from != null || to != null)
145         orders = orders.stream().filter(o -> inWindow(shipDay(o.getShipDate()), from, to)).toList();
146      try (var s = PetStore.ORDER_QUERY.getSession(orders)) {
147         return DataTablesQuery.run(req, s);
148      } catch (BeanQuerySyntaxException e) {
149         return DataTablesResults.error(req.getDraw(), e.getMessage());
150      }
151   }
152
153   /** Whether a ship day is inside the window; either bound may be {@code null} (open), and no ship day is never inside. */
154   private static boolean inWindow(LocalDate shipped, LocalDate from, LocalDate to) {
155      return shipped != null && (from == null || ! shipped.isBefore(from)) && (to == null || ! shipped.isAfter(to));
156   }
157
158   private static LocalDate parseDay(String value) {
159      if (value == null)
160         return null;
161      try {
162         return LocalDate.parse(value.trim());
163      } catch (@SuppressWarnings("unused") DateTimeException e) {
164         return null;
165      }
166   }
167
168   /** The calendar date of an order's ship date, which is an ISO date or an ISO date-time; {@code null} if it is neither. */
169   private static LocalDate shipDay(String value) {
170      var day = parseDay(value);
171      if (day != null || value == null)
172         return day;
173      try {
174         return DateTimeFormatter.ISO_DATE_TIME.parse(value.trim(), LocalDate::from);
175      } catch (@SuppressWarnings("unused") DateTimeException e) {
176         return null;
177      }
178   }
179
180   /**
181    * The new-order dialog: pick a pet that is for sale and an optional ship date.
182    *
183    * <p>
184    * The dialog submits to the ribbon item's endpoint.
185    *
186    * @return The modal, on the compact chrome.
187    */
188   @RestGet(path="/new-form")
189   public ModalDef newForm() {
190      var pet = FormDef.Input.of("petId", "Pet", "select").required();
191      store().getPets().stream().filter(p -> p.getStatus() == PetStatus.AVAILABLE)
192         .sorted(Comparator.comparingLong(Pet::getId))
193         .forEach(p -> pet.option(String.valueOf(p.getId()), p.getName()));
194      var form = FormDef.create()
195         .field(pet)
196         .field(FormDef.Input.of("shipDate", "Ship date", "date"));
197      return ModalDef.create("New order: choose a pet").chrome("compact").form(form);
198   }
199
200   /**
201    * Places a new order.
202    *
203    * @param req The request (audit actor).
204    * @param body The order, as the plain {@code {petId, shipDate}} or the dialog envelope {@code {fields:{...}}}.
205    * @return The result toast, carrying the stored order.
206    * @throws BadRequest On a missing body, non-object {@code fields}, missing pet or a bad ship date.
207    * @throws NotFound If the pet does not exist.
208    * @throws Conflict If the pet is not available.
209    */
210   @RestPost(path="/")
211   public ActionResult create(RestRequest req, @Content JsonMap body) {
212      var actor = ConsoleWrites.actor(req);
213      if (body == null)
214         throw new BadRequest("Missing order body");
215      JsonMap fields;
216      try {
217         fields = body.getMap("fields");
218      } catch (Exception e) {
219         throw new BadRequest("Invalid order fields: '%s'", e.getMessage());
220      }
221      if (fields == null && body.get("fields") != null)
222         throw new BadRequest("Invalid order fields: '%s'", body.get("fields"));
223      var f = fields != null ? fields : body;
224      var pet = pet(f.getString("petId"));
225      var order = new Order().setPetId(pet.getId()).setShipDate(shipDate(f.getString("shipDate"))).setStatus(OrderStatus.PLACED);
226      var stored = store().createOrder(order, actor);
227      return ActionResult.success(stored).message(f("Placed order '%s' for '%s'", stored.getId(), pet.getName()));
228   }
229
230   private Pet pet(String id) {
231      if (ib(id))
232         throw new BadRequest("Missing pet");
233      Pet p = null;
234      try {
235         p = store().getPet(Long.parseLong(id.trim()));
236      } catch (NumberFormatException e) {
237         throw new BadRequest("Invalid pet '%s'", id);
238      }
239      if (p == null)
240         throw new NotFound("Unknown pet '%s'", id);
241      if (p.getStatus() != PetStatus.AVAILABLE)
242         throw new Conflict("Pet '%s' is '%s'; only an available pet can be ordered", id, p.getStatus());
243      return p;
244   }
245
246   private static String shipDate(String value) {
247      if (ib(value))
248         return null;
249      try {
250         return LocalDate.parse(value.trim()).toString();
251      } catch (DateTimeException e) {
252         throw new BadRequest("Invalid ship date '%s'", value);
253      }
254   }
255
256   /**
257    * Approves a placed order.
258    *
259    * @param req The request.
260    * @param id The order id.
261    * @return The result toast, carrying the order.
262    * @throws NotFound If the order does not exist.
263    * @throws Conflict If it is not {@code PLACED}.
264    */
265   @RestPost(path="/{id}/approve")
266   public ActionResult approve(RestRequest req, @Path("id") long id) {
267      return transition(req, id, "approve", OrderStatus.PLACED, OrderStatus.APPROVED);
268   }
269
270   /**
271    * Delivers an approved order.
272    *
273    * @param req The request.
274    * @param id The order id.
275    * @return The result toast, carrying the order.
276    * @throws NotFound If the order does not exist.
277    * @throws Conflict If it is not {@code APPROVED}.
278    */
279   @RestPost(path="/{id}/deliver")
280   public ActionResult deliver(RestRequest req, @Path("id") long id) {
281      return transition(req, id, "deliver", OrderStatus.APPROVED, OrderStatus.DELIVERED);
282   }
283
284   /**
285    * The cancel dialog form: a reason and whether to notify the customer.
286    *
287    * @param id The order id.
288    * @return The modal.
289    * @throws NotFound If the order does not exist.
290    */
291   @RestGet(path="/{id}/cancel-form")
292   public ModalDef cancelForm(@Path("id") long id) {
293      require(id);
294      return ModalDef.create(f("Cancel order '%s'", id))
295         .form(FormDef.create()
296            .field(FormDef.Input.of("reason", "Reason", "text"))
297            .field(FormDef.Input.of("notify", "Notify the customer", "checkbox")));
298   }
299
300   /**
301    * Deletes (cancels) an order.
302    *
303    * @param req The request.
304    * @param id The order id.
305    * @return The result toast.
306    * @throws BadRequest If the optional body is not a JSON object.
307    * @throws NotFound If the order does not exist.
308    */
309   @RestDelete(path="/{id}")
310   public ActionResult cancel(RestRequest req, @Path("id") long id) {
311      var actor = ConsoleWrites.actor(req);
312      require(id);
313      var reason = reason(req);
314      store().deleteOrder(id, actor, reason);
315      return ActionResult.success(null).message(f("Cancelled order '%s'", id));
316   }
317
318   /** The optional body: the cancel dialog envelope {@code {fields:{reason, notify}}}, or {@code {reason}} from a plain API call. */
319   private static String reason(RestRequest req) {
320      try {
321         var text = req.getContent().asString();
322         if (ib(text))
323            return null;
324         var body = new JsonMap(text);
325         var fields = body.getMap("fields");
326         return (fields != null ? fields : body).getString("reason");
327      } catch (Exception e) {
328         throw new BadRequest("Invalid cancel body: '%s'", e.getMessage());
329      }
330   }
331
332   private ActionResult transition(RestRequest req, long id, String verb, OrderStatus from, OrderStatus to) {
333      var actor = ConsoleWrites.actor(req);
334      var o = require(id);
335      if (o.getStatus() != from)
336         throw new Conflict("Order '%s' is '%s'; cannot '%s'", id, o.getStatus(), verb);
337      // Update a copy: the live order must not change unless the store accepts the write.
338      var next = new Order().setId(o.getId()).setPetId(o.getPetId()).setShipDate(o.getShipDate()).setStatus(to);
339      return ActionResult.success(store().updateOrder(next, actor)).message(f("Order '%s' %s", id, to));
340   }
341
342   private Order require(long id) {
343      var o = store().getOrder(id);
344      if (o == null)
345         throw new NotFound("Unknown order '%s'", id);
346      return o;
347   }
348}