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.console.views;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022import java.util.function.*;
023
024import org.apache.juneau.console.*;
025import org.apache.juneau.marshall.collections.*;
026import org.apache.juneau.marshall.marshaller.Json;
027
028/**
029 * Row-detail panel for a table: the per-row GET endpoint, title template, icon and the row-detail region.
030 *
031 * <p>
032 * {@link #CONTRACT_VERSION} and {@link #response(Object)} describe the JSON that endpoint returns.
033 *
034 * <h2 class='section'>Example:</h2>
035 * <p class='bjava'>
036 *    <jv>table</jv>.detail(RowDetail.<jsm>create</jsm>(<js>"/rest/work/data/{id}"</js>)
037 *       .title(<js>"{workId}"</js>).icon(<js>"search"</js>)
038 *       .region(RegionDef.<jsm>create</jsm>(<js>"work-detail"</js>).populate(<js>"work-detail"</js>)
039 *          .allowPopulators(<js>"work-detail"</js>)));
040 *
041 *    <jc>// The matching endpoint:</jc>
042 *    <ja>@RestGet</ja>(path=<js>"/data/{id}"</js>)
043 *    <jk>public</jk> JsonMap detail(<ja>@Path</ja> String <jv>id</jv>) {
044 *       <jk>return</jk> RowDetail.<jsm>response</jsm>(<jv>store</jv>.fields(<jv>id</jv>));
045 *    }
046 * </p>
047 *
048 * @since 10.0.0
049 */
050@SuppressWarnings({
051   "java:S1192", // Map keys read more clearly inline than as constants.
052   "java:S3776" // Branching is inherent to toMap() and tabModelMap(), which serialize many optional settings.
053})
054public final class RowDetail implements Handled<RowDetail> {
055
056   /** The contract version for the detail GET response (the card fragment itself carries no version). */
057   public static final String CONTRACT_VERSION = "1";
058
059   private final String endpoint;
060   private final String mode;
061   private final Class<?> beanType;
062   private final Function<String,?> lookup;
063   private String key;
064   private String basePath = "";
065   private String title;
066   private String icon;
067   private RegionDef region;
068   private boolean tabModel;
069   private int columns;
070   private DetailTab.Cache cache = DetailTab.Cache.PER_ROW;
071   private String countsEndpoint;
072   private final List<RowAction> actions = new ArrayList<>();
073   private final List<DetailTab> tabs = new ArrayList<>();
074   private final List<String> narrowedFields = new ArrayList<>();
075   private final Map<String,String> labels = new LinkedHashMap<>();
076   private final ModelBlock model;
077   /** Default field sets and labels resolved against each owning table, keyed by table id; shared by every copy. */
078   private final Map<String,Resolved> resolved;
079
080   private static final class Resolved {
081      final List<String> fields = new ArrayList<>();
082      final Map<String,String> labels = new LinkedHashMap<>();
083   }
084
085   private RowDetail(String endpoint, String mode, Class<?> beanType, Function<String,?> lookup) {
086      this(endpoint, mode, beanType, lookup, new java.util.concurrent.ConcurrentHashMap<>());
087   }
088
089   private RowDetail(String endpoint, String mode, Class<?> beanType, Function<String,?> lookup, Map<String,Resolved> resolved) {
090      this.endpoint = endpoint;
091      this.mode = mode;
092      this.beanType = beanType;
093      this.lookup = lookup;
094      this.tabModel = mode != null;
095      this.resolved = resolved;
096      this.model = new ModelBlock("rowdetail", modelId(endpoint, beanType));
097   }
098
099   private static String modelId(String endpoint, Class<?> beanType) {
100      if (endpoint != null)
101         return endpoint;
102      return beanType != null ? beanType.getSimpleName() : "inline";
103   }
104
105   @Override /* Handled */
106   public ModelBlock modelBlock() { return model; }
107
108   @Override /* Handled */
109   public RowDetail self() { return this; }
110
111   /**
112    * Starts a row-detail definition for the given per-row GET endpoint.
113    *
114    * @param endpoint A same-origin path template carrying the literal {@code {id}} row-id placeholder (the client substitutes only that), e.g. {@code "/rest/work/data/{id}"}.
115    *    Must not be <jk>null</jk> or blank.
116    * @return A new {@link RowDetail}.
117    * @throws IllegalArgumentException If {@code endpoint} is not a same-origin path with the literal {@code {id}} placeholder.
118    */
119   public static RowDetail create(String endpoint) {
120      if (! RegionDef.isSafeDetailEndpoint(endpoint) || ! endpoint.contains("{id}"))
121         throw iaex("RowDetail endpoint '%s' is not a safe detail endpoint (same-origin path with an {id} placeholder).", endpoint);
122      return new RowDetail(endpoint, null, null, null);
123   }
124
125   /**
126    * Starts a tabbed detail fed from the clicked row's own data, with no server round trip.
127    *
128    * <p>
129    * The row data includes columns hidden by default.  A column that must not reach the browser must not be in the
130    * rows endpoint.
131    *
132    * @return A new {@link RowDetail}.
133    */
134   public static RowDetail inline() {
135      return new RowDetail(null, "inline", null, null);
136   }
137
138   /**
139    * Starts a tabbed detail served by {@link RowDetailMixin} from a bean.
140    *
141    * @param <T> The bean type.
142    * @param type The bean class; only its readable, non-ignored properties can be served.
143    * @param lookup Finds the bean for a row id, or returns <jk>null</jk> when there is none.
144    * @return A new {@link RowDetail}.
145    */
146   public static <T> RowDetail fromBean(Class<T> type, Function<String,T> lookup) {
147      if (type == null || lookup == null)
148         throw iaex("RowDetail.fromBean needs a type and a lookup.");
149      var d = new RowDetail(null, "bean", type, lookup);
150      d.key = decapitalise(type.getSimpleName());
151      return d;
152   }
153
154   private static String decapitalise(String s) {
155      return s.isEmpty() ? s : Character.toLowerCase(s.charAt(0)) + s.substring(1);
156   }
157
158   /**
159    * Returns an independent copy, so a shared instance can be attached to several tables.
160    *
161    * @return The copy.
162    */
163   public RowDetail copy() {
164      var c = new RowDetail(endpoint, mode, beanType, lookup, resolved);
165      c.key = key;
166      c.basePath = basePath;
167      c.title = title;
168      c.icon = icon;
169      c.region = region;
170      c.tabModel = tabModel;
171      c.columns = columns;
172      c.cache = cache;
173      c.countsEndpoint = countsEndpoint;
174      c.actions.addAll(actions);
175      c.tabs.addAll(tabs);
176      c.narrowedFields.addAll(narrowedFields);
177      c.labels.putAll(labels);
178      c.model.addAll(model);
179      return c;
180   }
181
182   /**
183    * Adds a header action, shown right-aligned in the detail header.
184    *
185    * @param a The action.
186    * @return This object.
187    */
188   public RowDetail action(RowAction a) {
189      useTabModel();
190      actions.add(a);
191      return this;
192   }
193
194   /**
195    * Adds a tab.
196    *
197    * @param t The tab.  Its id must be unique in this detail.
198    * @return This object.
199    */
200   public RowDetail tab(DetailTab t) {
201      useTabModel();
202      tabs.add(t);
203      return this;
204   }
205
206   /**
207    * Adds a fields tab.
208    *
209    * @param tabTitle The tab title.
210    * @param fields The row fields shown.
211    * @return This object.
212    */
213   public RowDetail section(String tabTitle, String...fields) {
214      return tab(DetailTab.fields(tabTitle, fields));
215   }
216
217   /**
218    * Narrows the fields the generated Details tab shows.
219    *
220    * @param names The field names.
221    * @return This object.
222    */
223   public RowDetail fields(String...names) {
224      useTabModel();
225      narrowedFields.addAll(Arrays.asList(names));
226      return this;
227   }
228
229   /**
230    * Sets the default grid column count of the fields tabs.
231    *
232    * @param n The count, 1 to 4 (default 2).
233    * @return This object.
234    */
235   public RowDetail columns(int n) {
236      if (n < 1 || n > 4)
237         throw iaex("RowDetail columns must be 1 to 4, was %s.", n);
238      useTabModel();
239      columns = n;
240      return this;
241   }
242
243   /**
244    * Sets an explicit label for a field.  It wins over the column label and the bean metadata.
245    *
246    * @param field The field name.
247    * @param text The label.
248    * @return This object.
249    */
250   public RowDetail label(String field, String text) {
251      useTabModel();
252      labels.put(field, text);
253      return this;
254   }
255
256   /**
257    * Sets a dedicated endpoint for the tab counts.  Without it the counts ride the detail response.
258    *
259    * @param value A same-origin path template carrying {@code {id}}.
260    * @return This object.
261    */
262   public RowDetail counts(String value) {
263      if (! RegionDef.isSafeDetailEndpoint(value) || ! value.contains("{id}"))
264         throw iaex("RowDetail counts endpoint '%s' is not a safe detail endpoint (same-origin path with an {id} placeholder).", value);
265      useTabModel();
266      countsEndpoint = value;
267      return this;
268   }
269
270   /**
271    * Sets how tab content is cached.
272    *
273    * @param value The policy (default {@link DetailTab.Cache#PER_ROW}).
274    * @return This object.
275    */
276   public RowDetail cache(DetailTab.Cache value) {
277      useTabModel();
278      cache = value;
279      return this;
280   }
281
282   /**
283    * Sets the URL key of a bean-backed detail (default: the decapitalised simple class name).
284    *
285    * @param value The key.
286    * @return This object.
287    */
288   public RowDetail key(String value) {
289      key = value;
290      return this;
291   }
292
293   /**
294    * Sets the path of the resource that serves a bean-backed detail through {@link RowDetailMixin}.
295    *
296    * <p>
297    * The endpoint becomes <c>{basePath}/row-detail/{key}/{id}</c>.  Without it the endpoint is relative to the site root.
298    *
299    * @param value A same-origin path with no placeholders, e.g. {@code "/console/pets"}.
300    * @return This object.
301    * @throws IllegalArgumentException If {@code value} is not a safe same-origin path.
302    */
303   public RowDetail basePath(String value) {
304      if (value == null || value.contains("{") || ! RegionDef.isSafeDetailEndpoint(value))
305         throw iaex("RowDetail basePath '%s' is not a safe same-origin path.", value);
306      basePath = value.endsWith("/") ? value.substring(0, value.length() - 1) : value;
307      return this;
308   }
309
310   /** @return The bean class of a bean-backed detail, or <jk>null</jk>. */
311   Class<?> beanType() { return beanType; }
312
313   /** @return The bean lookup of a bean-backed detail, or <jk>null</jk>. */
314   @SuppressWarnings({
315      "java:S1452" // The lookup result type is the caller's bean type, unknown to this class.
316   })
317   Function<String,?> lookup() { return lookup; }
318
319   /** @return The tabs declared on this detail. */
320   List<DetailTab> tabList() { return List.copyOf(tabs); }
321
322   /** @return The title template, or <jk>null</jk>. */
323   String titleTemplate() { return title; }
324
325   /** @return The field set resolved against the owning tables, in order and without repeats (empty until a table has been built). */
326   List<String> resolvedFields() {
327      var out = new LinkedHashSet<String>();
328      for (var r : resolved.values())
329         out.addAll(r.fields);
330      return List.copyOf(out);
331   }
332
333   /** @return The labels resolved against the owning table. */
334   Map<String,String> resolvedLabels() {
335      var m = new LinkedHashMap<String,String>();
336      for (var r : resolved.values())
337         r.labels.forEach(m::putIfAbsent);
338      labels.forEach(m::put);
339      return m;
340   }
341
342   /** @return The bean property names that may be served: readable and not ignored. */
343   Set<String> servableProperties() {
344      return eligibleBeanProperties();
345   }
346
347   /** @return The URL key of a bean-backed detail, or <jk>null</jk>. */
348   String key() {
349      return key;
350   }
351
352   private void useTabModel() {
353      if (region != null)
354         throw isex("RowDetail with a region cannot use tabs or header actions.");
355      tabModel = true;
356   }
357
358   /**
359    * Resolves a field label: explicit, then column, then bean metadata, then the humanised name.
360    *
361    * @param field The field name.
362    * @param explicit The label set with {@link #label(String,String)}, or <jk>null</jk>.
363    * @param columnLabel The table column's label, or <jk>null</jk>.
364    * @param beanLabel The bean metadata label, or <jk>null</jk>.
365    * @return The label.
366    */
367   static String resolveLabel(String field, String explicit, String columnLabel, String beanLabel) {
368      if (explicit != null)
369         return explicit;
370      if (columnLabel != null)
371         return columnLabel;
372      if (beanLabel != null)
373         return beanLabel;
374      return humanise(field);
375   }
376
377   /** Turns {@code birthDate} or {@code birth_date} into {@code Birth date}. */
378   static String humanise(String field) {
379      var s = field.replaceAll("([a-z0-9])([A-Z])", "$1 $2").replaceAll("[_-]+", " ").trim().toLowerCase(Locale.ROOT);
380      return s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
381   }
382
383   /**
384    * Sets the detail panel's title template.
385    *
386    * @param template A row-data interpolation template, e.g. {@code "{workId}"}.  Can be <jk>null</jk> to unset.
387    * @return This object.
388    */
389   public RowDetail title(String template) {
390      title = template;
391      return this;
392   }
393
394   /**
395    * Sets the detail panel's icon.
396    *
397    * @param name A glyph name resolved by the shared icon registry.  Can be <jk>null</jk> to unset.
398    * @return This object.
399    */
400   public RowDetail icon(String name) {
401      icon = name;
402      return this;
403   }
404
405   /**
406    * Sets the detail panel's region.
407    *
408    * @param value The region.  Can be <jk>null</jk> to clear it (a header-only panel).
409    *    Its {@link RegionDef#type} defaults to {@link RegionDef#TYPE_ROW_DETAIL} and its
410    *    {@link RegionDef#dataUrl} defaults to this detail's own endpoint, applied at {@link #toMap()} time onto a
411    *    copy; this method never mutates {@code value} itself.
412    * @return This object.
413    */
414   public RowDetail region(RegionDef value) {
415      if (tabModel)
416         throw isex("RowDetail with tabs or header actions cannot have a region.");
417      region = value;
418      return this;
419   }
420
421   /**
422    * Builds the detail GET endpoint's own JSON response (not the card fragment).
423    *
424    * @param fields The row's detail fields, a map (or bean) in whatever shape the detail region's populator/renderer expects.
425    * @return {@code {contractVersion, fields}}.
426    */
427   public static JsonMap response(Object fields) {
428      var m = new JsonMap();
429      m.put("contractVersion", CONTRACT_VERSION);
430      m.put("fields", fields);
431      return m;
432   }
433
434   /**
435    * Builds this detail's card-body entry: {@code {endpoint, title?, icon?, region?}}.
436    *
437    * <p>
438    * The region is optional: a detail with none is a header-only panel (the client fills the {@code title}/{@code icon}
439    * header from the endpoint's {@code fields}) and the entry carries no {@code region} key.
440    *
441    * <p>
442    * When a region is set, builds from a copy: reads {@link RegionDef#toContractMap()} off the caller's {@link #region(RegionDef) region}
443    * into a fresh map, applies the {@code type}/{@code dataUrl} defaults onto that copy, and strips the copy's
444    * {@code contractVersion} key (a card fragment never nests a {@code contractVersion}, since the client stamps it
445    * on mount).  The caller's {@link RegionDef} instance is never written to.
446    *
447    * @return The detail entry.
448    */
449   public JsonMap toMap() {
450      return tabModel ? tabModelMap() : plainMap();
451   }
452
453   /**
454    * Builds the detail entry resolved against the owning table: the default field set, labels and row id.
455    *
456    * @param tableId The table id, for error messages.
457    * @param cols The table's columns.
458    * @param rowIdField The table's row-id field (explicit, else the selection's), or <jk>null</jk>.
459    * @return The detail entry.
460    * @throws IllegalStateException If a tabbed detail has no resolvable row id field.
461    */
462   JsonMap toMap(String tableId, List<Column> cols, String rowIdField) {
463      if (! tabModel)
464         return plainMap();
465      var names = cols.stream().map(Column::name).toList();
466      var idField = rowIdField;
467      if (idField == null && names.contains("id"))
468         idField = "id";
469      if (idField == null && names.contains("name"))
470         idField = "name";
471      if (idField == null)
472         throw isex("table '%s' has a detail but no resolvable row id field.", tableId);
473      var c = copy();
474      if (c.narrowedFields.isEmpty()) {
475         var eligible = eligibleBeanProperties();
476         for (var col : cols)
477            if (beanType == null || eligible.contains(col.name()))
478               c.narrowedFields.add(col.name());
479      }
480      for (var col : cols)
481         if (col.label() != null && ! c.labels.containsKey(col.name()))
482            c.labels.put(col.name(), col.label());
483      var r = new Resolved();
484      r.fields.addAll(c.narrowedFields);
485      r.labels.putAll(c.labels);
486      resolved.put(tableId, r);
487      return c.tabModelMap();
488   }
489
490   private Set<String> eligibleBeanProperties() {
491      if (beanType == null)
492         return Set.of();
493      var bm = org.apache.juneau.marshall.MarshallingContext.DEFAULT.getBeanMeta(beanType);
494      var out = new LinkedHashSet<String>();
495      if (bm != null)
496         for (var pm : bm.getProperties().values())
497            if (pm.canRead())
498               out.add(pm.getName());
499      return out;
500   }
501
502   private JsonMap tabModelMap() {
503      var m = new JsonMap();
504      if (mode != null)
505         m.put("mode", mode);
506      var ep = endpoint;
507      if (ep == null && "bean".equals(mode))
508         ep = basePath + "/row-detail/" + key + "/{id}";
509      if (ep != null)
510         m.put("endpoint", ep);
511      if (title != null)
512         m.put("title", title);
513      if (icon != null)
514         m.put("icon", icon);
515      if (columns != 0)
516         m.put("columns", columns);
517      if (cache != DetailTab.Cache.PER_ROW)
518         m.put("cache", cache.wire());
519      if (countsEndpoint != null)
520         m.put("countsEndpoint", countsEndpoint);
521      if (! labels.isEmpty())
522         m.put("labels", new LinkedHashMap<>(labels));
523      var all = new ArrayList<Map<String,Object>>();
524      for (var a : actions) {
525         a.validateLink();
526         if (a.href == null && ib(a.label) || ib(a.label) && ! ib(a.icon))
527            throw iaex("RowDetail action '%s' needs a label (an icon-only action has no accessible name).", a.id);
528         var am = new LinkedHashMap<String,Object>(Json.to(Json.of(a), Map.class));
529         am.put("type", a.href != null ? "link" : "row-action");
530         all.add(am);
531      }
532      var mm = model.toMap();
533      if (mm != null && mm.get("actions") instanceof List<?> hl)
534         for (var h : hl)
535            all.add(castMap(h));
536      if (! all.isEmpty())
537         m.put("actions", all);
538      var tl = new ArrayList<DetailTab>(tabs);
539      if (tl.isEmpty())
540         tl.add(DetailTab.autoFields("Details", narrowedFields).id("details"));
541      var ids = new HashSet<String>();
542      var tms = new ArrayList<Map<String,Object>>();
543      var viewIds = new HashSet<String>();
544      for (var t : tl) {
545         var tm = t.toMap();
546         if (tm.get("nested") instanceof Map<?,?> nm && ! viewIds.add((String)((Map<?,?>)nm.get("view")).get("id")))
547            throw iaex("RowDetail has two nested tables with view id '%s'.", ((Map<?,?>)nm.get("view")).get("id"));
548         if (! ids.add((String)tm.get("id")))
549            throw iaex("RowDetail has two tabs with id '%s'.", tm.get("id"));
550         tms.add(tm);
551      }
552      m.put("tabs", tms);
553      if (mm != null) {
554         var rest = new LinkedHashMap<>(mm);
555         rest.remove("actions");
556         if (! rest.isEmpty())
557            m.put("model", rest);
558      }
559      return m;
560   }
561
562   @SuppressWarnings("unchecked") // Handler action maps are string-keyed by construction.
563   private static Map<String,Object> castMap(Object o) {
564      return (Map<String,Object>)o;
565   }
566
567   private JsonMap plainMap() {
568      var m = new JsonMap();
569      m.put("endpoint", endpoint);
570      if (title != null)
571         m.put("title", title);
572      if (icon != null)
573         m.put("icon", icon);
574      if (region != null) {
575         var regionMap = new LinkedHashMap<>(region.toContractMap());
576         regionMap.remove("contractVersion");
577         regionMap.putIfAbsent("type", RegionDef.TYPE_ROW_DETAIL);
578         regionMap.putIfAbsent("dataUrl", endpoint);
579         m.put("region", regionMap);
580      }
581      var mm = model.toMap();
582      if (mm != null) {
583         mm = new LinkedHashMap<>(mm);
584         var modelActions = mm.remove("actions");
585         if (modelActions != null)
586            m.put("actions", modelActions);
587         if (! mm.isEmpty())
588            m.put("model", mm);
589      }
590      return m;
591   }
592}