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.pets;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023import org.apache.juneau.commons.Schema;
024import org.apache.juneau.commons.beanquery.*;
025import org.apache.juneau.marshall.collections.*;
026import org.apache.juneau.marshall.marshaller.*;
027import org.apache.juneau.marshall.parser.*;
028import org.apache.juneau.http.*;
029import org.apache.juneau.http.response.*;
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 pets JSON endpoints (server-mode datatable query over BeanQuery, create/replace/delete, sell, stage, and the
044 * per-pet feeds), the Pets and Sold pages, the add/edit dialog form, and the P4 pet pages: Summary (inline edit),
045 * Photo, Orders (with a row detail, and one order selected at nav depth 4) and History, whose nav nodes the page
046 * appends under {@code pets} as {@code p<petId>} and {@code o<orderId>}.  The Pending changes page is the
047 * {@link ChangesRest} child.
048 *
049 * <h2 class='section'>Example:</h2>
050 * <p class='bjava'>
051 *    <jc>// The BQ#6 endpoint behind the table.</jc>
052 *    <ja>@RestPost</ja>(path=<js>"/query"</js>)
053 *    <jk>public</jk> DataTablesResults&lt;Pet&gt; query(<ja>@Content</ja> DataTablesRequest <jv>req</jv>) {
054 *       <jk>try</jk> (<jk>var</jk> <jv>s</jv> = store().queryPets()) {
055 *          <jk>return</jk> DataTablesQuery.<jsm>run</jsm>(<jv>req</jv>, <jv>s</jv>);
056 *       }
057 *    }
058 * </p>
059 * <p class='bcode'>
060 *    &lt;@card type="datatables" id="pets"&gt;
061 *    { dataMode:'server', dataUrl:'/console/pets/query', columns:[{key:'name', label:'Name'}, ...] }
062 *    &lt;/@card&gt;
063 * </p>
064 * <p class='bjava'>
065 *    <jc>// The same table in the builder twin.</jc>
066 *    TableSpec.<jsm>create</jsm>(<js>"pets"</js>).dataMode(DataMode.<jsf>SERVER</jsf>).dataUrl(<js>"/console/pets/query"</js>)
067 *       .columns(Column.<jsm>create</jsm>(<js>"name"</js>).label(<js>"Name"</js>));
068 * </p>
069 */
070@Rest(path="/pets", title="Pets", children={ChangesRest.class})
071@SuppressWarnings({
072   "java:S110" // Inheritance depth comes from the BasicRestServlet hierarchy, not this page.
073})
074public class PetsRest extends PetstoreConsolePage implements RowDetailMixin {
075
076   private static final long serialVersionUID = 1L;
077
078   /** The P4 tabs, in nav order. */
079   private static final List<String> TABS = List.of("summary", "photo", "orders", "history");
080
081   @SuppressWarnings({
082      "java:S1948" // Servlets are nominally Serializable, but these REST resources are never serialized.
083   })
084   private final RowDetail petDetail = RowDetails.pet(this::lookup);
085
086   @SuppressWarnings({
087      "java:S1948" // Servlets are nominally Serializable, but these REST resources are never serialized.
088   })
089   private final RowDetail soldDetail = RowDetails.soldPet(this::lookup);
090
091   /**
092    * The Pets page.
093    *
094    * @param req The request; {@code ?mixed} renders the half-FTL variant, {@code ?builder} the builder twin.
095    * @return The page.
096    */
097   @RestGet(path="/")
098   public View page(RestRequest req) {
099      var mixed = req.containsQueryParam("mixed");
100      if (! builder(req))
101         return mixed ? PetsPageBuilders.petsMixed().view(req) : FreemarkerView.of("pets.ftlh");
102      return twin(req, mixed ? PetsPageBuilders.petsMixed() : PetsPageBuilders.pets());
103   }
104
105   /**
106    * The Sold pets page.
107    *
108    * @param req The request; {@code ?builder} renders the builder twin.
109    * @return The page.
110    */
111   @RestGet(path="/sold")
112   public View sold(RestRequest req) {
113      return builder(req) ? twin(req, PetsPageBuilders.sold()) : FreemarkerView.of("pets-sold.ftlh");
114   }
115
116   /** @return The client-mode rows for the Sold page: every sold pet, by id. */
117   @RestGet(path="/sold/rows")
118   public List<Pet> soldRows() {
119      return store().getPets().stream().filter(x -> x.getStatus() == PetStatus.SOLD).sorted(Comparator.comparingLong(Pet::getId)).toList();
120   }
121
122   @Override
123   public Collection<RowDetail> rowDetails() {
124      return List.of(petDetail, soldDetail);
125   }
126
127   private Pet lookup(String id) {
128      try {
129         return store().getPet(Long.parseLong(id));
130      } catch (@SuppressWarnings("unused") NumberFormatException e) {
131         return null;
132      }
133   }
134
135   /**
136    * The Orders tab of the pet row detail: one pet's orders, by id.
137    *
138    * @param petId The pet id.
139    * @return The orders.
140    * @throws NotFound If {@code petId} is missing or names no pet.
141    */
142   @RestGet(path="/orders/rows")
143   public List<Order> scopedOrderRows(@Query("petId") Long petId) {
144      return orderRows(requireScope(petId));
145   }
146
147   /**
148    * The History tab of the pet row detail: one pet's audit rows, oldest first.
149    *
150    * @param petId The pet id.
151    * @return The audit rows.
152    * @throws NotFound If {@code petId} is missing or names no pet.
153    */
154   @RestGet(path="/history/rows")
155   public List<AuditEntry> scopedHistoryRows(@Query("petId") Long petId) {
156      return historyRows(requireScope(petId));
157   }
158
159   private long requireScope(Long petId) {
160      if (petId == null)
161         throw new NotFound("Missing pet");
162      return require(petId).getId();
163   }
164
165   /**
166    * The add/edit dialog form.
167    *
168    * @param id The pet to edit, or <jk>null</jk> to add.
169    * @return The modal.
170    * @throws NotFound If {@code id} names no pet.
171    */
172   @RestGet(path="/form")
173   public ModalDef form(@Query("id") Long id) {
174      var p = id == null ? new Pet().setStatus(PetStatus.AVAILABLE) : require(id);
175      var form = FormDef.create()
176         .field(FormDef.Input.of("name", "Name", "text").required().value(p.getName()));
177      var species = FormDef.Input.of("species", "Species", "select").required();
178      for (var s : Species.values())
179         species.option(s.name(), s.name().charAt(0) + s.name().substring(1).toLowerCase());
180      if (p.getSpecies() != null)
181         species.value(p.getSpecies().name());
182      form.field(species);
183      form.field(FormDef.Input.of("price", "Price (USD)", "text").required().value(id == null ? "" : String.valueOf(p.getPrice())));
184      return ModalDef.create(id == null ? "Add pet" : f("Edit '%s'", p.getName())).form(form);
185   }
186
187   /**
188    * Server-mode DataTables query over all pets.
189    *
190    * <p>
191    * The optional {@code ids} query parameter (comma-separated pet ids, as the {@code ids} URL-state directive sends it)
192    * narrows the pets to those ids, before the request's own column filters apply, so the two combine.  Tokens that are
193    * not numbers are dropped, and a blank value or one with no usable token is ignored.
194    *
195    * @param req The DataTables request.
196    * @param ids The ids to keep, or {@code null}.
197    * @return One page of pets, or a 200 {@code error} envelope for a malformed search expression.
198    */
199   @RestPost(path="/query")
200   public DataTablesResults<Pet> query(@Content DataTablesRequest req, @Query("ids") @Schema(aev=true) String ids) {
201      var wanted = parseIds(ids);
202      var pets = store().getPets();
203      if (wanted != null)
204         pets = pets.stream().filter(p -> wanted.contains(p.getId())).toList();
205      try (var s = PetStore.PET_QUERY.getSession(pets)) {
206         return DataTablesQuery.run(req, s);
207      } catch (BeanQuerySyntaxException e) {
208         // DataTablesQuery maps a bad expression to HTTP 400 by default; the table wants a 200 error envelope it can show.
209         return DataTablesResults.error(req.getDraw(), e.getMessage());
210      }
211   }
212
213   /** The usable ids in a comma-separated value, or {@code null} if there are none (no filter). */
214   @SuppressWarnings({
215      "java:S1168" // null means no filter, distinct from an empty id set
216   })
217   private static Set<Long> parseIds(String value) {
218      if (value == null)
219         return null;
220      var out = new HashSet<Long>();
221      for (var token : value.split(",")) {
222         try {
223            out.add(Long.parseLong(token.trim()));
224         } catch (@SuppressWarnings("unused") NumberFormatException e) {
225            // Not a pet id; dropped.
226         }
227      }
228      return out.isEmpty() ? null : out;
229   }
230
231   /**
232    * Creates a pet.  Status defaults to {@code AVAILABLE}.
233    *
234    * @param req The request (write gate, audit actor).
235    * @param body The new pet, either as the plain pet or as the dialog envelope {@code {fields:{...}}}.
236    * @return The result toast, carrying the stored pet.
237    * @throws BadRequest On a blank name or negative price.
238    */
239   @RestPost(path="/")
240   public ActionResult create(RestRequest req, @Content JsonMap body) {
241      var actor = ConsoleWrites.actor(req);
242      var pet = toPet(body);
243      validate(pet);
244      if (pet.getStatus() == null)
245         pet.setStatus(PetStatus.AVAILABLE);
246      var p = store().createPet(pet, actor);
247      return ActionResult.success(p).message(f("Added '%s'", p.getName()));
248   }
249
250   /**
251    * Replaces a pet.  Name and price are required; a species, tags or photo left out of the body keep their
252    * current values, as does the status.
253    *
254    * @param req The request.
255    * @param id The pet id.
256    * @param body The new state, either as the plain pet or as the dialog envelope {@code {fields:{...}}}.
257    * @return The result toast.
258    * @throws NotFound If the pet does not exist.
259    */
260   @RestPut(path="/{id}")
261   public ActionResult update(RestRequest req, @Path("id") long id, @Content JsonMap body) {
262      // The edit form offers name, species and price but no status, so for a saved edit (for example from the
263      // store treemap) species is the grouping field that can change; status moves only through the sell action.
264      var actor = ConsoleWrites.actor(req);
265      var old = require(id);
266      var pet = toPet(body);
267      validate(pet);
268      pet.setId(id);
269      pet.defaultStatus(old.getStatus()).defaultSpecies(old.getSpecies()).defaultTags(old.getTags()).defaultPhoto(old.getPhoto());
270      return ActionResult.success(store().updatePet(pet, actor)).message(f("Saved '%s'", pet.getName()));
271   }
272
273   /**
274    * Deletes a pet.
275    *
276    * @param req The request.
277    * @param id The pet id.
278    * @return The result toast.
279    * @throws NotFound If the pet does not exist.
280    */
281   @RestDelete(path="/{id}")
282   public ActionResult delete(RestRequest req, @Path("id") long id) {
283      var actor = ConsoleWrites.actor(req);
284      var p = require(id);
285      store().deletePet(id, actor);
286      return ActionResult.success(null).message(f("Deleted '%s'", p.getName()));
287   }
288
289   /**
290    * Marks a pet sold.  The Pets page bulk "Mark sold (N)" action calls this per row.
291    *
292    * @param req The request.
293    * @param id The pet id.
294    * @return The result toast, carrying the updated pet.
295    * @throws NotFound If the pet does not exist.
296    * @throws Conflict If it is already sold.
297    */
298   @RestPost(path="/{id}/sell")
299   public ActionResult sell(RestRequest req, @Path("id") long id) {
300      var actor = ConsoleWrites.actor(req);
301      var p = require(id);
302      if (p.getStatus() == PetStatus.SOLD)
303         throw new Conflict("Pet '%s' is already '%s'", id, p.getStatus());
304      // Update a copy: the live pet must not change unless the store accepts the write.
305      var sold = new Pet().setId(p.getId()).setSpecies(p.getSpecies()).setName(p.getName()).setPrice(p.getPrice())
306         .setTags(p.getTags()).setStatus(PetStatus.SOLD).setPhoto(p.getPhoto());
307      return ActionResult.success(store().updatePet(sold, actor)).message(f("Sold '%s'", p.getName()));
308   }
309
310   /**
311    * Stages an inline edit for review on the Pending changes page.  The pet itself is not changed until the change is applied.
312    *
313    * <p>
314    * {@link PendingChanges#stage} owns which fields are stageable and its messages.  The photo is deliberately not
315    * stageable: the pet detail Photo tab edits it directly through the API's own {@code PUT /petstore/pets/{id}/photo}.
316    *
317    * @param req The request.
318    * @param id The pet id.
319    * @param body {@code {field, value}}, or the inline-edit envelope {@code {fields:{<field>:value}}} with exactly one field.
320    * @return {@code success} carrying the new {@link PendingChange}.
321    * @throws BadRequest If the field is missing or not stageable, or the value is invalid.
322    * @throws NotFound If the pet does not exist.
323    */
324   @RestPost(path="/{id}/stage")
325   public ActionResult stage(RestRequest req, @Path("id") long id, @Content JsonMap body) {
326      var actor = ConsoleWrites.actor(req);
327      String field;
328      String value;
329      // The 'edit' column renderer commits {fields:{<column>:value}} (plus its dialog envelope keys) through the row action.
330      var fields = body.getMap("fields");
331      if (fields != null) {
332         if (fields.size() != 1)
333            throw new BadRequest("Exactly one field can be staged at a time; got '%s'", fields.size());
334         field = fields.keySet().iterator().next();
335         value = fields.getString(field);
336      } else {
337         field = body.getString("field");
338         value = body.getString("value");
339      }
340      if (ib(field))
341         throw new BadRequest("Missing field to stage");
342      try {
343         var c = store().pendingChanges().stage(id, field, value, ConsoleWrites.author(actor));
344         return ActionResult.success(c).message(f("Staged '%s'", c.getSummary()));
345      } catch (PetstoreNotFoundException e) {
346         throw new NotFound(e.getMessage());
347      } catch (IllegalArgumentException e) {
348         throw new BadRequest(e.getMessage());
349      }
350   }
351
352   /**
353    * @param id The pet id.
354    * @return This pet's orders (the related list), by id.
355    * @throws NotFound If the pet does not exist.
356    */
357   @RestGet(path="/{id}/orders/rows")
358   public List<Order> orderRows(@Path("id") long id) {
359      require(id);
360      return store().getOrders().stream().filter(x -> x.getPetId() == id).sorted(Comparator.comparingLong(Order::getId)).toList();
361   }
362
363   /**
364    * @param id The pet id.
365    * @return The audit rows for this pet, oldest first.
366    * @throws NotFound If the pet does not exist.
367    */
368   @RestGet(path="/{id}/history/rows")
369   public List<AuditEntry> historyRows(@Path("id") long id) {
370      require(id);
371      var t = String.valueOf(id);
372      return store().getAudit().stream().filter(x -> "Pet".equals(x.getEntity()) && t.equals(x.getEntityId())).toList();
373   }
374
375   /**
376    * The bare pet URL; lands on the first tab.
377    *
378    * @param req The request.
379    * @param id The pet id.
380    * @return A 303 to {@code /console/pets/{id}/summary}.
381    */
382   @RestGet(path="/{id}")
383   public SeeOther detail(RestRequest req, @Path("id") long id) {
384      return new SeeOther().setLocation(req.getUriResolver().resolve("servlet:/" + id + "/summary"));
385   }
386
387   /**
388    * P4, one tab.
389    *
390    * @param req The request (viewer roles).
391    * @param res The response (404 status for the not-found card).
392    * @param id The pet id.
393    * @param tab One of {@link #TABS}.
394    * @return The tab page, or the not-found card with a 404 status.
395    * @throws NotFound If the tab is unknown.
396    */
397   @RestGet(path="/{id}/{tab}")
398   public View detailTab(RestRequest req, RestResponse res, @Path("id") long id, @Path("tab") String tab) {
399      if (! TABS.contains(tab))
400         throw new NotFound("Unknown tab '%s'", tab);
401      return petPage(req, res, id, tab, null);
402   }
403
404   /**
405    * P4 at nav depth 4: the Orders tab with one of this pet's orders selected.
406    *
407    * @param req The request.
408    * @param res The response.
409    * @param id The pet id.
410    * @param orderId The order id.
411    * @return The Orders tab with the order card, or the not-found card with a 404 status if the pet does not exist.
412    * @throws NotFound If the order does not exist or is not this pet's.
413    */
414   @RestGet(path="/{id}/orders/{orderId}")
415   public View detailOrder(RestRequest req, RestResponse res, @Path("id") long id, @Path("orderId") long orderId) {
416      // An unknown pet gets the not-found card, not the order 404.
417      return petPage(req, res, id, "orders", store().getPet(id) == null ? null : requireOrder(id, orderId));
418   }
419
420   /**
421    * @param id The pet id.
422    * @return The Summary card's single row: this pet, as a one-element list (the card is client-mode).
423    * @throws NotFound If the pet does not exist.
424    */
425   @RestGet(path="/{id}/row")
426   public List<Pet> row(@Path("id") long id) {
427      return List.of(require(id));
428   }
429
430   /**
431    * The Orders tab's row-detail GET.
432    *
433    * @param id The pet id.
434    * @param orderId The order id.
435    * @return {@code {contractVersion, fields}} (see {@link RowDetail#response(Object)}).
436    * @throws NotFound If the order does not exist or is not this pet's.
437    */
438   @RestGet(path="/{id}/orders/{orderId}/detail")
439   public JsonMap orderDetail(@Path("id") long id, @Path("orderId") long orderId) {
440      return RowDetail.response(requireOrder(id, orderId));
441   }
442
443   private View petPage(RestRequest req, RestResponse res, long id, String tab, Order order) {
444      var p = store().getPet(id);
445      if (p == null) {
446         // A View, not a thrown NotFound, so the not-found card renders inside the chrome.
447         res.setStatus(404);
448         return FreemarkerView.of("pet-not-found.ftlh").attr("message", f("Unknown pet '%s'", id));
449      }
450      // Node ids must start with a letter, so the pet node is p<id> and the order node o<id>.
451      var nav = order == null ? f("pets/p%s/%s", id, tab) : f("pets/p%s/orders/o%s", id, order.getId());
452      // The API's CSRF token, published by the console boundary on allowed requests; absent means the upload form renders without one.
453      var servletReq = req.getHttpServletRequest();
454      var apiCsrf = servletReq.getAttribute(PetstoreApiBoundary.TOKEN_ATTRIBUTE) instanceof String s ? s : null;
455      if (builder(req))
456         return twin(req, PetsPageBuilders.pet(p, tab, nav, order, ConsoleWrites.roles(req), apiCsrf));
457      var v = FreemarkerView.of("pet.ftlh").attr("pet", p).attr("tab", tab).attr("activeNav", nav)
458         .attr("pageTitle", p.getName()).attr("roles", ConsoleWrites.roles(req));
459      if (apiCsrf != null)
460         v = v.attr("apiCsrf", apiCsrf);
461      return order == null ? v : v.attr("order", order);
462   }
463
464   private Order requireOrder(long id, long orderId) {
465      var o = store().getOrder(orderId);
466      if (o == null || o.getPetId() != id)
467         throw new NotFound("Unknown order '%s'", orderId);
468      return o;
469   }
470
471   /**
472    * @param id The pet id.
473    * @return The live pet.
474    * @throws NotFound If it does not exist.
475    */
476   protected Pet require(long id) {
477      var p = store().getPet(id);
478      if (p == null)
479         throw new NotFound("Unknown pet '%s'", id);
480      return p;
481   }
482
483   /** Unwraps the dialog envelope ({@code fields}) if present; otherwise the body is the pet itself. */
484   private static Pet toPet(JsonMap body) {
485      var fields = body.getMap("fields");
486      var src = fields != null ? fields : body;
487      try {
488         return Json.to(Json.of(src), Pet.class);
489      } catch (ParseException e) {
490         throw new BadRequest("Invalid pet: '%s'", e.getMessage());
491      }
492   }
493
494   private static void validate(Pet p) {
495      if (p.getName() == null || p.getName().isBlank())
496         throw new BadRequest("Name must not be blank");
497      if (Float.isNaN(p.getPrice()) || Float.isInfinite(p.getPrice()) || p.getPrice() < 0)
498         throw new BadRequest("Price '%s' must be a non-negative number", p.getPrice());
499   }
500}