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.pages;
018
019import java.util.*;
020
021import org.apache.juneau.petstore.dto.*;
022import org.apache.juneau.petstore.service.*;
023import org.apache.juneau.console.freemarker.*;
024import org.apache.juneau.console.views.*;
025import org.apache.juneau.console.views.RowAction.*;
026import org.apache.juneau.console.views.TableSpec.*;
027import org.apache.juneau.console.widgets.*;
028
029/**
030 * Builder twin of the Store page (P1, {@code store.ftlh}).
031 *
032 * <h2 class='section'>Example:</h2>
033 * <p class='bjava'>
034 *    <jk>return</jk> <jsm>twin</jsm>(<jv>req</jv>, StorePageBuilders.<jsm>store</jsm>(QuickStats.<jsm>of</jsm>(store())));
035 * </p>
036 */
037@SuppressWarnings({
038   "java:S1192" // Page-definition ids and labels repeat as inline literals by design.
039})
040public final class StorePageBuilders {
041
042   private StorePageBuilders() {}
043
044   /**
045    * The Store page's quick-stat tiles, shared by both render paths.
046    *
047    * <h2 class='section'>Example:</h2>
048    * <p class='bjava'>
049    *    <jk>var</jk> <jv>qs</jv> = QuickStats.<jsm>of</jsm>(<jv>store</jv>);
050    * </p>
051    *
052    * @param available Available pets.
053    * @param pending Pending pets.
054    * @param sold Sold pets.
055    * @param ordersPlaced Placed orders.
056    * @param ordersApproved Approved orders.
057    * @param ordersDelivered Delivered orders.
058    * @param petTotal All pets, the inventory meter's maximum.
059    */
060   public record QuickStats(long available, long pending, long sold, long ordersPlaced, long ordersApproved, long ordersDelivered, long petTotal) {
061
062      /**
063       * Counts the tiles from the store.
064       *
065       * @param store The store.
066       * @return The tiles.
067       */
068      public static QuickStats of(PetStore store) {
069         var pets = store.getPets();
070         var orders = store.getOrders();
071         return new QuickStats(count(pets, PetStatus.AVAILABLE), count(pets, PetStatus.PENDING), count(pets, PetStatus.SOLD),
072            count(orders, OrderStatus.PLACED), count(orders, OrderStatus.APPROVED), count(orders, OrderStatus.DELIVERED), pets.size());
073      }
074
075      private static long count(Collection<Pet> pets, PetStatus status) {
076         return pets.stream().filter(x -> x.getStatus() == status).count();
077      }
078
079      private static long count(Collection<Order> orders, OrderStatus status) {
080         return orders.stream().filter(x -> x.getStatus() == status).count();
081      }
082   }
083
084   /** The store strip: three status tiles, an order breakdown, and an inventory meter (a tile when there are no pets). */
085   private static QuickStat[] storeQuickStats(QuickStats qs) {
086      var inventory = qs.petTotal() > 0
087         ? QuickStat.meter("inventory", "Inventory", qs.available(), qs.petTotal()).text(qs.available() + " of " + qs.petTotal())
088         : QuickStat.of("inventory", "Inventory", "0 of 0");
089      return new QuickStat[] {
090         QuickStat.of("available", "Available", qs.available()),
091         QuickStat.of("pending", "Pending", qs.pending()),
092         QuickStat.of("sold", "Sold", qs.sold()),
093         QuickStat.segmented("orders", "Orders").segment("Placed", qs.ordersPlaced())
094            .segment("Approved", qs.ordersApproved(), StatusTone.INFO).segment("Delivered", qs.ordersDelivered(), StatusTone.SUCCESS),
095         inventory
096      };
097   }
098
099   /**
100    * P1 Store.
101    *
102    * @param qs The quick-stat tiles.
103    * @return The page spec.
104    */
105   public static PageSpec store(QuickStats qs) {
106      return PageSpec.create().tab("store").toolkit("views", "datatables-buttons", "datatables-export").init("/console/dev/cards/petstore-cards.js")
107         .html("welcome", "Welcome to the petstore", """
108            <div class="jc-prose"><p>Browse pets, place orders and review what changed. Every page here is built from the same
109            Juneau console pieces your own app can use.</p>
110            <p data-slot="welcome-note">Signed in as a guest.</p></div>""")
111         .card(SwitcherDef.create("store-sw").style(SwitcherDef.STYLE_SLIDER).initialView("recent")
112            .view("recent", "Recent orders", v -> v.section(SwitcherCards.table(recentOrders(qs))))
113            .view("revenue", "Revenue", v -> v
114               .section("chart", "Chart", ChartDef.line("revenue-chart").src("/console/store/stats/revenue")
115                  .x("day", null, "Day").series("revenue", "Revenue").toCardSpec())
116               .section("data", "Data", dataCard("revenue-data", "/console/store/stats/revenue", "day", "Day", "revenue", "Revenue"))
117               .initialSection("chart"))
118            .view("orders", "Orders", v -> v
119               .section("chart", "Chart", ChartDef.line("orders-trend").src("/console/store/stats/daily")
120                  .x("day", null, "Day").series("placed", "Placed").series("delivered", "Delivered", "ok")
121                  .onClickHref("/console/orders?state=day({day})").toCardSpec())
122               .section("data", "Data", dataCard("orders-data", "/console/store/stats/daily", "day", "Day", "placed", "Placed", "delivered", "Delivered"))
123               .initialSection("chart"))
124            .view("pets", "Pets", v -> v
125               .section("species", "Species", ChartDef.donut("by-species").src("/console/store/stats/species")
126                  .label("species").value("count").center("total").dataTab().toCardSpec())
127               .section("status", "Status", ChartDef.bar("by-status").src("/console/store/stats/status")
128                  .x("status").series("count", "Pets").dataTab().toCardSpec())
129               .section("treemap", "Treemap", ChartDef.treemap("pets-map").src("/console/store/stats/pets")
130                  .groupBy("species", "status").label("name")
131                  .colorBy("status", ChartDef.legendItem("AVAILABLE", "Available", "ok"),
132                     ChartDef.legendItem("PENDING", "Pending", "warning"),
133                     ChartDef.legendItem("SOLD", "Sold", null))
134                  .tileFields("id", "name", "species", "status")
135                  .onClickAction(PetsPageBuilders.editPetAction(OnSuccess.REDRAW)).dataTab().toCardSpec())
136               .initialSection("species"))
137            .view("hours", "Store hours", v -> v.section(CardSpec.html("hours").title("Store hours").src("/console/store/fragments/hours")))
138            .toCardSpec());
139   }
140
141   /** The Recent orders table: ribbon, row details and the quick-stat strip. */
142   private static TableSpec recentOrders(QuickStats qs) {
143      return TableSpec.create("stats").rowType("Order").dataMode(DataMode.CLIENT).dataUrl("/console/store/recent-orders")
144            .detail(RowDetails.order())
145            .columns(
146               Column.create("id").label("Order").href("/console/pets/{petId}/orders/{id}"),
147               Column.create("petId").label("Pet").href("/console/pets/{petId}/summary"),
148               Column.create("shipDate").label("Ship date").render("date"),
149               Column.create("status").label("Status").render(PillRenders.orderStatus()))
150            .columnConfig(true)
151            .ribbon(Ribbons.standard()
152               .create(RibbonItem.dialog("new-order").title("+ New order").symbol("plus")
153                  .form("/console/orders/new-form").endpoint("/console/orders").method(Method.POST).onSuccess(OnSuccess.REDRAW))
154               .export("excel", "pdf")
155               .build())
156            .quickStats("store", storeQuickStats(qs));
157   }
158
159   /** A datatables card for a nested switcher view: client-side rows from {@code dataUrl}, one plain column per {@code key,label} pair. */
160   private static CardSpec dataCard(String id, String dataUrl, String...keyLabelPairs) {
161      var columns = new ArrayList<Map<String,Object>>();
162      for (var i = 0; i < keyLabelPairs.length; i += 2)
163         columns.add(new LinkedHashMap<>(Map.of("key", keyLabelPairs[i], "label", keyLabelPairs[i + 1])));
164      return CardSpec.of("datatables", id).body("dataMode", "client").body("dataUrl", dataUrl).body("columns", columns);
165   }
166}